pendra 0.12.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -370,6 +370,12 @@ interface ChatCompletionCreateParams {
370
370
  * rather than filtering lines — so a frame the server tags with a named
371
371
  * `event:` is dropped in one piece instead of having its `data:` line mistaken
372
372
  * for a chat chunk (issue #1398).
373
+ *
374
+ * Each surviving frame goes through {@link parseStreamFrame}, which throws on
375
+ * the API's in-band `{"error": …}` failure reports and on a frame that isn't a
376
+ * chunk. The error frames used to be yielded *as* chunks (`JSON.parse` succeeds
377
+ * on them), so a worker crash surfaced as a `TypeError` on `chunk.choices[0]`
378
+ * rather than as something a caller could catch and read (issue #2252).
373
379
  */
374
380
  declare class Stream implements AsyncIterable<ChatCompletionChunk> {
375
381
  private reader;
@@ -729,5 +735,58 @@ declare class AuthenticationError extends APIStatusError {
729
735
  declare class RateLimitError extends APIStatusError {
730
736
  constructor(message?: string);
731
737
  }
738
+ /**
739
+ * Raised when a response arrives but isn't the shape the SDK expects.
740
+ *
741
+ * A server or proxy problem, not a transport one: the request reached Pendra
742
+ * and came back, but the body could not be read as the documented type — a 200
743
+ * missing a required field, a captive-portal HTML page from a corporate proxy,
744
+ * a truncated body.
745
+ *
746
+ * Deliberately NOT an `APIConnectionError`: retrying a response that will never
747
+ * parse just burns the retry budget, so callers that retry on connection
748
+ * failures should let this one through. `body` holds a short excerpt of what
749
+ * actually came back.
750
+ */
751
+ declare class APIResponseValidationError extends APIError {
752
+ /** How much of the offending body to keep in the message. */
753
+ static readonly BODY_EXCERPT_CHARS = 200;
754
+ readonly body: string | undefined;
755
+ constructor(message: string, options?: {
756
+ status?: number;
757
+ body?: string;
758
+ });
759
+ }
760
+ /**
761
+ * Raised when a stream reports a failure in-band, after HTTP 200.
762
+ *
763
+ * A streaming response commits its status line before the worker has done any
764
+ * work, so anything that goes wrong afterwards — the worker crashing, the
765
+ * request timing out, the fleet being at capacity — can only be described in
766
+ * the body. The API sends `data: {"error": {…}}` followed by `data: [DONE]`,
767
+ * and this error is how the SDK surfaces that instead of ending the stream as
768
+ * though it had succeeded.
769
+ *
770
+ * `requestId` and `workerId` identify the failed inference to Pendra support.
771
+ *
772
+ * Note this extends `APIError`, not `APIStatusError`, because the API omits
773
+ * `code` on some frames (the timeout and the generic catch-all) — so `status`
774
+ * is genuinely optional here, which `APIStatusError`'s always-present `status`
775
+ * cannot express. Check `status` for undefined before comparing it.
776
+ */
777
+ declare class APIStreamError extends APIError {
778
+ readonly type: string | undefined;
779
+ readonly code: number | undefined;
780
+ readonly requestId: string | undefined;
781
+ readonly workerId: string | undefined;
782
+ readonly workerName: string | undefined;
783
+ constructor(message: string, options?: {
784
+ type?: string;
785
+ code?: number;
786
+ requestId?: string;
787
+ workerId?: string;
788
+ workerName?: string;
789
+ });
790
+ }
732
791
 
733
- export { APIConnectionError, APIError, APIStatusError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
792
+ export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, APIStreamError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
package/dist/index.d.ts CHANGED
@@ -370,6 +370,12 @@ interface ChatCompletionCreateParams {
370
370
  * rather than filtering lines — so a frame the server tags with a named
371
371
  * `event:` is dropped in one piece instead of having its `data:` line mistaken
372
372
  * for a chat chunk (issue #1398).
373
+ *
374
+ * Each surviving frame goes through {@link parseStreamFrame}, which throws on
375
+ * the API's in-band `{"error": …}` failure reports and on a frame that isn't a
376
+ * chunk. The error frames used to be yielded *as* chunks (`JSON.parse` succeeds
377
+ * on them), so a worker crash surfaced as a `TypeError` on `chunk.choices[0]`
378
+ * rather than as something a caller could catch and read (issue #2252).
373
379
  */
374
380
  declare class Stream implements AsyncIterable<ChatCompletionChunk> {
375
381
  private reader;
@@ -729,5 +735,58 @@ declare class AuthenticationError extends APIStatusError {
729
735
  declare class RateLimitError extends APIStatusError {
730
736
  constructor(message?: string);
731
737
  }
738
+ /**
739
+ * Raised when a response arrives but isn't the shape the SDK expects.
740
+ *
741
+ * A server or proxy problem, not a transport one: the request reached Pendra
742
+ * and came back, but the body could not be read as the documented type — a 200
743
+ * missing a required field, a captive-portal HTML page from a corporate proxy,
744
+ * a truncated body.
745
+ *
746
+ * Deliberately NOT an `APIConnectionError`: retrying a response that will never
747
+ * parse just burns the retry budget, so callers that retry on connection
748
+ * failures should let this one through. `body` holds a short excerpt of what
749
+ * actually came back.
750
+ */
751
+ declare class APIResponseValidationError extends APIError {
752
+ /** How much of the offending body to keep in the message. */
753
+ static readonly BODY_EXCERPT_CHARS = 200;
754
+ readonly body: string | undefined;
755
+ constructor(message: string, options?: {
756
+ status?: number;
757
+ body?: string;
758
+ });
759
+ }
760
+ /**
761
+ * Raised when a stream reports a failure in-band, after HTTP 200.
762
+ *
763
+ * A streaming response commits its status line before the worker has done any
764
+ * work, so anything that goes wrong afterwards — the worker crashing, the
765
+ * request timing out, the fleet being at capacity — can only be described in
766
+ * the body. The API sends `data: {"error": {…}}` followed by `data: [DONE]`,
767
+ * and this error is how the SDK surfaces that instead of ending the stream as
768
+ * though it had succeeded.
769
+ *
770
+ * `requestId` and `workerId` identify the failed inference to Pendra support.
771
+ *
772
+ * Note this extends `APIError`, not `APIStatusError`, because the API omits
773
+ * `code` on some frames (the timeout and the generic catch-all) — so `status`
774
+ * is genuinely optional here, which `APIStatusError`'s always-present `status`
775
+ * cannot express. Check `status` for undefined before comparing it.
776
+ */
777
+ declare class APIStreamError extends APIError {
778
+ readonly type: string | undefined;
779
+ readonly code: number | undefined;
780
+ readonly requestId: string | undefined;
781
+ readonly workerId: string | undefined;
782
+ readonly workerName: string | undefined;
783
+ constructor(message: string, options?: {
784
+ type?: string;
785
+ code?: number;
786
+ requestId?: string;
787
+ workerId?: string;
788
+ workerName?: string;
789
+ });
790
+ }
732
791
 
733
- export { APIConnectionError, APIError, APIStatusError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
792
+ export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, APIStreamError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
package/dist/index.js CHANGED
@@ -32,7 +32,9 @@ var index_exports = {};
32
32
  __export(index_exports, {
33
33
  APIConnectionError: () => APIConnectionError,
34
34
  APIError: () => APIError,
35
+ APIResponseValidationError: () => APIResponseValidationError,
35
36
  APIStatusError: () => APIStatusError,
37
+ APIStreamError: () => APIStreamError,
36
38
  AuthenticationError: () => AuthenticationError,
37
39
  Pendra: () => Pendra,
38
40
  PrivateInferenceError: () => PrivateInferenceError,
@@ -75,6 +77,33 @@ var RateLimitError = class extends APIStatusError {
75
77
  this.name = "RateLimitError";
76
78
  }
77
79
  };
80
+ var _APIResponseValidationError = class _APIResponseValidationError extends APIError {
81
+ constructor(message, options = {}) {
82
+ const { status, body } = options;
83
+ let text = message;
84
+ if (body) {
85
+ const max = _APIResponseValidationError.BODY_EXCERPT_CHARS;
86
+ text = `${message} (body: ${body.slice(0, max)}${body.length > max ? "\u2026" : ""})`;
87
+ }
88
+ super(text, status);
89
+ this.name = "APIResponseValidationError";
90
+ this.body = body;
91
+ }
92
+ };
93
+ /** How much of the offending body to keep in the message. */
94
+ _APIResponseValidationError.BODY_EXCERPT_CHARS = 200;
95
+ var APIResponseValidationError = _APIResponseValidationError;
96
+ var APIStreamError = class extends APIError {
97
+ constructor(message, options = {}) {
98
+ super(message, typeof options.code === "number" ? options.code : void 0);
99
+ this.name = "APIStreamError";
100
+ this.type = options.type;
101
+ this.code = options.code;
102
+ this.requestId = options.requestId;
103
+ this.workerId = options.workerId;
104
+ this.workerName = options.workerName;
105
+ }
106
+ };
78
107
 
79
108
  // src/resources/audio/transcriptions.ts
80
109
  var MAX_FILE_SIZE = 25 * 1024 * 1024;
@@ -204,6 +233,89 @@ var Audio = class {
204
233
  }
205
234
  };
206
235
 
236
+ // src/_parsing.ts
237
+ function asString(v) {
238
+ return typeof v === "string" ? v : void 0;
239
+ }
240
+ function throwIfInBandError(parsed) {
241
+ if (typeof parsed !== "object" || parsed === null) return;
242
+ const err = parsed.error;
243
+ if (typeof err !== "object" || err === null || Array.isArray(err)) return;
244
+ const e = err;
245
+ throw new APIStreamError(
246
+ asString(e.message) ?? "The server reported an error mid-stream",
247
+ {
248
+ type: asString(e.type),
249
+ code: typeof e.code === "number" ? e.code : void 0,
250
+ requestId: asString(e.request_id),
251
+ workerId: asString(e.worker_id),
252
+ workerName: asString(e.worker_name)
253
+ }
254
+ );
255
+ }
256
+ function isChunkShaped(parsed) {
257
+ if (typeof parsed !== "object" || parsed === null) return false;
258
+ const c = parsed;
259
+ return typeof c.id === "string" && typeof c.model === "string" && Array.isArray(c.choices);
260
+ }
261
+ function parseStreamFrame(data, label = "Stream frame") {
262
+ let parsed;
263
+ try {
264
+ parsed = JSON.parse(data);
265
+ } catch {
266
+ throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });
267
+ }
268
+ throwIfInBandError(parsed);
269
+ if (!isChunkShaped(parsed)) {
270
+ throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
271
+ body: data
272
+ });
273
+ }
274
+ return parsed;
275
+ }
276
+ function completionFrom(parsed, body, status) {
277
+ if (typeof parsed !== "object" || parsed === null) {
278
+ throw new APIResponseValidationError("Response was not a chat completion", { status, body });
279
+ }
280
+ const c = parsed;
281
+ if (typeof c.id !== "string" || typeof c.model !== "string" || !Array.isArray(c.choices)) {
282
+ throw new APIResponseValidationError("Response was not a chat completion", { status, body });
283
+ }
284
+ return parsed;
285
+ }
286
+ async function parseCompletion(response) {
287
+ const body = await response.text();
288
+ let parsed;
289
+ try {
290
+ parsed = JSON.parse(body);
291
+ } catch {
292
+ throw new APIResponseValidationError("Response was not valid JSON", {
293
+ status: response.status,
294
+ body
295
+ });
296
+ }
297
+ return completionFrom(parsed, body, response.status);
298
+ }
299
+ function parseDecryptedCompletion(json, status) {
300
+ let parsed;
301
+ try {
302
+ parsed = JSON.parse(json);
303
+ } catch {
304
+ throw new APIResponseValidationError("Decrypted response was not valid JSON", {
305
+ status,
306
+ body: json
307
+ });
308
+ }
309
+ try {
310
+ return completionFrom(parsed, json, status);
311
+ } catch {
312
+ throw new APIResponseValidationError("Decrypted response was not a chat completion", {
313
+ status,
314
+ body: json
315
+ });
316
+ }
317
+ }
318
+
207
319
  // src/_sse.ts
208
320
  var DEFAULT_EVENT = "message";
209
321
  function fieldValue(line, name) {
@@ -293,10 +405,7 @@ var Stream = class {
293
405
  this.done = true;
294
406
  return;
295
407
  }
296
- try {
297
- yield JSON.parse(data);
298
- } catch {
299
- }
408
+ yield parseStreamFrame(data);
300
409
  }
301
410
  if (readerDone) {
302
411
  this.done = true;
@@ -337,15 +446,16 @@ var EncryptedStream = class {
337
446
  this.done = true;
338
447
  return;
339
448
  }
340
- let parsed;
449
+ let inner;
341
450
  try {
342
- parsed = JSON.parse(data);
451
+ inner = JSON.parse(data).pendra_encrypted;
343
452
  } catch {
344
- continue;
453
+ throw new APIResponseValidationError("Stream frame was not valid JSON", {
454
+ body: data
455
+ });
345
456
  }
346
- const inner = parsed.pendra_encrypted;
347
457
  if (!inner) {
348
- yield parsed;
458
+ yield parseStreamFrame(data);
349
459
  continue;
350
460
  }
351
461
  const plain = this.decryptor.openChunk(inner);
@@ -357,10 +467,7 @@ var EncryptedStream = class {
357
467
  }
358
468
  continue;
359
469
  }
360
- try {
361
- yield JSON.parse(chunkJson);
362
- } catch {
363
- }
470
+ yield parseStreamFrame(chunkJson, "Decrypted stream frame");
364
471
  }
365
472
  if (readerDone) {
366
473
  this.done = true;
@@ -405,7 +512,7 @@ var Completions = class {
405
512
  "/api/v1/chat/completions",
406
513
  { method: "POST", body, headers }
407
514
  );
408
- return await response.json();
515
+ return parseCompletion(response);
409
516
  }
410
517
  async createEncrypted(params, body, headers) {
411
518
  const engine = await this.client._privateEngine();
@@ -428,12 +535,21 @@ var Completions = class {
428
535
  "/api/v1/chat/completions",
429
536
  { method: "POST", body: topLevel, headers }
430
537
  );
431
- const wrapper = await response.json();
538
+ const raw = await response.text();
539
+ let wrapper;
540
+ try {
541
+ wrapper = JSON.parse(raw);
542
+ } catch {
543
+ throw new APIResponseValidationError("Response was not valid JSON", {
544
+ status: response.status,
545
+ body: raw
546
+ });
547
+ }
432
548
  if (!wrapper.pendra_encrypted) {
433
- return wrapper;
549
+ return parseDecryptedCompletion(raw, response.status);
434
550
  }
435
551
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
436
- return JSON.parse(DECODER2.decode(plain));
552
+ return parseDecryptedCompletion(DECODER2.decode(plain), response.status);
437
553
  }
438
554
  };
439
555
 
@@ -667,7 +783,7 @@ var Rerank = class {
667
783
  };
668
784
 
669
785
  // src/version.ts
670
- var VERSION = "0.12.2";
786
+ var VERSION = "0.13.0";
671
787
  var USER_AGENT = `pendra-node/${VERSION}`;
672
788
 
673
789
  // src/_hpke.ts
@@ -1405,7 +1521,9 @@ var index_default = Pendra;
1405
1521
  0 && (module.exports = {
1406
1522
  APIConnectionError,
1407
1523
  APIError,
1524
+ APIResponseValidationError,
1408
1525
  APIStatusError,
1526
+ APIStreamError,
1409
1527
  AuthenticationError,
1410
1528
  Pendra,
1411
1529
  PrivateInferenceError,