pendra 0.17.2 → 0.18.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
@@ -626,6 +626,78 @@ declare class Models {
626
626
  list(): Promise<Model[]>;
627
627
  }
628
628
 
629
+ /** A text part of a multi-part moderation input. */
630
+ interface ModerationTextInput {
631
+ type: "text";
632
+ text: string;
633
+ }
634
+ /** An image part of a multi-part moderation input (a `data:` or `https://` URL). */
635
+ interface ModerationImageURLInput {
636
+ type: "image_url";
637
+ image_url: {
638
+ url: string;
639
+ };
640
+ }
641
+ type ModerationInputPart = ModerationTextInput | ModerationImageURLInput;
642
+ /**
643
+ * What to check: a string (one result), an array of 1 to 32 strings (one
644
+ * result each, in order) or an array of 1 to 32 parts (one result for the
645
+ * combined content). Strings and parts can't be mixed.
646
+ */
647
+ type ModerationInput = string | string[] | ModerationInputPart[];
648
+ interface ModerationCreateParams {
649
+ /** A moderation model id, e.g. `"llama-guard3:1b"`. */
650
+ model: string;
651
+ input: ModerationInput;
652
+ /** Pin to a specific worker (sent as the `X-Pendra-Worker-Id` header). */
653
+ worker_id?: string | null;
654
+ }
655
+ interface ModerationResult {
656
+ /** True when any category is set, including a borderline hit. */
657
+ flagged: boolean;
658
+ /** Only the categories the model checks are present: a missing key means "not checked". */
659
+ categories: Record<string, boolean>;
660
+ /** 1.0 flagged, 0.0 checked and clean, 0.5 a borderline hit. */
661
+ category_scores: Record<string, number>;
662
+ category_applied_input_types: Record<string, Array<"text" | "image">>;
663
+ }
664
+ /** OpenAI-compatible moderation response. */
665
+ interface ModerationResponse {
666
+ id: string;
667
+ model: string;
668
+ results: ModerationResult[];
669
+ /**
670
+ * Pendra's extension block — `pendra?.worker` names the worker that served
671
+ * the request. Absent when the API didn't report one.
672
+ */
673
+ pendra?: PendraExtension | null;
674
+ }
675
+
676
+ declare class Moderations {
677
+ private client;
678
+ constructor(client: Pendra);
679
+ /**
680
+ * Check content with a moderation model installed on one of your workers
681
+ * (OpenAI-compatible).
682
+ *
683
+ * `input` is a string, an array of up to 32 strings (one result each) or an
684
+ * array of up to 32 `text` / `image_url` parts checked together (one
685
+ * result). With private inference turned on, the check is end-to-end
686
+ * encrypted: Pendra sees neither the content nor the verdict.
687
+ *
688
+ * @example
689
+ * ```ts
690
+ * const result = await client.moderations.create({
691
+ * model: "llama-guard3:1b",
692
+ * input: "Hello world",
693
+ * });
694
+ * console.log(result.results[0].flagged);
695
+ * ```
696
+ */
697
+ create(params: ModerationCreateParams): Promise<ModerationResponse>;
698
+ private createEncrypted;
699
+ }
700
+
629
701
  interface RerankCreateParams {
630
702
  model: string;
631
703
  query: string;
@@ -799,9 +871,9 @@ interface PendraOptions {
799
871
  baseURL?: string;
800
872
  timeout?: number;
801
873
  /**
802
- * Enable end-to-end encrypted (private) inference. When `true`, chat and
803
- * embeddings requests are sealed to your org's workload key (TOFU-pinned on
804
- * first use) and the responses are decrypted client-side — Pendra relays only
874
+ * Enable end-to-end encrypted (private) inference. When `true`, inference
875
+ * requests (chat, embeddings, moderations and the rest) are sealed to your
876
+ * org's workload key (TOFU-pinned on first use) and the responses are decrypted client-side — Pendra relays only
805
877
  * ciphertext. Pass `{ pinnedFingerprint }` to hard-pin the org key fingerprint
806
878
  * (required in browser bundles, which cannot use the TOFU key store).
807
879
  *
@@ -822,6 +894,7 @@ declare class Pendra {
822
894
  models: Models;
823
895
  audio: Audio;
824
896
  rerank: Rerank;
897
+ moderations: Moderations;
825
898
  /** @internal Whether end-to-end encrypted inference is enabled for this client. */
826
899
  readonly privateInferenceEnabled: boolean;
827
900
  private _piEngine;
@@ -946,4 +1019,4 @@ declare class APIStreamError extends APIError {
946
1019
  });
947
1020
  }
