@openclaw/onnx 2026.11.3 → 2026.11.5-beta.2

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 CHANGED
@@ -6,11 +6,12 @@ persistent CPU inference process.
6
6
 
7
7
  ## Setup
8
8
 
9
- Released OpenClaw `2026.9.5` lacks the decision-provider API. Packaged installs
10
- require a host and plugin API of at least `2026.9.6`.
9
+ This adapter requires the prepared Decision V2 API. Released OpenClaw
10
+ `2026.10.4` exposes V1 only. Packaged use requires a supporting paired host/plugin
11
+ release; the older installation floor alone does not establish V2 compatibility.
11
12
 
12
- For development, use an OpenClaw checkout containing both the decision-provider
13
- API and this plugin. Run `pnpm install --frozen-lockfile` and `pnpm build`, enable
13
+ For development, use a matching checkout containing both the prepared V2
14
+ runtime and this plugin. Run `pnpm install --frozen-lockfile` and `pnpm build`, enable
14
15
  `plugins.entries.onnx`, and run these commands from the checkout:
15
16
 
16
17
  ```sh
@@ -1,10 +1,10 @@
1
- import { t as OnnxWorkerError } from "./protocol-lN8zQ8J3.mjs";
1
+ import { t as OnnxWorkerError } from "./protocol-YadX71Hf.mjs";
2
2
  import path from "node:path";
3
3
  import { Type } from "typebox";
4
- import { Value } from "typebox/value";
5
4
  import { createHash, randomUUID } from "node:crypto";
6
5
  import fs from "node:fs/promises";
7
6
  import { readFileWindowFully, root, sha256File } from "openclaw/plugin-sdk/file-access-runtime";
7
+ import { Value } from "typebox/value";
8
8
  //#region extensions/onnx/src/artifacts.ts
9
9
  const ExportSchema = Type.Object({
10
10
  modelId: Type.String(),
@@ -0,0 +1,47 @@
1
+ //#region extensions/onnx/src/catalog.ts
2
+ function file(bytes, sha256, path = "model.onnx") {
3
+ return {
4
+ name: path.slice(path.lastIndexOf("/") + 1),
5
+ path,
6
+ bytes,
7
+ sha256
8
+ };
9
+ }
10
+ function preset(id, name, repository, revision, files, family = "gliclass") {
11
+ return {
12
+ id,
13
+ name,
14
+ family,
15
+ maxTokens: 512,
16
+ source: files ? {
17
+ kind: "hub",
18
+ repository,
19
+ revision,
20
+ files
21
+ } : {
22
+ kind: "local-export",
23
+ repository,
24
+ revision
25
+ }
26
+ };
27
+ }
28
+ const gliner25TokenizerFiles = [file(8341713, "cbc8ae6037812709c9c26f2a160f8dc48b0440bcb79c8141804259ae2d6adac3", "tokenizer.json"), file(646, "fd4a31dc2f1f17e31638c5f0e783b81cdb2fbe6bddd116a8d9e5d50d78148cf1", "tokenizer_config.json")];
29
+ const MODELS = [
30
+ preset("gliclass-edge-v3.0", "GLiClass Edge v3", "cnmoro/gliclass-edge-v3.0-onnx", "1167c26c90183f20165120292dc5c7684af406ae", [file(131130181, "5289497ae11bb612806e56eefa168c6338e3e5d9f548e8012f1e10560e19fa8f"), file(3583864, "b6e09abceac75851eae141e7d51224a9da835c0c03684282fe2d5c42c745754f", "tokenizer.json")]),
31
+ preset("gliclass-base-v3.0", "GLiClass Base v3", "cnmoro/gliclass-base-v3.0-onnx", "8acca975fd47e89e15f13a4f5446f2ccd1dcf7bb", [file(747316021, "1395fde4ae8de8e41f51080c18a09c48c704b5a1dd34d78950b6c9a11efddd7b"), file(8649499, "9db2e87fbab9819100edd8d6dc7a54f82167045d04bfb752039dae4efb9cd85c", "tokenizer.json")]),
32
+ preset("gliner2.5-small-v1", "GLiNER 2.5 Small", "nicolasembleton/gliner2.5-small-v1-onnx", "5e2e3f51adfb0eeb7c1f83464400b4d498d41659", [file(288521577, "12dda5cf4b0e9ed3af17596cef1cdbd22185a32fcc230af4f476353b5e4ade1f", "onnx/model.onnx"), ...gliner25TokenizerFiles], "gliner"),
33
+ preset("gliner2.5-base-v1", "GLiNER 2.5 Base", "nicolasembleton/gliner2.5-base-v1-onnx", "b29dcb3c273644e833837933533ac37274fe585e", [file(746400205, "db56fe723c14e856ab5618a5bceb66b55a1e8d2cf5f3026202c45e6ff4b86f42", "onnx/model.onnx"), ...gliner25TokenizerFiles], "gliner"),
34
+ preset("deberta-v3-base-zeroshot-v2.0", "DeBERTa Zero-shot v2", "MoritzLaurer/deberta-v3-base-zeroshot-v2.0", "8e7e5af5983a0ddb1a5b45a38b129ab69e2258e8", [
35
+ file(738563249, "d46fa6c1addc598abd34af8651120291f51417ddfce45b9d5f70bc32d3efa81c", "onnx/model.onnx"),
36
+ file(1016, "a1c8011b852ae46d6ac26160d358fa595861d261352885f8f7bfcd2811030d9f", "config.json"),
37
+ file(8656646, "05402ffae6dd382a8491b1d29bfc139bec5d332662e86a026f433ce54c25c202", "tokenizer.json"),
38
+ file(1256, "f5a1a74a632c0e9225e09a21ddf60c2e70ef5d3bfc1f261a24fd8ddab27254d2", "tokenizer_config.json")
39
+ ], "deberta"),
40
+ preset("gliclass-instruct-edge-v1.0", "GLiClass Instruct Edge (local export)", "knowledgator/gliclass-instruct-edge-v1.0", "727be8a417f6a7718e591b025e07054c146d8139"),
41
+ preset("gliclass-instruct-base-v1.0", "GLiClass Instruct Base (local export)", "knowledgator/gliclass-instruct-base-v1.0", "4f6a108b08a5537f395521d19b5073e197923dd3")
42
+ ];
43
+ function findModel(id) {
44
+ return MODELS.find((model) => model.id === id);
45
+ }
46
+ //#endregion
47
+ export { findModel as n, MODELS as t };
@@ -1,6 +1,6 @@
1
- import { n as findModel, t as MODELS } from "./catalog-Bgbx4LHv.mjs";
2
- import { n as createOnnxProvider, t as InferenceWorkerClient } from "./worker-client-DUApeDD4.mjs";
3
- import { i as verifyModel, t as downloadModel } from "./artifacts-CD0XZUIN.mjs";
1
+ import { n as findModel, t as MODELS } from "./catalog-1BypY0zY.mjs";
2
+ import { n as createOnnxProvider, t as InferenceWorkerClient } from "./worker-client-DkWtdqU9.mjs";
3
+ import { i as verifyModel, t as downloadModel } from "./artifacts-Ca0QH6_i.mjs";
4
4
  import path from "node:path";
5
5
  //#region extensions/onnx/src/cli.ts
6
6
  function registerOnnxCli({ program }, settings, workerUrl, resolvePath) {
@@ -0,0 +1,214 @@
1
+ import { n as findModel } from "./catalog-1BypY0zY.mjs";
2
+ import { n as UnsupportedInputError, t as OnnxWorkerError } from "./protocol-YadX71Hf.mjs";
3
+ import { n as readModelArtifact, r as resolveModelFiles } from "./artifacts-Ca0QH6_i.mjs";
4
+ import { Tokenizer } from "@huggingface/tokenizers";
5
+ import { InferenceSession, Tensor } from "onnxruntime-node";
6
+ //#region extensions/onnx/src/models/tokenize.ts
7
+ function tokenIds(value) {
8
+ return Array.isArray(value) && value.every((id) => typeof id === "number" && Number.isSafeInteger(id) && id >= 0);
9
+ }
10
+ function encodeModelText(tokenizer, text, options) {
11
+ const encoded = tokenizer.encode(text, options);
12
+ if (!encoded || typeof encoded !== "object" || !("ids" in encoded) || !("attention_mask" in encoded) || !tokenIds(encoded.ids) || !tokenIds(encoded.attention_mask) || encoded.ids.length === 0 || encoded.ids.length !== encoded.attention_mask.length || encoded.attention_mask.some((mask) => mask !== 0 && mask !== 1)) throw new Error("Tokenizer returned invalid native tensor inputs.");
13
+ return {
14
+ ids: encoded.ids,
15
+ attention_mask: encoded.attention_mask
16
+ };
17
+ }
18
+ //#endregion
19
+ //#region extensions/onnx/src/model-loader.ts
20
+ const WORDS = /(?:https?:\/\/[^\s]+|www\.[^\s]+)|[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}|@[a-z0-9_]+|[\p{L}\p{N}_]+(?:[-_][\p{L}\p{N}_]+)*|\S/giu;
21
+ const RESERVED = /\[(?:P|L|C|E|R|DESCRIPTION|EXAMPLE|OUTPUT|SEP_TEXT|SEP_STRUCT)\]|[()]/u;
22
+ function indices(values) {
23
+ return new Tensor("int64", BigInt64Array.from(values, BigInt), [1, values.length]);
24
+ }
25
+ function mask(length, value = 1) {
26
+ return new Tensor("float32", new Float32Array(length).fill(value), [1, length]);
27
+ }
28
+ function jsonObject(data) {
29
+ const parsed = JSON.parse(data.toString("utf8"));
30
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new OnnxWorkerError("model-integrity");
31
+ return parsed;
32
+ }
33
+ var ModelCache = class {
34
+ constructor(config) {
35
+ this.config = config;
36
+ this.models = /* @__PURE__ */ new Map();
37
+ }
38
+ async close() {
39
+ const models = [...this.models.values()];
40
+ this.models.clear();
41
+ const failures = (await Promise.allSettled(models.map(({ session }) => session.release()))).filter((result) => result.status === "rejected");
42
+ if (failures.length > 0) throw new AggregateError(failures.map((result) => result.reason), "ONNX session release failed");
43
+ }
44
+ async get(id) {
45
+ const existing = this.models.get(id);
46
+ if (existing) {
47
+ this.models.delete(id);
48
+ this.models.set(id, existing);
49
+ return existing.adapter;
50
+ }
51
+ const model = findModel(id);
52
+ if (!model) throw new UnsupportedInputError("Unknown ONNX model.");
53
+ const files = await resolveModelFiles(this.config.modelDir, model);
54
+ const buffers = /* @__PURE__ */ new Map();
55
+ for (const file of files) buffers.set(file.name, await readModelArtifact(this.config.modelDir, model, file));
56
+ const modelBytes = buffers.get("model.onnx");
57
+ const tokenizerBytes = buffers.get("tokenizer.json");
58
+ if (!modelBytes || !tokenizerBytes) throw new OnnxWorkerError("model-integrity");
59
+ const tokenizerConfig = buffers.get("tokenizer_config.json");
60
+ const tokenizer = new Tokenizer(jsonObject(tokenizerBytes), tokenizerConfig ? jsonObject(tokenizerConfig) : {});
61
+ if (this.models.size >= this.config.maxLoadedModels) {
62
+ const first = this.models.entries().next().value;
63
+ if (first) {
64
+ this.models.delete(first[0]);
65
+ await first[1].session.release();
66
+ }
67
+ }
68
+ const session = await InferenceSession.create(modelBytes, {
69
+ executionProviders: ["cpu"],
70
+ intraOpNumThreads: this.config.threads,
71
+ interOpNumThreads: 1,
72
+ logSeverityLevel: 3
73
+ });
74
+ try {
75
+ const maxTokens = model.maxTokens;
76
+ let adapter;
77
+ if (model.family === "gliclass") {
78
+ const labelToken = tokenizer.token_to_id("<<LABEL>>");
79
+ const separatorToken = tokenizer.token_to_id("<<SEP>>");
80
+ const exampleToken = tokenizer.token_to_id("<<EXAMPLE>>");
81
+ if (labelToken === void 0 || separatorToken === void 0 || labelToken === separatorToken) throw new Error("GLiClass tokenizer is missing its label and separator tokens.");
82
+ adapter = { async classify(input) {
83
+ const labels = input.labels.map((label) => input.descriptions?.[label] ?? label);
84
+ const text = input.instructions ? `${input.instructions}\n${input.text}` : input.text;
85
+ if (labels.length < 2 || labels.length > 64 || labels.some((label) => !label.trim()) || new Set(labels).size !== labels.length || [text, ...labels].some((value) => /<<LABEL>>|<<SEP>>|<<EXAMPLE>>/.test(value.normalize("NFKC")))) throw new UnsupportedInputError("GLiClass requires 2–64 distinct labels and input without its reserved markers.");
86
+ const packed = `${labels.map((label) => `<<LABEL>>${label}`).join("")}<<SEP>>${text}`;
87
+ const encoded = encodeModelText(tokenizer, packed);
88
+ if (encoded.ids.length > maxTokens) throw new UnsupportedInputError(`GLiClass input exceeds its ${maxTokens}-token limit; shorten the state or rubric.`);
89
+ if (encoded.ids.filter((token) => token === labelToken).length !== labels.length || encoded.ids.filter((token) => token === separatorToken).length !== 1 || exampleToken !== void 0 && encoded.ids.includes(exampleToken)) throw new UnsupportedInputError("GLiClass input changes the number of rubric markers.");
90
+ const shape = [1, encoded.ids.length];
91
+ const scores = (await session.run({
92
+ input_ids: new Tensor("int64", BigInt64Array.from(encoded.ids, BigInt), shape),
93
+ attention_mask: new Tensor("int64", BigInt64Array.from(encoded.attention_mask, BigInt), shape)
94
+ })).logits;
95
+ if (!scores || scores.type !== "float32" || !(scores.data instanceof Float32Array) || scores.dims.length !== 2 || scores.dims[0] !== 1 || scores.dims[1] !== labels.length || scores.data.length !== labels.length) throw new Error("GLiClass returned an invalid label-logit shape.");
96
+ const logits = Array.from(scores.data);
97
+ if (logits.some((value) => !Number.isFinite(value))) throw new Error("GLiClass returned non-finite label logits.");
98
+ return {
99
+ logits,
100
+ inputTokens: encoded.ids.length
101
+ };
102
+ } };
103
+ } else if (model.family === "gliner") adapter = { async classify({ text, labels, task, instructions, descriptions }) {
104
+ if ([
105
+ task,
106
+ ...labels,
107
+ instructions,
108
+ ...labels.map((label) => descriptions?.[label])
109
+ ].some((value) => value !== void 0 && (!value.trim() || RESERVED.test(value)))) throw new UnsupportedInputError("GLiNER2.5 rubric contains an empty or reserved schema token.");
110
+ let prompt = instructions ? `${task}: ${instructions}` : task;
111
+ for (const label of labels) if (descriptions?.[label]) prompt += ` [DESCRIPTION] ${label}: ${descriptions[label]}`;
112
+ const inputIds = [];
113
+ const append = (token) => {
114
+ const encoded = encodeModelText(tokenizer, token, { add_special_tokens: false }).ids;
115
+ if (encoded.length === 0 || inputIds.length + encoded.length > maxTokens) throw new UnsupportedInputError("GLiNER2.5 input exceeds the token limit or is empty.");
116
+ inputIds.push(...encoded);
117
+ };
118
+ for (const token of [
119
+ "(",
120
+ "[P]",
121
+ prompt,
122
+ "("
123
+ ]) append(token);
124
+ const classificationPositions = [];
125
+ for (const label of labels) {
126
+ classificationPositions.push(inputIds.length);
127
+ append("[L]");
128
+ append(label);
129
+ }
130
+ for (const token of [
131
+ ")",
132
+ ")",
133
+ "[SEP_TEXT]"
134
+ ]) append(token);
135
+ const normalized = /[.!?]$/.test(text) ? text : `${text}.`;
136
+ const wordPositions = [];
137
+ for (const match of normalized.matchAll(WORDS)) {
138
+ wordPositions.push(inputIds.length);
139
+ append(match[0].toLowerCase());
140
+ }
141
+ const feeds = {
142
+ input_ids: indices(inputIds),
143
+ attention_mask: indices(inputIds.map(() => 1)),
144
+ text_word_indices: indices(wordPositions),
145
+ text_word_mask: mask(wordPositions.length),
146
+ query_marker_indices: indices([0]),
147
+ query_marker_mask: mask(1, 0),
148
+ cls_marker_indices: indices(classificationPositions),
149
+ cls_marker_mask: mask(labels.length),
150
+ rel_marker_indices: indices([0]),
151
+ rel_marker_mask: mask(1, 0)
152
+ };
153
+ const output = (await session.run(feeds, ["cls_logits"])).cls_logits;
154
+ if (!output || output.type !== "float32" || output.dims.length !== 2 || output.dims[0] !== 1 || output.dims[1] !== labels.length) throw new Error("GLiNER2.5 returned an invalid classification tensor.");
155
+ const logits = Array.from(output.data, Number);
156
+ if (logits.some((value) => !Number.isFinite(value))) throw new Error("GLiNER2.5 returned non-finite classification logits.");
157
+ return {
158
+ logits,
159
+ inputTokens: inputIds.length
160
+ };
161
+ } };
162
+ else adapter = { async classify({ text, labels, instructions, descriptions }) {
163
+ const premise = instructions ? `${instructions}\n${text}` : text;
164
+ const encoded = labels.map((label) => {
165
+ const hypothesis = descriptions?.[label] ?? `This example is ${label}.`;
166
+ const pair = encodeModelText(tokenizer, premise, {
167
+ text_pair: hypothesis,
168
+ add_special_tokens: true
169
+ });
170
+ if (pair.ids.length > maxTokens) throw new UnsupportedInputError("DeBERTa input exceeds its token limit; shorten the state or rubric.");
171
+ return pair;
172
+ });
173
+ const logits = [];
174
+ const pad = tokenizer.token_to_id("[PAD]");
175
+ if (pad === void 0) throw new Error("DeBERTa tokenizer is missing its padding token.");
176
+ for (let offset = 0; offset < encoded.length; offset += 8) {
177
+ const batch = encoded.slice(offset, offset + 8);
178
+ const length = Math.max(...batch.map((pair) => pair.ids.length));
179
+ const ids = new BigInt64Array(batch.length * length).fill(BigInt(pad));
180
+ const attention = new BigInt64Array(ids.length);
181
+ batch.forEach((pair, row) => {
182
+ ids.set(BigInt64Array.from(pair.ids, BigInt), row * length);
183
+ attention.set(BigInt64Array.from(pair.attention_mask, BigInt), row * length);
184
+ });
185
+ const shape = [batch.length, length];
186
+ const scores = (await session.run({
187
+ input_ids: new Tensor("int64", ids, shape),
188
+ attention_mask: new Tensor("int64", attention, shape)
189
+ })).logits;
190
+ if (!scores || scores.type !== "float32" || scores.dims.length !== 2 || !(scores.data instanceof Float32Array) || scores.dims[0] !== batch.length || scores.dims[1] !== 2 || scores.data.length !== batch.length * 2) throw new Error("DeBERTa returned an invalid entailment tensor.");
191
+ for (let row = 0; row < batch.length; row++) {
192
+ const entailment = scores.data[row * 2];
193
+ if (!Number.isFinite(entailment)) throw new Error("DeBERTa returned non-finite logits.");
194
+ logits.push(entailment);
195
+ }
196
+ }
197
+ return {
198
+ logits,
199
+ inputTokens: encoded.reduce((sum, pair) => sum + pair.ids.length, 0)
200
+ };
201
+ } };
202
+ this.models.set(id, {
203
+ session,
204
+ adapter
205
+ });
206
+ return adapter;
207
+ } catch (error) {
208
+ await session.release();
209
+ throw error;
210
+ }
211
+ }
212
+ };
213
+ //#endregion
214
+ export { ModelCache };
@@ -0,0 +1,12 @@
1
+ //#region extensions/onnx/src/models/types.ts
2
+ var UnsupportedInputError = class extends Error {};
3
+ //#endregion
4
+ //#region extensions/onnx/src/protocol.ts
5
+ var OnnxWorkerError = class extends Error {
6
+ constructor(code) {
7
+ super(`ONNX worker: ${code}`);
8
+ this.code = code;
9
+ }
10
+ };
11
+ //#endregion
12
+ export { UnsupportedInputError as n, OnnxWorkerError as t };
@@ -1,7 +1,9 @@
1
- import { n as findModel } from "./catalog-Bgbx4LHv.mjs";
2
- import { i as UnsupportedInputError, n as parseWorkerReply, r as parseWorkerRequest, t as OnnxWorkerError } from "./protocol-lN8zQ8J3.mjs";
3
- import { createDeferred } from "openclaw/plugin-sdk/concurrency-runtime";
1
+ import { n as findModel } from "./catalog-1BypY0zY.mjs";
2
+ import { n as UnsupportedInputError, t as OnnxWorkerError } from "./protocol-YadX71Hf.mjs";
4
3
  import { resolveRuntimeWorkerArgv, spawnOomScoreAdjusted } from "openclaw/plugin-sdk/process-runtime";
4
+ import { decisionBatchV2ToV1, decisionResultV1ToV2 } from "openclaw/plugin-sdk/decisions";
5
+ import { createDeferred } from "openclaw/plugin-sdk/concurrency-runtime";
6
+ import { Guard } from "typebox/guard";
5
7
  //#region extensions/onnx/src/decisions.ts
6
8
  function render(value) {
7
9
  return typeof value === "string" ? value : JSON.stringify(value);
@@ -31,7 +33,6 @@ function rubric(question) {
31
33
  };
32
34
  }
33
35
  function probabilities(logits) {
34
- if (logits.length < 2 || logits.some((value) => !Number.isFinite(value))) throw new Error("ONNX returned invalid label logits.");
35
36
  const max = Math.max(...logits);
36
37
  const weights = logits.map((value) => Math.exp(value - max));
37
38
  const sum = weights.reduce((total, value) => total + value, 0);
@@ -49,11 +50,9 @@ function createOnnxProvider(client, warn) {
49
50
  };
50
51
  try {
51
52
  const entries = Object.entries(batch.questions);
52
- if (entries.length === 0 || entries.length > 32) throw new UnsupportedInputError("Unsupported batch size.");
53
53
  const text = render(batch.state);
54
54
  const inputs = entries.map(([, question]) => {
55
55
  const selected = rubric(question);
56
- if (selected.labels.length < 2 || selected.labels.length > 64) throw new UnsupportedInputError("Unsupported label count.");
57
56
  return {
58
57
  text,
59
58
  task: "decision",
@@ -61,15 +60,13 @@ function createOnnxProvider(client, warn) {
61
60
  ...question.instructions == null ? {} : { instructions: render(question.instructions) }
62
61
  };
63
62
  });
64
- const results = await client.classify(context.model, inputs, context.signal);
63
+ const results = await client.classify(context.model, inputs, context.signal, context.isAdmissible);
65
64
  context.signal.throwIfAborted();
66
- if (results.length !== entries.length) throw new Error("ONNX returned an incomplete batch.");
67
65
  const answers = /* @__PURE__ */ new Map();
68
66
  let inputTokens = 0;
69
67
  entries.forEach(([id, question], index) => {
70
68
  const result = results[index];
71
69
  const labels = inputs[index].labels;
72
- if (result.logits.length !== labels.length) throw new Error("ONNX returned an incomplete distribution.");
73
70
  const values = probabilities(result.logits);
74
71
  inputTokens += result.inputTokens;
75
72
  if (question.type === "boolean") answers.set(id, {
@@ -122,6 +119,90 @@ function createOnnxProvider(client, warn) {
122
119
  }
123
120
  };
124
121
  }
122
+ function createPreparedOnnxProvider(client, warn) {
123
+ const legacy = createOnnxProvider(client, warn);
124
+ return {
125
+ id: "onnx",
126
+ contractVersion: 2,
127
+ provider: {
128
+ label: "ONNX",
129
+ auth: [],
130
+ authScope: "plugin",
131
+ resolveSyntheticAuth: () => ({
132
+ apiKey: "onnx-local",
133
+ source: "onnx plugin",
134
+ mode: "api-key"
135
+ }),
136
+ augmentModelCatalog: ({ entries }) => {
137
+ const models = [];
138
+ for (const entry of entries) {
139
+ if (entry.provider !== "onnx") continue;
140
+ const inference = entry.inference;
141
+ if (!inference?.decision || inference.decision.protocol !== "decision-v1") {
142
+ models.push(entry);
143
+ continue;
144
+ }
145
+ const decision = inference.decision;
146
+ models.push({
147
+ ...entry,
148
+ inference: {
149
+ ...inference,
150
+ decision: {
151
+ ...decision,
152
+ protocol: "onnx-classifier",
153
+ questions: {
154
+ boolean: {
155
+ ...decision.questions?.boolean,
156
+ probabilities: "boolean",
157
+ abstention: false,
158
+ requiresCriteria: true
159
+ },
160
+ choice: {
161
+ ...decision.questions?.choice,
162
+ probabilities: "categorical",
163
+ abstention: false,
164
+ minOptions: 2
165
+ },
166
+ score: {
167
+ ...decision.questions?.score,
168
+ probabilities: "categorical",
169
+ abstention: false,
170
+ minOptions: 2
171
+ }
172
+ },
173
+ reasoning: { modes: ["auto"] }
174
+ }
175
+ }
176
+ });
177
+ }
178
+ return models;
179
+ }
180
+ },
181
+ async evaluate(batch, context) {
182
+ const v1 = decisionBatchV2ToV1(batch);
183
+ if (!v1 || context.reasoning !== void 0 && context.reasoning !== "auto") return {
184
+ status: "unavailable",
185
+ reason: "unsupported-input"
186
+ };
187
+ const outcome = await legacy.evaluate(v1, {
188
+ model: context.model.id,
189
+ agentId: context.agentId,
190
+ signal: context.signal,
191
+ deadlineMonotonicMs: context.deadlineMonotonicMs,
192
+ isAdmissible: context.isAdmissible
193
+ });
194
+ if (outcome.status !== "ok") return outcome;
195
+ const result = decisionResultV1ToV2(v1, outcome.result);
196
+ return result ? {
197
+ status: "ok",
198
+ result
199
+ } : {
200
+ status: "unavailable",
201
+ reason: "invalid-response"
202
+ };
203
+ }
204
+ };
205
+ }
125
206
  //#endregion
126
207
  //#region extensions/onnx/src/worker-client.ts
127
208
  function workerEnv() {
@@ -140,29 +221,28 @@ function workerEnv() {
140
221
  var InferenceWorkerClient = class {
141
222
  constructor(options) {
142
223
  this.queue = [];
143
- this.nextId = 0;
144
224
  this.closed = false;
145
- this.workerUrl = new URL(options.workerUrl.href);
146
- this.config = { ...options.config };
225
+ this.workerUrl = options.workerUrl;
226
+ this.config = options.config;
147
227
  }
148
- async classify(model, inputs, signal) {
149
- const reply = await this.enqueue({
228
+ async classify(model, inputs, signal, isAdmissible) {
229
+ signal.throwIfAborted();
230
+ if (!model.length || !Guard.IsMaxLength(model, 128) || inputs.length < 1 || inputs.length > 32) throw new OnnxWorkerError("unsupported-input");
231
+ let bytes = 0;
232
+ for (const input of inputs) {
233
+ bytes += Buffer.byteLength(JSON.stringify(input));
234
+ if (!Guard.IsMaxLength(input.text, 262144) || input.labels.length < 2 || input.labels.length > 64 || input.labels.some((label) => !label.length || !Guard.IsMaxLength(label, 16384)) || !input.task.length || !Guard.IsMaxLength(input.task, 1024) || !Guard.IsMaxLength(input.instructions ?? "", 16384) || Object.values(input.descriptions ?? {}).some((value) => !Guard.IsMaxLength(value, 16384)) || bytes > 1048576) throw new OnnxWorkerError("unsupported-input");
235
+ }
236
+ return (await this.enqueue({
150
237
  kind: "classify",
151
- id: ++this.nextId,
152
238
  model,
153
- inputs: inputs.map((input) => ({
154
- ...input,
155
- labels: [...input.labels]
156
- }))
157
- }, signal);
158
- if (reply.kind !== "results") throw new OnnxWorkerError("runtime");
159
- return reply.results;
239
+ inputs
240
+ }, signal, isAdmissible)).results;
160
241
  }
161
242
  async warm(models, signal) {
162
243
  await this.enqueue({
163
244
  kind: "warm",
164
- id: ++this.nextId,
165
- models: [...models]
245
+ models
166
246
  }, signal);
167
247
  }
168
248
  stop() {
@@ -177,19 +257,14 @@ var InferenceWorkerClient = class {
177
257
  this.stopping = worker?.closed ?? Promise.resolve();
178
258
  return this.stopping;
179
259
  }
180
- enqueue(request, signal) {
260
+ enqueue(request, signal, isAdmissible) {
181
261
  signal.throwIfAborted();
182
- try {
183
- parseWorkerRequest(request);
184
- } catch {
185
- return Promise.reject(new OnnxWorkerError("unsupported-input"));
186
- }
187
262
  if (this.closed || this.queue.length + (this.active ? 1 : 0) >= 4) return Promise.reject(new OnnxWorkerError("runtime"));
188
263
  return new Promise((resolve, reject) => {
189
264
  const task = {
190
265
  request,
191
266
  signal,
192
- sent: false,
267
+ isAdmissible,
193
268
  resolve,
194
269
  reject,
195
270
  abort: () => this.cancel(task)
@@ -217,20 +292,23 @@ var InferenceWorkerClient = class {
217
292
  const task = this.queue.shift();
218
293
  if (!task) return;
219
294
  this.active = task;
295
+ try {
296
+ if (task.isAdmissible && !task.isAdmissible()) throw new OnnxWorkerError("runtime");
297
+ } catch (error) {
298
+ this.finish(void 0, error);
299
+ return;
300
+ }
220
301
  if (!this.worker) {
221
302
  try {
222
- this.start();
303
+ this.start(task.request);
223
304
  } catch {
224
305
  this.finish(void 0, new OnnxWorkerError("runtime"));
225
306
  }
226
307
  return;
227
308
  }
228
- if (this.worker.ready) {
229
- this.send(this.worker, task.request);
230
- task.sent = true;
231
- }
309
+ this.send(this.worker, task.request);
232
310
  }
233
- start() {
311
+ start(request) {
234
312
  const child = spawnOomScoreAdjusted(process.execPath, resolveRuntimeWorkerArgv(this.workerUrl), {
235
313
  env: workerEnv(),
236
314
  shell: false,
@@ -245,13 +323,12 @@ var InferenceWorkerClient = class {
245
323
  const { promise: closed, resolve: resolveClosed } = createDeferred();
246
324
  const worker = {
247
325
  child,
248
- ready: false,
249
326
  retiring: false,
250
327
  closed,
251
328
  resolveClosed
252
329
  };
253
330
  this.worker = worker;
254
- child.on("message", (message) => this.receive(worker, message));
331
+ child.on("message", (reply) => this.receive(worker, reply));
255
332
  const onFailure = () => {
256
333
  if (this.worker === worker) this.retire(new OnnxWorkerError("runtime"));
257
334
  };
@@ -270,6 +347,7 @@ var InferenceWorkerClient = class {
270
347
  kind: "init",
271
348
  config: this.config
272
349
  });
350
+ this.send(worker, request);
273
351
  }
274
352
  send(worker, request) {
275
353
  try {
@@ -280,33 +358,13 @@ var InferenceWorkerClient = class {
280
358
  if (this.worker === worker) this.retire(new OnnxWorkerError("runtime"));
281
359
  }
282
360
  }
283
- receive(worker, message) {
361
+ receive(worker, reply) {
284
362
  if (this.worker !== worker || worker.retiring) return;
285
- let reply;
286
- try {
287
- reply = parseWorkerReply(message);
288
- } catch {
289
- this.retire(new OnnxWorkerError("runtime"));
290
- return;
291
- }
292
- const task = this.active;
293
- if (reply.kind === "ready" && !worker.ready && task) {
294
- worker.ready = true;
295
- task.sent = true;
296
- this.send(worker, task.request);
297
- return;
298
- }
299
- if (!worker.ready || !task?.sent || reply.kind === "ready" || reply.id !== task.request.id) {
300
- this.retire(new OnnxWorkerError("runtime"));
301
- return;
302
- }
303
363
  if (reply.kind === "error") {
304
364
  this.finish(void 0, new OnnxWorkerError(reply.code));
305
365
  return;
306
366
  }
307
- const request = task.request;
308
- if (reply.kind === "warmed" && request.kind === "warm" || reply.kind === "results" && request.kind === "classify" && reply.results.length === request.inputs.length && reply.results.every((result, index) => result.logits.length === request.inputs[index]?.labels.length && result.logits.every(Number.isFinite))) this.finish(reply);
309
- else this.retire(new OnnxWorkerError("runtime"));
367
+ this.finish(reply);
310
368
  }
311
369
  finish(reply, failure) {
312
370
  const task = this.active;
@@ -326,4 +384,4 @@ var InferenceWorkerClient = class {
326
384
  }
327
385
  };
328
386
  //#endregion
329
- export { createOnnxProvider as n, InferenceWorkerClient as t };
387
+ export { createOnnxProvider as n, createPreparedOnnxProvider as r, InferenceWorkerClient as t };
@@ -0,0 +1 @@
1
+ {"version":3,"entries":[{"output":"index.js","source":"extensions/onnx/index.ts"},{"output":"src/inference.worker.js","source":"extensions/onnx/src/inference.worker.ts"}],"chunks":[{"output":".setup/artifacts-Ca0QH6_i.mjs","sha256":"ae6ee99d5f657475c66637e15015da181750270305b5cb1ee953f8e533b82303","facadeSource":null,"sources":["extensions/onnx/src/artifacts.ts"]},{"output":".setup/catalog-1BypY0zY.mjs","sha256":"83fa303fea925511aef41b7fdd5ee6234e79894531cfb7afad9a038924576427","facadeSource":null,"sources":["extensions/onnx/src/catalog.ts"]},{"output":".setup/cli-1ENeSnvV.mjs","sha256":"fa530bcbd08bbba6b0911b5e02dde8deaca765d692b38257bf9c35fb6d7630e5","facadeSource":"extensions/onnx/src/cli.ts","sources":["extensions/onnx/src/cli.ts"]},{"output":".setup/model-loader-qxzJEnKc.mjs","sha256":"e6f48da5cb87ca03e9bdf657280682ffa7ccef4709c220f5a7ef541494b4ab67","facadeSource":"extensions/onnx/src/model-loader.ts","sources":["extensions/onnx/src/model-loader.ts","extensions/onnx/src/models/tokenize.ts"]},{"output":".setup/protocol-YadX71Hf.mjs","sha256":"ad5650fb4a85a5d0c6b5533377113dac7aa5fc4fcfa73e54a3ae58645ef77fe9","facadeSource":null,"sources":["extensions/onnx/src/models/types.ts","extensions/onnx/src/protocol.ts"]},{"output":".setup/worker-client-DkWtdqU9.mjs","sha256":"b7778bfd0b0247df898c6ed6cee8cf42ef8927e2d05b1bd3ac7c5b888359be5e","facadeSource":null,"sources":["extensions/onnx/src/decisions.ts","extensions/onnx/src/worker-client.ts"]},{"output":"index.js","sha256":"71641c60c15bbfcf74e6d60d3de4675f9dcb03487d696d4e60fcfa85d0437b00","facadeSource":"extensions/onnx/index.ts","sources":["extensions/onnx/index.ts","extensions/onnx/src/config.ts"]},{"output":"src/inference.worker.js","sha256":"aef155c6508246642cc09c56e136288b2d56a6899ccc6c2fdd1ae226d85d7241","facadeSource":"extensions/onnx/src/inference.worker.ts","sources":["extensions/onnx/src/inference.worker.ts"]}],"unrenderedSources":[]}