@openclaw/onnx 2026.10.10 → 2026.11.5-beta.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/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
- import { n as findModel } from "./.setup/catalog-0M53kmJq.mjs";
2
- import { n as createOnnxProvider, t as InferenceWorkerClient } from "./.setup/worker-client-cQ1VR-j4.mjs";
3
- import path from "node:path";
1
+ import { n as findModel } from "./.setup/catalog-g9or975s.mjs";
2
+ import { r as createPreparedOnnxProvider, t as InferenceWorkerClient } from "./.setup/worker-client-C6PMT6Zd.mjs";
4
3
  import { pathToFileURL } from "node:url";
5
4
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
5
+ import { createPluginRuntimeProcessEntrypoint, resolveRuntimeWorkerUrl } from "openclaw/plugin-sdk/process-runtime";
6
+ import path from "node:path";
6
7
  import { resolveStateDir } from "openclaw/plugin-sdk/state-paths";
7
8
  import { Type } from "typebox";
8
9
  // extensions/onnx/src/config.ts
@@ -49,29 +50,29 @@ var onnx_default = definePluginEntry({
49
50
  configSchema: { jsonSchema: { ...ConfigSchema } },
50
51
  register(api) {
51
52
  if (!api.runtimeSource) throw new Error("ONNX requires runtime entrypoint metadata from its OpenClaw host.");
52
- const workerUrl = new URL(`./src/inference.worker${path.extname(api.runtimeSource)}`, pathToFileURL(api.runtimeSource));
53
+ const workerUrl = resolveRuntimeWorkerUrl(createPluginRuntimeProcessEntrypoint("onnxInference", pathToFileURL(api.runtimeSource).href));
53
54
  const config = resolveOnnxConfig(api.pluginConfig, api.resolvePath);
54
55
  const client = new InferenceWorkerClient({
55
56
  workerUrl,
56
57
  config
57
58
  });
58
- api.registerDecisionProvider(createOnnxProvider(client, (message) => api.logger.warn(message)));
59
+ api.registerDecisionProvider(createPreparedOnnxProvider(client, (message) => api.logger.warn(message)));
59
60
  api.registerService({
60
61
  id: "onnx-worker",
61
62
  async start(context) {
62
63
  const models = selectedModels(context.config).slice(0, config.maxLoadedModels);
63
64
  if (models.length === 0) return;
64
65
  try {
65
- await client.warm(models, AbortSignal.any([AbortSignal.timeout(12e4), ...api.lifecycle?.signal ? [api.lifecycle.signal] : []]));
66
+ await client.warm(models, AbortSignal.any([AbortSignal.timeout(12e4), ...api.lifecycle.signal ? [api.lifecycle.signal] : []]));
66
67
  } catch {
67
68
  context.logger.warn("ONNX models are not ready. Run openclaw onnx models and verify/download the selected artifacts.");
68
69
  }
69
70
  },
70
71
  stop: () => client.stop()
71
72
  });
72
- api.lifecycle?.onDispose?.(() => client.stop());
73
+ api.lifecycle.onDispose?.(() => client.stop());
73
74
  api.registerCli(async (context) => {
74
- const { registerOnnxCli } = await import("./.setup/cli-Dc9p3Cjs.mjs");
75
+ const { registerOnnxCli } = await import("./.setup/cli-wozJmsLz.mjs");
75
76
  registerOnnxCli(context, config, workerUrl, api.resolvePath);
76
77
  }, { descriptors: [{
77
78
  name: "onnx",
@@ -80,30 +80,10 @@ def parse_args():
80
80
  def publish(staged, output):
81
81
  # POSIX directory rename can replace another writer's empty directory.
82
82
  output.mkdir(exist_ok=False)
83
- reservation = output.lstat()
84
- linked = []
85
- try:
86
- files = sorted(path for path in staged.iterdir() if path.name != "model.json")
87
- # Readers require the manifest, so it is the publication boundary.
88
- for source in [*files, staged / "model.json"]:
89
- target = output / source.name
90
- identity = source.lstat()
91
- os.link(source, target)
92
- linked.append((target, identity))
93
- except BaseException:
94
- try:
95
- for target, identity in linked:
96
- if not os.path.samestat(output.lstat(), reservation):
97
- break
98
- if target.exists() and os.path.samestat(target.lstat(), identity):
99
- target.unlink()
100
- # A concurrent rename can replace the reservation during cleanup.
101
- if os.path.samestat(output.lstat(), reservation):
102
- # Unexpected files keep the reservation in place rather than being removed.
103
- output.rmdir()
104
- except OSError as error:
105
- print(f"Incomplete output cleanup: {error}", file=sys.stderr)
106
- raise
83
+ files = sorted(path for path in staged.iterdir() if path.name != "model.json")
84
+ # Manifest-last publication leaves failed exports visibly incomplete; choose a new output path.
85
+ for source in [*files, staged / "model.json"]:
86
+ os.link(source, output / source.name)
107
87
 
108
88
 
109
89
  def export(args):
@@ -1,4 +1,4 @@
1
- import { i as UnsupportedInputError, r as parseWorkerRequest, t as OnnxWorkerError } from "../.setup/protocol-0QYyt_af.mjs";
1
+ import { n as UnsupportedInputError, t as OnnxWorkerError } from "../.setup/protocol-CG1ILdRP.mjs";
2
2
  // extensions/onnx/src/inference.worker.ts
3
3
  let config;
4
4
  let cache;
@@ -27,33 +27,25 @@ function send(reply) {
27
27
  if (error) stop(1);
28
28
  });
29
29
  }
30
- function onMessage(value) {
30
+ function onMessage(request) {
31
31
  if (stopping) return;
32
- if (activeTask) {
33
- stop(1);
32
+ if (request.kind === "init") {
33
+ config = request.config;
34
34
  return;
35
35
  }
36
- activeTask = handle(value);
36
+ activeTask = handle(request);
37
37
  activeTask.catch(() => stop(1)).finally(() => {
38
38
  activeTask = void 0;
39
39
  });
40
40
  }
41
41
  process.on("disconnect", () => stop(0));
42
42
  process.on("message", onMessage);
43
- async function handle(value) {
44
- const request = parseWorkerRequest(value);
45
- if (request.kind === "init") {
46
- if (config) throw new Error("Already initialized");
47
- config = request.config;
48
- send({ kind: "ready" });
49
- return;
50
- }
51
- if (!config) throw new Error("Invalid worker admission");
43
+ async function handle(request) {
52
44
  try {
53
45
  if (!cache) {
54
46
  let implementation;
55
47
  try {
56
- implementation = await import("../.setup/model-loader-Dkk1GRxt.mjs");
48
+ implementation = await import("../.setup/model-loader-DDsav9p5.mjs");
57
49
  } catch {
58
50
  throw new OnnxWorkerError("dependency-unavailable");
59
51
  }
@@ -64,10 +56,7 @@ async function handle(value) {
64
56
  if (stopping) return;
65
57
  await cache.get(model);
66
58
  }
67
- send({
68
- kind: "warmed",
69
- id: request.id
70
- });
59
+ send({ kind: "warmed" });
71
60
  } else {
72
61
  const model = await cache.get(request.model);
73
62
  const results = [];
@@ -77,14 +66,12 @@ async function handle(value) {
77
66
  }
78
67
  send({
79
68
  kind: "results",
80
- id: request.id,
81
69
  results
82
70
  });
83
71
  }
84
72
  } catch (error) {
85
73
  send({
86
74
  kind: "error",
87
- id: request.id,
88
75
  code: error instanceof UnsupportedInputError ? "unsupported-input" : error instanceof OnnxWorkerError ? error.code : "runtime"
89
76
  });
90
77
  }
@@ -192,5 +192,19 @@
192
192
  "confidence": "none"
193
193
  }
194
194
  }
195
+ ],
196
+ "modelCatalog": {
197
+ "providers": {
198
+ "onnx": {
199
+ "authScope": "plugin",
200
+ "models": []
201
+ }
202
+ }
203
+ },
204
+ "providers": [
205
+ "onnx"
206
+ ],
207
+ "nonSecretAuthMarkers": [
208
+ "onnx-local"
195
209
  ]
196
210
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/onnx",
3
- "version": "2026.10.10",
3
+ "version": "2026.11.5-beta.1",
4
4
  "description": "Local ONNX decision models for OpenClaw",
5
5
  "repository": {
6
6
  "type": "git",
@@ -9,7 +9,7 @@
9
9
  "type": "module",
10
10
  "dependencies": {
11
11
  "@huggingface/tokenizers": "0.2.0",
12
- "typebox": "1.3.35"
12
+ "typebox": "1.4.2"
13
13
  },
14
14
  "optionalDependencies": {
15
15
  "onnxruntime-node": "1.30.0"
@@ -28,11 +28,11 @@
28
28
  "minHostVersion": ">=2026.9.6"
29
29
  },
30
30
  "compat": {
31
- "pluginApi": ">=2026.10.10"
31
+ "pluginApi": ">=2026.11.5-beta.1"
32
32
  },
33
33
  "build": {
34
34
  "bundledDist": false,
35
- "openclawVersion": "2026.10.10",
35
+ "openclawVersion": "2026.11.5-beta.1",
36
36
  "workerEntries": [
37
37
  "./src/inference.worker.ts"
38
38
  ],
@@ -60,7 +60,7 @@
60
60
  "assets/activity.svg"
61
61
  ],
62
62
  "peerDependencies": {
63
- "openclaw": ">=2026.10.10"
63
+ "openclaw": ">=2026.11.5-beta.1"
64
64
  },
65
65
  "peerDependenciesMeta": {
66
66
  "openclaw": {
@@ -1,172 +0,0 @@
1
- // extensions/onnx/src/catalog.ts
2
- const MODELS = [
3
- {
4
- id: "gliclass-edge-v3.0",
5
- name: "GLiClass Edge v3",
6
- family: "gliclass",
7
- maxTokens: 512,
8
- source: {
9
- kind: "hub",
10
- repository: "cnmoro/gliclass-edge-v3.0-onnx",
11
- revision: "1167c26c90183f20165120292dc5c7684af406ae",
12
- files: [{
13
- name: "model.onnx",
14
- path: "model.onnx",
15
- bytes: 131130181,
16
- sha256: "5289497ae11bb612806e56eefa168c6338e3e5d9f548e8012f1e10560e19fa8f"
17
- }, {
18
- name: "tokenizer.json",
19
- path: "tokenizer.json",
20
- bytes: 3583864,
21
- sha256: "b6e09abceac75851eae141e7d51224a9da835c0c03684282fe2d5c42c745754f"
22
- }]
23
- }
24
- },
25
- {
26
- id: "gliclass-base-v3.0",
27
- name: "GLiClass Base v3",
28
- family: "gliclass",
29
- maxTokens: 512,
30
- source: {
31
- kind: "hub",
32
- repository: "cnmoro/gliclass-base-v3.0-onnx",
33
- revision: "8acca975fd47e89e15f13a4f5446f2ccd1dcf7bb",
34
- files: [{
35
- name: "model.onnx",
36
- path: "model.onnx",
37
- bytes: 747316021,
38
- sha256: "1395fde4ae8de8e41f51080c18a09c48c704b5a1dd34d78950b6c9a11efddd7b"
39
- }, {
40
- name: "tokenizer.json",
41
- path: "tokenizer.json",
42
- bytes: 8649499,
43
- sha256: "9db2e87fbab9819100edd8d6dc7a54f82167045d04bfb752039dae4efb9cd85c"
44
- }]
45
- }
46
- },
47
- {
48
- id: "gliner2.5-small-v1",
49
- name: "GLiNER 2.5 Small",
50
- family: "gliner",
51
- maxTokens: 512,
52
- source: {
53
- kind: "hub",
54
- repository: "nicolasembleton/gliner2.5-small-v1-onnx",
55
- revision: "5e2e3f51adfb0eeb7c1f83464400b4d498d41659",
56
- files: [
57
- {
58
- name: "model.onnx",
59
- path: "onnx/model.onnx",
60
- bytes: 288521577,
61
- sha256: "12dda5cf4b0e9ed3af17596cef1cdbd22185a32fcc230af4f476353b5e4ade1f"
62
- },
63
- {
64
- name: "tokenizer.json",
65
- path: "tokenizer.json",
66
- bytes: 8341713,
67
- sha256: "cbc8ae6037812709c9c26f2a160f8dc48b0440bcb79c8141804259ae2d6adac3"
68
- },
69
- {
70
- name: "tokenizer_config.json",
71
- path: "tokenizer_config.json",
72
- bytes: 646,
73
- sha256: "fd4a31dc2f1f17e31638c5f0e783b81cdb2fbe6bddd116a8d9e5d50d78148cf1"
74
- }
75
- ]
76
- }
77
- },
78
- {
79
- id: "gliner2.5-base-v1",
80
- name: "GLiNER 2.5 Base",
81
- family: "gliner",
82
- maxTokens: 512,
83
- source: {
84
- kind: "hub",
85
- repository: "nicolasembleton/gliner2.5-base-v1-onnx",
86
- revision: "b29dcb3c273644e833837933533ac37274fe585e",
87
- files: [
88
- {
89
- name: "model.onnx",
90
- path: "onnx/model.onnx",
91
- bytes: 746400205,
92
- sha256: "db56fe723c14e856ab5618a5bceb66b55a1e8d2cf5f3026202c45e6ff4b86f42"
93
- },
94
- {
95
- name: "tokenizer.json",
96
- path: "tokenizer.json",
97
- bytes: 8341713,
98
- sha256: "cbc8ae6037812709c9c26f2a160f8dc48b0440bcb79c8141804259ae2d6adac3"
99
- },
100
- {
101
- name: "tokenizer_config.json",
102
- path: "tokenizer_config.json",
103
- bytes: 646,
104
- sha256: "fd4a31dc2f1f17e31638c5f0e783b81cdb2fbe6bddd116a8d9e5d50d78148cf1"
105
- }
106
- ]
107
- }
108
- },
109
- {
110
- id: "deberta-v3-base-zeroshot-v2.0",
111
- name: "DeBERTa Zero-shot v2",
112
- family: "deberta",
113
- maxTokens: 512,
114
- source: {
115
- kind: "hub",
116
- repository: "MoritzLaurer/deberta-v3-base-zeroshot-v2.0",
117
- revision: "8e7e5af5983a0ddb1a5b45a38b129ab69e2258e8",
118
- files: [
119
- {
120
- name: "model.onnx",
121
- path: "onnx/model.onnx",
122
- bytes: 738563249,
123
- sha256: "d46fa6c1addc598abd34af8651120291f51417ddfce45b9d5f70bc32d3efa81c"
124
- },
125
- {
126
- name: "config.json",
127
- path: "config.json",
128
- bytes: 1016,
129
- sha256: "a1c8011b852ae46d6ac26160d358fa595861d261352885f8f7bfcd2811030d9f"
130
- },
131
- {
132
- name: "tokenizer.json",
133
- path: "tokenizer.json",
134
- bytes: 8656646,
135
- sha256: "05402ffae6dd382a8491b1d29bfc139bec5d332662e86a026f433ce54c25c202"
136
- },
137
- {
138
- name: "tokenizer_config.json",
139
- path: "tokenizer_config.json",
140
- bytes: 1256,
141
- sha256: "f5a1a74a632c0e9225e09a21ddf60c2e70ef5d3bfc1f261a24fd8ddab27254d2"
142
- }
143
- ]
144
- }
145
- },
146
- {
147
- id: "gliclass-instruct-edge-v1.0",
148
- name: "GLiClass Instruct Edge (local export)",
149
- family: "gliclass",
150
- maxTokens: 512,
151
- source: {
152
- kind: "local-export",
153
- repository: "knowledgator/gliclass-instruct-edge-v1.0",
154
- revision: "727be8a417f6a7718e591b025e07054c146d8139"
155
- }
156
- },
157
- {
158
- id: "gliclass-instruct-base-v1.0",
159
- name: "GLiClass Instruct Base (local export)",
160
- family: "gliclass",
161
- maxTokens: 512,
162
- source: {
163
- kind: "local-export",
164
- repository: "knowledgator/gliclass-instruct-base-v1.0",
165
- revision: "4f6a108b08a5537f395521d19b5073e197923dd3"
166
- }
167
- }
168
- ];
169
- function findModel(id) {
170
- return MODELS.find((model) => model.id === id);
171
- }
172
- export { findModel as n, MODELS as t };
@@ -1,224 +0,0 @@
1
- import { n as findModel } from "./catalog-0M53kmJq.mjs";
2
- import { i as UnsupportedInputError, t as OnnxWorkerError } from "./protocol-0QYyt_af.mjs";
3
- import { n as readModelArtifact, r as resolveModelFiles } from "./artifacts-BoNZbqnR.mjs";
4
- import { Tokenizer } from "@huggingface/tokenizers";
5
- import { InferenceSession, Tensor } from "onnxruntime-node";
6
- // 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
- // extensions/onnx/src/models/deberta.ts
19
- function createDebertaAdapter({ session, tokenizer, maxTokens }) {
20
- return { async classify({ text, labels, instructions, descriptions }) {
21
- const premise = instructions ? `${instructions}\n${text}` : text;
22
- const encoded = labels.map((label) => {
23
- const hypothesis = descriptions?.[label] ?? `This example is ${label}.`;
24
- const pair = encodeModelText(tokenizer, premise, {
25
- text_pair: hypothesis,
26
- add_special_tokens: true
27
- });
28
- if (pair.ids.length > maxTokens) throw new UnsupportedInputError("DeBERTa input exceeds its token limit; shorten the state or rubric.");
29
- return pair;
30
- });
31
- const logits = [];
32
- const pad = tokenizer.token_to_id("[PAD]");
33
- if (pad === void 0) throw new Error("DeBERTa tokenizer is missing its padding token.");
34
- for (let offset = 0; offset < encoded.length; offset += 8) {
35
- const batch = encoded.slice(offset, offset + 8);
36
- const length = Math.max(...batch.map((pair) => pair.ids.length));
37
- const ids = new BigInt64Array(batch.length * length).fill(BigInt(pad));
38
- const attention = new BigInt64Array(ids.length);
39
- batch.forEach((pair, row) => {
40
- ids.set(BigInt64Array.from(pair.ids, BigInt), row * length);
41
- attention.set(BigInt64Array.from(pair.attention_mask, BigInt), row * length);
42
- });
43
- const shape = [batch.length, length];
44
- const scores = (await session.run({
45
- input_ids: new Tensor("int64", ids, shape),
46
- attention_mask: new Tensor("int64", attention, shape)
47
- })).logits;
48
- 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.");
49
- for (let row = 0; row < batch.length; row++) {
50
- const entailment = scores.data[row * 2];
51
- if (!Number.isFinite(entailment)) throw new Error("DeBERTa returned non-finite logits.");
52
- logits.push(entailment);
53
- }
54
- }
55
- return {
56
- logits,
57
- inputTokens: encoded.reduce((sum, pair) => sum + pair.ids.length, 0)
58
- };
59
- } };
60
- }
61
- // extensions/onnx/src/models/gliclass.ts
62
- function createGliclassAdapter(context) {
63
- const labelToken = context.tokenizer.token_to_id("<<LABEL>>");
64
- const separatorToken = context.tokenizer.token_to_id("<<SEP>>");
65
- const exampleToken = context.tokenizer.token_to_id("<<EXAMPLE>>");
66
- if (labelToken === void 0 || separatorToken === void 0 || labelToken === separatorToken) throw new Error("GLiClass tokenizer is missing its label and separator tokens.");
67
- return { async classify(input) {
68
- const labels = input.labels.map((label) => input.descriptions?.[label] ?? label);
69
- const text = input.instructions ? `${input.instructions}\n${input.text}` : input.text;
70
- 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.");
71
- const packed = `${labels.map((label) => `<<LABEL>>${label}`).join("")}<<SEP>>${text}`;
72
- const encoded = encodeModelText(context.tokenizer, packed);
73
- if (encoded.ids.length > context.maxTokens) throw new UnsupportedInputError(`GLiClass input exceeds its ${context.maxTokens}-token limit; shorten the state or rubric.`);
74
- 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.");
75
- const shape = [1, encoded.ids.length];
76
- const scores = (await context.session.run({
77
- input_ids: new Tensor("int64", BigInt64Array.from(encoded.ids, BigInt), shape),
78
- attention_mask: new Tensor("int64", BigInt64Array.from(encoded.attention_mask, BigInt), shape)
79
- })).logits;
80
- 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.");
81
- const logits = Array.from(scores.data);
82
- if (logits.some((value) => !Number.isFinite(value))) throw new Error("GLiClass returned non-finite label logits.");
83
- return {
84
- logits,
85
- inputTokens: encoded.ids.length
86
- };
87
- } };
88
- }
89
- // extensions/onnx/src/models/gliner.ts
90
- 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;
91
- const RESERVED = /\[(?:P|L|C|E|R|DESCRIPTION|EXAMPLE|OUTPUT|SEP_TEXT|SEP_STRUCT)\]|[()]/u;
92
- function indices(values) {
93
- return new Tensor("int64", BigInt64Array.from(values, BigInt), [1, values.length]);
94
- }
95
- function mask(length, value = 1) {
96
- return new Tensor("float32", new Float32Array(length).fill(value), [1, length]);
97
- }
98
- function createGlinerAdapter({ session, tokenizer, maxTokens }) {
99
- return { async classify({ text, labels, task, instructions, descriptions }) {
100
- if ([
101
- task,
102
- ...labels,
103
- instructions,
104
- ...labels.map((label) => descriptions?.[label])
105
- ].some((value) => value !== void 0 && (!value.trim() || RESERVED.test(value)))) throw new UnsupportedInputError("GLiNER2.5 rubric contains an empty or reserved schema token.");
106
- let prompt = instructions ? `${task}: ${instructions}` : task;
107
- for (const label of labels) if (descriptions?.[label]) prompt += ` [DESCRIPTION] ${label}: ${descriptions[label]}`;
108
- const inputIds = [];
109
- const append = (token) => {
110
- const encoded = encodeModelText(tokenizer, token, { add_special_tokens: false }).ids;
111
- if (encoded.length === 0 || inputIds.length + encoded.length > maxTokens) throw new UnsupportedInputError("GLiNER2.5 input exceeds the token limit or is empty.");
112
- inputIds.push(...encoded);
113
- };
114
- for (const token of [
115
- "(",
116
- "[P]",
117
- prompt,
118
- "("
119
- ]) append(token);
120
- const classificationPositions = [];
121
- for (const label of labels) {
122
- classificationPositions.push(inputIds.length);
123
- append("[L]");
124
- append(label);
125
- }
126
- for (const token of [
127
- ")",
128
- ")",
129
- "[SEP_TEXT]"
130
- ]) append(token);
131
- const normalized = /[.!?]$/.test(text) ? text : `${text}.`;
132
- const wordPositions = [];
133
- for (const match of normalized.matchAll(WORDS)) {
134
- wordPositions.push(inputIds.length);
135
- append(match[0].toLowerCase());
136
- }
137
- const feeds = {
138
- input_ids: indices(inputIds),
139
- attention_mask: indices(inputIds.map(() => 1)),
140
- text_word_indices: indices(wordPositions),
141
- text_word_mask: mask(wordPositions.length),
142
- query_marker_indices: indices([0]),
143
- query_marker_mask: mask(1, 0),
144
- cls_marker_indices: indices(classificationPositions),
145
- cls_marker_mask: mask(labels.length),
146
- rel_marker_indices: indices([0]),
147
- rel_marker_mask: mask(1, 0)
148
- };
149
- const output = (await session.run(feeds, ["cls_logits"])).cls_logits;
150
- 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.");
151
- const logits = Array.from(output.data, Number);
152
- if (logits.some((value) => !Number.isFinite(value))) throw new Error("GLiNER2.5 returned non-finite classification logits.");
153
- return {
154
- logits,
155
- inputTokens: inputIds.length
156
- };
157
- } };
158
- }
159
- // extensions/onnx/src/model-loader.ts
160
- function jsonObject(data) {
161
- const parsed = JSON.parse(data.toString("utf8"));
162
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new OnnxWorkerError("model-integrity");
163
- return parsed;
164
- }
165
- var ModelCache = class {
166
- constructor(config) {
167
- this.config = config;
168
- this.models = /* @__PURE__ */ new Map();
169
- }
170
- async close() {
171
- const models = [...this.models.values()];
172
- this.models.clear();
173
- const failures = (await Promise.allSettled(models.map(({ session }) => session.release()))).filter((result) => result.status === "rejected");
174
- if (failures.length > 0) throw new AggregateError(failures.map((result) => result.reason), "ONNX session release failed");
175
- }
176
- async get(id) {
177
- const existing = this.models.get(id);
178
- if (existing) {
179
- this.models.delete(id);
180
- this.models.set(id, existing);
181
- return existing.adapter;
182
- }
183
- const model = findModel(id);
184
- if (!model) throw new UnsupportedInputError("Unknown ONNX model.");
185
- const files = await resolveModelFiles(this.config.modelDir, model);
186
- const buffers = /* @__PURE__ */ new Map();
187
- for (const file of files) buffers.set(file.name, await readModelArtifact(this.config.modelDir, model, file));
188
- const modelBytes = buffers.get("model.onnx");
189
- const tokenizerBytes = buffers.get("tokenizer.json");
190
- if (!modelBytes || !tokenizerBytes) throw new OnnxWorkerError("model-integrity");
191
- const tokenizerConfig = buffers.get("tokenizer_config.json");
192
- const tokenizer = new Tokenizer(jsonObject(tokenizerBytes), tokenizerConfig ? jsonObject(tokenizerConfig) : {});
193
- if (this.models.size >= this.config.maxLoadedModels) {
194
- const first = this.models.entries().next().value;
195
- if (first) {
196
- this.models.delete(first[0]);
197
- await first[1].session.release();
198
- }
199
- }
200
- const session = await InferenceSession.create(modelBytes, {
201
- executionProviders: ["cpu"],
202
- intraOpNumThreads: this.config.threads,
203
- interOpNumThreads: 1,
204
- logSeverityLevel: 3
205
- });
206
- try {
207
- const context = {
208
- session,
209
- tokenizer,
210
- maxTokens: model.maxTokens
211
- };
212
- const adapter = model.family === "gliclass" ? createGliclassAdapter(context) : model.family === "gliner" ? createGlinerAdapter(context) : createDebertaAdapter(context);
213
- this.models.set(id, {
214
- session,
215
- adapter
216
- });
217
- return adapter;
218
- } catch (error) {
219
- await session.release();
220
- throw error;
221
- }
222
- }
223
- };
224
- export { ModelCache };