948
1021
 
949
- export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, type APIStatusErrorOptions, 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, type PendraWorker, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, type SpeechCreateParams, type SpeechResponse, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
1022
+ export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, type APIStatusErrorOptions, 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, type ModerationCreateParams, type ModerationImageURLInput, type ModerationInput, type ModerationInputPart, type ModerationResponse, type ModerationResult, type ModerationTextInput, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, type PendraWorker, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, type SpeechCreateParams, type SpeechResponse, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
package/dist/index.d.ts CHANGED
@@ -626,6 +626,78 @@ declare class Models {
626
626
  list(): Promise<Model[]>;
627
627
  }
628
628
 
629
+ /** A text part of a multi-part moderation input. */
630
+ interface ModerationTextInput {
631
+ type: "text";
632
+ text: string;
633
+ }
634
+ /** An image part of a multi-part moderation input (a `data:` or `https://` URL). */
635
+ interface ModerationImageURLInput {
636
+ type: "image_url";
637
+ image_url: {
638
+ url: string;
639
+ };
640
+ }
641
+ type ModerationInputPart = ModerationTextInput | ModerationImageURLInput;
642
+ /**
643
+ * What to check: a string (one result), an array of 1 to 32 strings (one
644
+ * result each, in order) or an array of 1 to 32 parts (one result for the
645
+ * combined content). Strings and parts can't be mixed.
646
+ */
647
+ type ModerationInput = string | string[] | ModerationInputPart[];
648
+ interface ModerationCreateParams {
649
+ /** A moderation model id, e.g. `"llama-guard3:1b"`. */
650
+ model: string;
651
+ input: ModerationInput;
652
+ /** Pin to a specific worker (sent as the `X-Pendra-Worker-Id` header). */
653
+ worker_id?: string | null;
654
+ }
655
+ interface ModerationResult {
656
+ /** True when any category is set, including a borderline hit. */
657
+ flagged: boolean;
658
+ /** Only the categories the model checks are present: a missing key means "not checked". */
659
+ categories: Record<string, boolean>;
660
+ /** 1.0 flagged, 0.0 checked and clean, 0.5 a borderline hit. */
661
+ category_scores: Record<string, number>;
662
+ category_applied_input_types: Record<string, Array<"text" | "image">>;
663
+ }
664
+ /** OpenAI-compatible moderation response. */
665
+ interface ModerationResponse {
666
+ id: string;
667
+ model: string;
668
+ results: ModerationResult[];
669
+ /**
670
+ * Pendra's extension block — `pendra?.worker` names the worker that served
671
+ * the request. Absent when the API didn't report one.
672
+ */
673
+ pendra?: PendraExtension | null;
674
+ }
675
+
676
+ declare class Moderations {
677
+ private client;
678
+ constructor(client: Pendra);
679
+ /**
680
+ * Check content with a moderation model installed on one of your workers
681
+ * (OpenAI-compatible).
682
+ *
683
+ * `input` is a string, an array of up to 32 strings (one result each) or an
684
+ * array of up to 32 `text` / `image_url` parts checked together (one
685
+ * result). With private inference turned on, the check is end-to-end
686
+ * encrypted: Pendra sees neither the content nor the verdict.
687
+ *
688
+ * @example
689
+ * ```ts
690
+ * const result = await client.moderations.create({
691
+ * model: "llama-guard3:1b",
692
+ * input: "Hello world",
693
+ * });
694
+ * console.log(result.results[0].flagged);
695
+ * ```
696
+ */
697
+ create(params: ModerationCreateParams): Promise<ModerationResponse>;
698
+ private createEncrypted;
699
+ }
700
+
629
701
  interface RerankCreateParams {
630
702
  model: string;
631
703
  query: string;
@@ -799,9 +871,9 @@ interface PendraOptions {
799
871
  baseURL?: string;
800
872
  timeout?: number;
801
873
  /**
802
- * Enable end-to-end encrypted (private) inference. When `true`, chat and
803
- * embeddings requests are sealed to your org's workload key (TOFU-pinned on
804
- * first use) and the responses are decrypted client-side — Pendra relays only
874
+ * Enable end-to-end encrypted (private) inference. When `true`, inference
875
+ * requests (chat, embeddings, moderations and the rest) are sealed to your
876
+ * org's workload key (TOFU-pinned on first use) and the responses are decrypted client-side — Pendra relays only
805
877
  * ciphertext. Pass `{ pinnedFingerprint }` to hard-pin the org key fingerprint
806
878
  * (required in browser bundles, which cannot use the TOFU key store).
807
879
  *
@@ -822,6 +894,7 @@ declare class Pendra {
822
894
  models: Models;
823
895
  audio: Audio;
824
896
  rerank: Rerank;
897
+ moderations: Moderations;
825
898
  /** @internal Whether end-to-end encrypted inference is enabled for this client. */
826
899
  readonly privateInferenceEnabled: boolean;
827
900
  private _piEngine;
@@ -946,4 +1019,4 @@ declare class APIStreamError extends APIError {
946
1019
  });
947
1020
  }
