@openclaw/onnx 2026.10.10-beta.5 → 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,11 +1,12 @@
1
- import { n as findModel } from "./.setup/catalog-Bgbx4LHv.mjs";
2
- import { n as createOnnxProvider, t as InferenceWorkerClient } from "./.setup/worker-client-DUApeDD4.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
- //#region extensions/onnx/src/config.ts
9
+ // extensions/onnx/src/config.ts
9
10
  const ConfigSchema = Type.Object({
10
11
  modelDir: Type.Optional(Type.String({
11
12
  minLength: 1,
@@ -33,8 +34,7 @@ function resolveOnnxConfig(config, resolvePath) {
33
34
  maxLoadedModels
34
35
  };
35
36
  }
36
- //#endregion
37
- //#region extensions/onnx/index.ts
37
+ // extensions/onnx/index.ts
38
38
  function selectedModels(config) {
39
39
  const selectors = [config.agents?.defaults?.decisionModel, ...Object.values(config.agents?.entries ?? {}).map((agent) => agent.decisionModel)];
40
40
  return [...new Set(selectors.flatMap((selector) => {
@@ -50,29 +50,29 @@ var onnx_default = definePluginEntry({
50
50
  configSchema: { jsonSchema: { ...ConfigSchema } },
51
51
  register(api) {
52
52
  if (!api.runtimeSource) throw new Error("ONNX requires runtime entrypoint metadata from its OpenClaw host.");
53
- const workerUrl = new URL(`./src/inference.worker${path.extname(api.runtimeSource)}`, pathToFileURL(api.runtimeSource));
53
+ const workerUrl = resolveRuntimeWorkerUrl(createPluginRuntimeProcessEntrypoint("onnxInference", pathToFileURL(api.runtimeSource).href));
54
54
  const config = resolveOnnxConfig(api.pluginConfig, api.resolvePath);
55
55
  const client = new InferenceWorkerClient({
56
56
  workerUrl,
57
57
  config
58
58
  });
59
- api.registerDecisionProvider(createOnnxProvider(client, (message) => api.logger.warn(message)));
59
+ api.registerDecisionProvider(createPreparedOnnxProvider(client, (message) => api.logger.warn(message)));
60
60
  api.registerService({
61
61
  id: "onnx-worker",
62
62
  async start(context) {
63
63
  const models = selectedModels(context.config).slice(0, config.maxLoadedModels);
64
64
  if (models.length === 0) return;
65
65
  try {
66
- 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] : []]));
67
67
  } catch {
68
68
  context.logger.warn("ONNX models are not ready. Run openclaw onnx models and verify/download the selected artifacts.");
69
69
  }
70
70
  },
71
71
  stop: () => client.stop()
72
72
  });
73
- api.lifecycle?.onDispose?.(() => client.stop());
73
+ api.lifecycle.onDispose?.(() => client.stop());
74
74
  api.registerCli(async (context) => {
75
- const { registerOnnxCli } = await import("./.setup/cli-Bs1V3EDP.mjs");
75
+ const { registerOnnxCli } = await import("./.setup/cli-wozJmsLz.mjs");
76
76
  registerOnnxCli(context, config, workerUrl, api.resolvePath);
77
77
  }, { descriptors: [{
78
78
  name: "onnx",
@@ -81,5 +81,4 @@ var onnx_default = definePluginEntry({
81
81
  }] });
82
82
  }
83
83
  });
84
- //#endregion
85
84
  export { onnx_default as default };
@@ -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,5 +1,5 @@
1
- import { i as UnsupportedInputError, r as parseWorkerRequest, t as OnnxWorkerError } from "../.setup/protocol-lN8zQ8J3.mjs";
2
- //#region extensions/onnx/src/inference.worker.ts
1
+ import { n as UnsupportedInputError, t as OnnxWorkerError } from "../.setup/protocol-CG1ILdRP.mjs";
2
+ // extensions/onnx/src/inference.worker.ts
3
3
  let config;
4
4
  let cache;
5
5
  let stopping = false;
@@ -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-C6GHyZWy.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,17 +66,14 @@ 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
  }
91
78
  }
92
- //#endregion
93
79
  export {};
@@ -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-beta.5",
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-beta.5"
31
+ "pluginApi": ">=2026.11.5-beta.1"
32
32
  },
33
33
  "build": {
34
34
  "bundledDist": false,
35
- "openclawVersion": "2026.10.10-beta.5",
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-beta.5"
63
+ "openclaw": ">=2026.11.5-beta.1"
64
64
  },
65
65
  "peerDependenciesMeta": {
66
66
  "openclaw": {
@@ -1,173 +0,0 @@
1
- //#region 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
- //#endregion
173
- export { findModel as n, MODELS as t };
@@ -1,229 +0,0 @@
1
- import { n as findModel } from "./catalog-Bgbx4LHv.mjs";
2
- import { i as UnsupportedInputError, t as OnnxWorkerError } from "./protocol-lN8zQ8J3.mjs";
3
- import { n as readModelArtifact, r as resolveModelFiles } from "./artifacts-CD0XZUIN.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/models/deberta.ts
20
- function createDebertaAdapter({ session, tokenizer, maxTokens }) {
21
- return { async classify({ text, labels, instructions, descriptions }) {
22
- const premise = instructions ? `${instructions}\n${text}` : text;
23
- const encoded = labels.map((label) => {
24
- const hypothesis = descriptions?.[label] ?? `This example is ${label}.`;
25
- const pair = encodeModelText(tokenizer, premise, {
26
- text_pair: hypothesis,
27
- add_special_tokens: true
28
- });
29
- if (pair.ids.length > maxTokens) throw new UnsupportedInputError("DeBERTa input exceeds its token limit; shorten the state or rubric.");
30
- return pair;
31
- });
32
- const logits = [];
33
- const pad = tokenizer.token_to_id("[PAD]");
34
- if (pad === void 0) throw new Error("DeBERTa tokenizer is missing its padding token.");
35
- for (let offset = 0; offset < encoded.length; offset += 8) {
36
- const batch = encoded.slice(offset, offset + 8);
37
- const length = Math.max(...batch.map((pair) => pair.ids.length));
38
- const ids = new BigInt64Array(batch.length * length).fill(BigInt(pad));
39
- const attention = new BigInt64Array(ids.length);
40
- batch.forEach((pair, row) => {
41
- ids.set(BigInt64Array.from(pair.ids, BigInt), row * length);
42
- attention.set(BigInt64Array.from(pair.attention_mask, BigInt), row * length);
43
- });
44
- const shape = [batch.length, length];
45
- const scores = (await session.run({
46
- input_ids: new Tensor("int64", ids, shape),
47
- attention_mask: new Tensor("int64", attention, shape)
48
- })).logits;
49
- 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.");
50
- for (let row = 0; row < batch.length; row++) {
51
- const entailment = scores.data[row * 2];
52
- if (!Number.isFinite(entailment)) throw new Error("DeBERTa returned non-finite logits.");
53
- logits.push(entailment);
54
- }
55
- }
56
- return {
57
- logits,
58
- inputTokens: encoded.reduce((sum, pair) => sum + pair.ids.length, 0)
59
- };
60
- } };
61
- }
62
- //#endregion
63
- //#region extensions/onnx/src/models/gliclass.ts
64
- function createGliclassAdapter(context) {
65
- const labelToken = context.tokenizer.token_to_id("<<LABEL>>");
66
- const separatorToken = context.tokenizer.token_to_id("<<SEP>>");
67
- const exampleToken = context.tokenizer.token_to_id("<<EXAMPLE>>");
68
- if (labelToken === void 0 || separatorToken === void 0 || labelToken === separatorToken) throw new Error("GLiClass tokenizer is missing its label and separator tokens.");
69
- return { async classify(input) {
70
- const labels = input.labels.map((label) => input.descriptions?.[label] ?? label);
71
- const text = input.instructions ? `${input.instructions}\n${input.text}` : input.text;
72
- 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.");
73
- const packed = `${labels.map((label) => `<<LABEL>>${label}`).join("")}<<SEP>>${text}`;
74
- const encoded = encodeModelText(context.tokenizer, packed);
75
- if (encoded.ids.length > context.maxTokens) throw new UnsupportedInputError(`GLiClass input exceeds its ${context.maxTokens}-token limit; shorten the state or rubric.`);
76
- 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.");
77
- const shape = [1, encoded.ids.length];
78
- const scores = (await context.session.run({
79
- input_ids: new Tensor("int64", BigInt64Array.from(encoded.ids, BigInt), shape),
80
- attention_mask: new Tensor("int64", BigInt64Array.from(encoded.attention_mask, BigInt), shape)
81
- })).logits;
82
- 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.");
83
- const logits = Array.from(scores.data);
84
- if (logits.some((value) => !Number.isFinite(value))) throw new Error("GLiClass returned non-finite label logits.");
85
- return {
86
- logits,
87
- inputTokens: encoded.ids.length
88
- };
89
- } };
90
- }
91
- //#endregion
92
- //#region extensions/onnx/src/models/gliner.ts
93
- 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;
94
- const RESERVED = /\[(?:P|L|C|E|R|DESCRIPTION|EXAMPLE|OUTPUT|SEP_TEXT|SEP_STRUCT)\]|[()]/u;
95
- function indices(values) {
96
- return new Tensor("int64", BigInt64Array.from(values, BigInt), [1, values.length]);
97
- }
98
- function mask(length, value = 1) {
99
- return new Tensor("float32", new Float32Array(length).fill(value), [1, length]);
100
- }
101
- function createGlinerAdapter({ session, tokenizer, maxTokens }) {
102
- return { async classify({ text, labels, task, instructions, descriptions }) {
103
- if ([
104
- task,
105
- ...labels,
106
- instructions,
107
- ...labels.map((label) => descriptions?.[label])
108
- ].some((value) => value !== void 0 && (!value.trim() || RESERVED.test(value)))) throw new UnsupportedInputError("GLiNER2.5 rubric contains an empty or reserved schema token.");
109
- let prompt = instructions ? `${task}: ${instructions}` : task;
110
- for (const label of labels) if (descriptions?.[label]) prompt += ` [DESCRIPTION] ${label}: ${descriptions[label]}`;
111
- const inputIds = [];
112
- const append = (token) => {
113
- const encoded = encodeModelText(tokenizer, token, { add_special_tokens: false }).ids;
114
- if (encoded.length === 0 || inputIds.length + encoded.length > maxTokens) throw new UnsupportedInputError("GLiNER2.5 input exceeds the token limit or is empty.");
115
- inputIds.push(...encoded);
116
- };
117
- for (const token of [
118
- "(",
119
- "[P]",
120
- prompt,
121
- "("
122
- ]) append(token);
123
- const classificationPositions = [];
124
- for (const label of labels) {
125
- classificationPositions.push(inputIds.length);
126
- append("[L]");
127
- append(label);
128
- }
129
- for (const token of [
130
- ")",
131
- ")",
132
- "[SEP_TEXT]"
133
- ]) append(token);
134
- const normalized = /[.!?]$/.test(text) ? text : `${text}.`;
135
- const wordPositions = [];
136
- for (const match of normalized.matchAll(WORDS)) {
137
- wordPositions.push(inputIds.length);
138
- append(match[0].toLowerCase());
139
- }
140
- const feeds = {
141
- input_ids: indices(inputIds),
142
- attention_mask: indices(inputIds.map(() => 1)),
143
- text_word_indices: indices(wordPositions),
144
- text_word_mask: mask(wordPositions.length),
145
- query_marker_indices: indices([0]),
146
- query_marker_mask: mask(1, 0),
147
- cls_marker_indices: indices(classificationPositions),
148
- cls_marker_mask: mask(labels.length),
149
- rel_marker_indices: indices([0]),
150
- rel_marker_mask: mask(1, 0)
151
- };
152
- const output = (await session.run(feeds, ["cls_logits"])).cls_logits;
153
- 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.");
154
- const logits = Array.from(output.data, Number);
155
- if (logits.some((value) => !Number.isFinite(value))) throw new Error("GLiNER2.5 returned non-finite classification logits.");
156
- return {
157
- logits,
158
- inputTokens: inputIds.length
159
- };
160
- } };
161
- }
162
- //#endregion
163
- //#region extensions/onnx/src/model-loader.ts
164
- function jsonObject(data) {
165
- const parsed = JSON.parse(data.toString("utf8"));
166
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new OnnxWorkerError("model-integrity");
167
- return parsed;
168
- }
169
- var ModelCache = class {
170
- constructor(config) {
171
- this.config = config;
172
- this.models = /* @__PURE__ */ new Map();
173
- }
174
- async close() {
175
- const models = [...this.models.values()];
176
- this.models.clear();
177
- const failures = (await Promise.allSettled(models.map(({ session }) => session.release()))).filter((result) => result.status === "rejected");
178
- if (failures.length > 0) throw new AggregateError(failures.map((result) => result.reason), "ONNX session release failed");
179
- }
180
- async get(id) {
181
- const existing = this.models.get(id);
182
- if (existing) {
183
- this.models.delete(id);
184
- this.models.set(id, existing);
185
- return existing.adapter;
186
- }
187
- const model = findModel(id);
188
- if (!model) throw new UnsupportedInputError("Unknown ONNX model.");
189
- const files = await resolveModelFiles(this.config.modelDir, model);
190
- const buffers = /* @__PURE__ */ new Map();
191
- for (const file of files) buffers.set(file.name, await readModelArtifact(this.config.modelDir, model, file));
192
- const modelBytes = buffers.get("model.onnx");
193
- const tokenizerBytes = buffers.get("tokenizer.json");
194
- if (!modelBytes || !tokenizerBytes) throw new OnnxWorkerError("model-integrity");
195
- const tokenizerConfig = buffers.get("tokenizer_config.json");
196
- const tokenizer = new Tokenizer(jsonObject(tokenizerBytes), tokenizerConfig ? jsonObject(tokenizerConfig) : {});
197
- if (this.models.size >= this.config.maxLoadedModels) {
198
- const first = this.models.entries().next().value;
199
- if (first) {
200
- this.models.delete(first[0]);
201
- await first[1].session.release();
202
- }
203
- }
204
- const session = await InferenceSession.create(modelBytes, {
205
- executionProviders: ["cpu"],
206
- intraOpNumThreads: this.config.threads,
207
- interOpNumThreads: 1,
208
- logSeverityLevel: 3
209
- });
210
- try {
211
- const context = {
212
- session,
213
- tokenizer,
214
- maxTokens: model.maxTokens
215
- };
216
- const adapter = model.family === "gliclass" ? createGliclassAdapter(context) : model.family === "gliner" ? createGlinerAdapter(context) : createDebertaAdapter(context);
217
- this.models.set(id, {
218
- session,
219
- adapter
220
- });
221
- return adapter;
222
- } catch (error) {
223
- await session.release();
224
- throw error;
225
- }
226
- }
227
- };
228
- //#endregion
229
- export { ModelCache };