948
1021
 
949
- export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, type APIStatusErrorOptions, 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, type PendraWorker, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, type SpeechCreateParams, type SpeechResponse, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
1022
+ export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, type APIStatusErrorOptions, 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, type ModerationCreateParams, type ModerationImageURLInput, type ModerationInput, type ModerationInputPart, type ModerationResponse, type ModerationResult, type ModerationTextInput, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, type PendraWorker, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, type SpeechCreateParams, type SpeechResponse, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
package/dist/index.js CHANGED
@@ -1083,17 +1083,27 @@ var MIME_EXT = {
1083
1083
  "audio/x-flac": "flac"
1084
1084
  };
1085
1085
  function extFromMime(type) {
1086
- if (!type) return "mp3";
1086
+ if (!type) return void 0;
1087
1087
  const base = type.split(";")[0].trim().toLowerCase();
1088
- return MIME_EXT[base] ?? "mp3";
1089
- }
1090
- function asBlob(file) {
1088
+ return MIME_EXT[base];
1089
+ }
1090
+ async function extFromHeader(blob) {
1091
+ const head = new Uint8Array(await blob.slice(0, 12).arrayBuffer());
1092
+ const ascii = (from, to) => String.fromCharCode(...head.subarray(from, to));
1093
+ if (head.length >= 12 && ascii(0, 4) === "RIFF" && ascii(8, 12) === "WAVE") return "wav";
1094
+ if (head.length >= 4 && ascii(0, 4) === "fLaC") return "flac";
1095
+ if (head.length >= 3 && ascii(0, 3) === "ID3") return "mp3";
1096
+ if (head.length >= 2 && head[0] === 255 && (head[1] & 224) === 224) return "mp3";
1097
+ return void 0;
1098
+ }
1099
+ async function asBlob(file) {
1091
1100
  if (file instanceof Blob) {
1092
1101
  const asFile = file;
1093
1102
  if (asFile.name) {
1094
1103
  return { blob: file, filename: asFile.name };
1095
1104
  }
1096
- return { blob: file, filename: `audio.${extFromMime(file.type)}` };
1105
+ const ext = extFromMime(file.type) ?? await extFromHeader(file);
1106
+ return { blob: file, filename: ext ? `audio.${ext}` : "audio" };
1097
1107
  }
1098
1108
  const { filename, content } = file;
1099
1109
  if (content instanceof Blob) {
@@ -1112,7 +1122,7 @@ var Transcriptions = class {
1112
1122
  if (params.beam_size != null && !(Number.isInteger(params.beam_size) && params.beam_size >= 1 && params.beam_size <= 8)) {
1113
1123
  throw new Error(`beam_size must be an integer between 1 and 8 (got ${params.beam_size})`);
1114
1124
  }
1115
- const { blob, filename } = asBlob(params.file);
1125
+ const { blob, filename } = await asBlob(params.file);
1116
1126
  if (blob.size === 0) {
1117
1127
  throw new Error("audio file is empty");
1118
1128
  }
@@ -1750,10 +1760,130 @@ var Models = class {
1750
1760
  }
1751
1761
  };
1752
1762
 
1753
- // src/resources/rerank.ts
1763
+ // src/resources/moderations.ts
1754
1764
  var ENCODER5 = new TextEncoder();
1755
1765
  var DECODER6 = new TextDecoder();
1766
+ var MAX_INPUTS = 32;
1767
+ function isPlainObject2(v) {
1768
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1769
+ }
1770
+ function validatePart(part) {
1771
+ if (!isPlainObject2(part)) {
1772
+ throw new Error("input can't mix strings and parts");
1773
+ }
1774
+ if (part.type === "text") {
1775
+ if (typeof part.text !== "string" || part.text.length === 0) {
1776
+ throw new Error("a text part needs a non-empty text");
1777
+ }
1778
+ return;
1779
+ }
1780
+ if (part.type === "image_url") {
1781
+ const url = isPlainObject2(part.image_url) ? part.image_url.url : void 0;
1782
+ if (typeof url !== "string" || url.length === 0) {
1783
+ throw new Error("an image_url part needs image_url.url");
1784
+ }
1785
+ return;
1786
+ }
1787
+ throw new Error("parts must be of type text or image_url");
1788
+ }
1756
1789
  function validateParams3(params) {
1790
+ if (!params.model || typeof params.model !== "string") {
1791
+ throw new Error("model must be a non-empty string");
1792
+ }
1793
+ const input = params.input;
1794
+ if (typeof input === "string") {
1795
+ if (input.length === 0) throw new Error("input must be a non-empty string");
1796
+ return;
1797
+ }
1798
+ if (!Array.isArray(input)) {
1799
+ throw new Error("input must be a string, an array of strings, or an array of text and image_url parts");
1800
+ }
1801
+ if (input.length === 0 || input.length > MAX_INPUTS) {
1802
+ throw new Error(`input must hold 1 to ${MAX_INPUTS} items`);
1803
+ }
1804
+ if (input.every((i) => typeof i === "string")) {
1805
+ if (!input.every((s) => s.length > 0)) {
1806
+ throw new Error("input strings must be non-empty");
1807
+ }
1808
+ return;
1809
+ }
1810
+ input.forEach(validatePart);
1811
+ }
1812
+ function asModeration(parsed, status, label) {
1813
+ if (!isPlainObject2(parsed) || !Array.isArray(parsed.results)) {
1814
+ throw new APIResponseValidationError(`${label} was not a moderation response`, {
1815
+ status,
1816
+ body: JSON.stringify(parsed)
1817
+ });
1818
+ }
1819
+ return parsed;
1820
+ }
1821
+ var Moderations = class {
1822
+ constructor(client) {
1823
+ this.client = client;
1824
+ }
1825
+ /**
1826
+ * Check content with a moderation model installed on one of your workers
1827
+ * (OpenAI-compatible).
1828
+ *
1829
+ * `input` is a string, an array of up to 32 strings (one result each) or an
1830
+ * array of up to 32 `text` / `image_url` parts checked together (one
1831
+ * result). With private inference turned on, the check is end-to-end
1832
+ * encrypted: Pendra sees neither the content nor the verdict.
1833
+ *
1834
+ * @example
1835
+ * ```ts
1836
+ * const result = await client.moderations.create({
1837
+ * model: "llama-guard3:1b",
1838
+ * input: "Hello world",
1839
+ * });
1840
+ * console.log(result.results[0].flagged);
1841
+ * ```
1842
+ */
1843
+ async create(params) {
1844
+ validateParams3(params);
1845
+ const body = {
1846
+ model: params.model,
1847
+ input: params.input
1848
+ };
1849
+ const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
1850
+ if (this.client.privateInferenceEnabled) {
1851
+ return this.createEncrypted(params.model, body, headers);
1852
+ }
1853
+ const { response } = await this.client._fetch(
1854
+ "/api/v1/moderations",
1855
+ { method: "POST", body, headers }
1856
+ );
1857
+ const result = asModeration(await readJsonReply(response), response.status, "Response");
1858
+ return withPlacement(result, response.headers, result.pendra);
1859
+ }
1860
+ async createEncrypted(model, body, headers) {
1861
+ const engine = await this.client._privateEngine();
1862
+ const { topLevel, decryptor } = engine.seal({
1863
+ model,
1864
+ stream: false,
1865
+ taskType: "moderation",
1866
+ body: ENCODER5.encode(JSON.stringify({ model: body.model, stream: false, input: body.input }))
1867
+ });
1868
+ const { response } = await this.client._fetch(
1869
+ "/api/v1/moderations",
1870
+ { method: "POST", body: topLevel, headers }
1871
+ );
1872
+ const { inner, placement } = await readSealedReply(response);
1873
+ const plain = decryptor.openResult(inner);
1874
+ const result = asModeration(
1875
+ parseDecryptedJson(DECODER6.decode(plain), response.status),
1876
+ response.status,
1877
+ "Decrypted response"
1878
+ );
1879
+ return withPlacement(result, response.headers, result.pendra, placement);
1880
+ }
1881
+ };
1882
+
1883
+ // src/resources/rerank.ts
1884
+ var ENCODER6 = new TextEncoder();
1885
+ var DECODER7 = new TextDecoder();
1886
+ function validateParams4(params) {
1757
1887
  if (!params.model || typeof params.model !== "string") {
1758
1888
  throw new Error("model must be a non-empty string");
1759
1889
  }
@@ -1787,7 +1917,7 @@ var Rerank = class {
1787
1917
  * ```
1788
1918
  */
1789
1919
  async create(params) {
1790
- validateParams3(params);
1920
+ validateParams4(params);
1791
1921
  const body = {
1792
1922
  model: params.model,
1793
1923
  query: params.query,
@@ -1812,7 +1942,7 @@ var Rerank = class {
1812
1942
  model,
1813
1943
  stream: false,
1814
1944
  taskType: "rerank",
1815
- body: ENCODER5.encode(JSON.stringify(body))
1945
+ body: ENCODER6.encode(JSON.stringify(body))
1816
1946
  });
1817
1947
  const { response } = await this.client._fetch(
1818
1948
  "/api/v1/rerank",
@@ -1820,13 +1950,13 @@ var Rerank = class {
1820
1950
  );
1821
1951
  const { inner, placement } = await readSealedReply(response);
1822
1952
  const plain = decryptor.openResult(inner);
1823
- const result = JSON.parse(DECODER6.decode(plain));
1953
+ const result = JSON.parse(DECODER7.decode(plain));
1824
1954
  return withPlacement(result, response.headers, result.pendra, placement);
1825
1955
  }
1826
1956
  };
1827
1957
 
1828
1958
  // src/version.ts
1829
- var VERSION = "0.17.2";
1959
+ var VERSION = "0.18.0";
1830
1960
  var USER_AGENT = `pendra-node/${VERSION}`;
1831
1961
 
1832
1962
  // src/client.ts
@@ -1887,6 +2017,7 @@ var Pendra = class {
1887
2017
  this.models = new Models(this);
1888
2018
  this.audio = new Audio(this);
1889
2019
  this.rerank = new Rerank(this);
2020
+ this.moderations = new Moderations(this);
1890
2021
  }
1891
2022
  /**
1892
2023
  * @internal