@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/README.md +5 -4
- package/dist/.setup/{artifacts-BoNZbqnR.mjs → artifacts-DgGGpngs.mjs} +2 -2
- package/dist/.setup/catalog-g9or975s.mjs +46 -0
- package/dist/.setup/{cli-Dc9p3Cjs.mjs → cli-wozJmsLz.mjs} +3 -3
- package/dist/.setup/model-loader-DDsav9p5.mjs +212 -0
- package/dist/.setup/protocol-CG1ILdRP.mjs +10 -0
- package/dist/.setup/{worker-client-cQ1VR-j4.mjs → worker-client-C6PMT6Zd.mjs} +120 -62
- package/dist/.source-module-urls/c006b803da4ad0d774d12fd121a0790ab987a6423243e5bb28b74c5ce87a8b57.json +1 -1
- package/dist/index.js +9 -8
- package/dist/scripts/export-gliclass-instruct.py +4 -24
- package/dist/src/inference.worker.js +8 -21
- package/openclaw.plugin.json +14 -0
- package/package.json +5 -5
- package/dist/.setup/catalog-0M53kmJq.mjs +0 -172
- package/dist/.setup/model-loader-Dkk1GRxt.mjs +0 -224
- package/dist/.setup/protocol-0QYyt_af.mjs +0 -113
package/README.md
CHANGED
|
@@ -6,11 +6,12 @@ persistent CPU inference process.
|
|
|
6
6
|
|
|
7
7
|
## Setup
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
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
|
|
13
|
-
|
|
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-
|
|
1
|
+
import { t as OnnxWorkerError } from "./protocol-CG1ILdRP.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
|
// extensions/onnx/src/artifacts.ts
|
|
9
9
|
const ExportSchema = Type.Object({
|
|
10
10
|
modelId: Type.String(),
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// 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
|
+
export { findModel as n, MODELS as t };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as findModel, t as MODELS } from "./catalog-
|
|
2
|
-
import { n as createOnnxProvider, t as InferenceWorkerClient } from "./worker-client-
|
|
3
|
-
import { i as verifyModel, t as downloadModel } from "./artifacts-
|
|
1
|
+
import { n as findModel, t as MODELS } from "./catalog-g9or975s.mjs";
|
|
2
|
+
import { n as createOnnxProvider, t as InferenceWorkerClient } from "./worker-client-C6PMT6Zd.mjs";
|
|
3
|
+
import { i as verifyModel, t as downloadModel } from "./artifacts-DgGGpngs.mjs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
// extensions/onnx/src/cli.ts
|
|
6
6
|
function registerOnnxCli({ program }, settings, workerUrl, resolvePath) {
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { n as findModel } from "./catalog-g9or975s.mjs";
|
|
2
|
+
import { n as UnsupportedInputError, t as OnnxWorkerError } from "./protocol-CG1ILdRP.mjs";
|
|
3
|
+
import { n as readModelArtifact, r as resolveModelFiles } from "./artifacts-DgGGpngs.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/model-loader.ts
|
|
19
|
+
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;
|
|
20
|
+
const RESERVED = /\[(?:P|L|C|E|R|DESCRIPTION|EXAMPLE|OUTPUT|SEP_TEXT|SEP_STRUCT)\]|[()]/u;
|
|
21
|
+
function indices(values) {
|
|
22
|
+
return new Tensor("int64", BigInt64Array.from(values, BigInt), [1, values.length]);
|
|
23
|
+
}
|
|
24
|
+
function mask(length, value = 1) {
|
|
25
|
+
return new Tensor("float32", new Float32Array(length).fill(value), [1, length]);
|
|
26
|
+
}
|
|
27
|
+
function jsonObject(data) {
|
|
28
|
+
const parsed = JSON.parse(data.toString("utf8"));
|
|
29
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new OnnxWorkerError("model-integrity");
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
var ModelCache = class {
|
|
33
|
+
constructor(config) {
|
|
34
|
+
this.config = config;
|
|
35
|
+
this.models = /* @__PURE__ */ new Map();
|
|
36
|
+
}
|
|
37
|
+
async close() {
|
|
38
|
+
const models = [...this.models.values()];
|
|
39
|
+
this.models.clear();
|
|
40
|
+
const failures = (await Promise.allSettled(models.map(({ session }) => session.release()))).filter((result) => result.status === "rejected");
|
|
41
|
+
if (failures.length > 0) throw new AggregateError(failures.map((result) => result.reason), "ONNX session release failed");
|
|
42
|
+
}
|
|
43
|
+
async get(id) {
|
|
44
|
+
const existing = this.models.get(id);
|
|
45
|
+
if (existing) {
|
|
46
|
+
this.models.delete(id);
|
|
47
|
+
this.models.set(id, existing);
|
|
48
|
+
return existing.adapter;
|
|
49
|
+
}
|
|
50
|
+
const model = findModel(id);
|
|
51
|
+
if (!model) throw new UnsupportedInputError("Unknown ONNX model.");
|
|
52
|
+
const files = await resolveModelFiles(this.config.modelDir, model);
|
|
53
|
+
const buffers = /* @__PURE__ */ new Map();
|
|
54
|
+
for (const file of files) buffers.set(file.name, await readModelArtifact(this.config.modelDir, model, file));
|
|
55
|
+
const modelBytes = buffers.get("model.onnx");
|
|
56
|
+
const tokenizerBytes = buffers.get("tokenizer.json");
|
|
57
|
+
if (!modelBytes || !tokenizerBytes) throw new OnnxWorkerError("model-integrity");
|
|
58
|
+
const tokenizerConfig = buffers.get("tokenizer_config.json");
|
|
59
|
+
const tokenizer = new Tokenizer(jsonObject(tokenizerBytes), tokenizerConfig ? jsonObject(tokenizerConfig) : {});
|
|
60
|
+
if (this.models.size >= this.config.maxLoadedModels) {
|
|
61
|
+
const first = this.models.entries().next().value;
|
|
62
|
+
if (first) {
|
|
63
|
+
this.models.delete(first[0]);
|
|
64
|
+
await first[1].session.release();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const session = await InferenceSession.create(modelBytes, {
|
|
68
|
+
executionProviders: ["cpu"],
|
|
69
|
+
intraOpNumThreads: this.config.threads,
|
|
70
|
+
interOpNumThreads: 1,
|
|
71
|
+
logSeverityLevel: 3
|
|
72
|
+
});
|
|
73
|
+
try {
|
|
74
|
+
const maxTokens = model.maxTokens;
|
|
75
|
+
let adapter;
|
|
76
|
+
if (model.family === "gliclass") {
|
|
77
|
+
const labelToken = tokenizer.token_to_id("<<LABEL>>");
|
|
78
|
+
const separatorToken = tokenizer.token_to_id("<<SEP>>");
|
|
79
|
+
const exampleToken = tokenizer.token_to_id("<<EXAMPLE>>");
|
|
80
|
+
if (labelToken === void 0 || separatorToken === void 0 || labelToken === separatorToken) throw new Error("GLiClass tokenizer is missing its label and separator tokens.");
|
|
81
|
+
adapter = { async classify(input) {
|
|
82
|
+
const labels = input.labels.map((label) => input.descriptions?.[label] ?? label);
|
|
83
|
+
const text = input.instructions ? `${input.instructions}\n${input.text}` : input.text;
|
|
84
|
+
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.");
|
|
85
|
+
const packed = `${labels.map((label) => `<<LABEL>>${label}`).join("")}<<SEP>>${text}`;
|
|
86
|
+
const encoded = encodeModelText(tokenizer, packed);
|
|
87
|
+
if (encoded.ids.length > maxTokens) throw new UnsupportedInputError(`GLiClass input exceeds its ${maxTokens}-token limit; shorten the state or rubric.`);
|
|
88
|
+
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.");
|
|
89
|
+
const shape = [1, encoded.ids.length];
|
|
90
|
+
const scores = (await session.run({
|
|
91
|
+
input_ids: new Tensor("int64", BigInt64Array.from(encoded.ids, BigInt), shape),
|
|
92
|
+
attention_mask: new Tensor("int64", BigInt64Array.from(encoded.attention_mask, BigInt), shape)
|
|
93
|
+
})).logits;
|
|
94
|
+
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.");
|
|
95
|
+
const logits = Array.from(scores.data);
|
|
96
|
+
if (logits.some((value) => !Number.isFinite(value))) throw new Error("GLiClass returned non-finite label logits.");
|
|
97
|
+
return {
|
|
98
|
+
logits,
|
|
99
|
+
inputTokens: encoded.ids.length
|
|
100
|
+
};
|
|
101
|
+
} };
|
|
102
|
+
} else if (model.family === "gliner") adapter = { 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
|
+
else adapter = { async classify({ text, labels, instructions, descriptions }) {
|
|
162
|
+
const premise = instructions ? `${instructions}\n${text}` : text;
|
|
163
|
+
const encoded = labels.map((label) => {
|
|
164
|
+
const hypothesis = descriptions?.[label] ?? `This example is ${label}.`;
|
|
165
|
+
const pair = encodeModelText(tokenizer, premise, {
|
|
166
|
+
text_pair: hypothesis,
|
|
167
|
+
add_special_tokens: true
|
|
168
|
+
});
|
|
169
|
+
if (pair.ids.length > maxTokens) throw new UnsupportedInputError("DeBERTa input exceeds its token limit; shorten the state or rubric.");
|
|
170
|
+
return pair;
|
|
171
|
+
});
|
|
172
|
+
const logits = [];
|
|
173
|
+
const pad = tokenizer.token_to_id("[PAD]");
|
|
174
|
+
if (pad === void 0) throw new Error("DeBERTa tokenizer is missing its padding token.");
|
|
175
|
+
for (let offset = 0; offset < encoded.length; offset += 8) {
|
|
176
|
+
const batch = encoded.slice(offset, offset + 8);
|
|
177
|
+
const length = Math.max(...batch.map((pair) => pair.ids.length));
|
|
178
|
+
const ids = new BigInt64Array(batch.length * length).fill(BigInt(pad));
|
|
179
|
+
const attention = new BigInt64Array(ids.length);
|
|
180
|
+
batch.forEach((pair, row) => {
|
|
181
|
+
ids.set(BigInt64Array.from(pair.ids, BigInt), row * length);
|
|
182
|
+
attention.set(BigInt64Array.from(pair.attention_mask, BigInt), row * length);
|
|
183
|
+
});
|
|
184
|
+
const shape = [batch.length, length];
|
|
185
|
+
const scores = (await session.run({
|
|
186
|
+
input_ids: new Tensor("int64", ids, shape),
|
|
187
|
+
attention_mask: new Tensor("int64", attention, shape)
|
|
188
|
+
})).logits;
|
|
189
|
+
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.");
|
|
190
|
+
for (let row = 0; row < batch.length; row++) {
|
|
191
|
+
const entailment = scores.data[row * 2];
|
|
192
|
+
if (!Number.isFinite(entailment)) throw new Error("DeBERTa returned non-finite logits.");
|
|
193
|
+
logits.push(entailment);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
logits,
|
|
198
|
+
inputTokens: encoded.reduce((sum, pair) => sum + pair.ids.length, 0)
|
|
199
|
+
};
|
|
200
|
+
} };
|
|
201
|
+
this.models.set(id, {
|
|
202
|
+
session,
|
|
203
|
+
adapter
|
|
204
|
+
});
|
|
205
|
+
return adapter;
|
|
206
|
+
} catch (error) {
|
|
207
|
+
await session.release();
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
export { ModelCache };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// extensions/onnx/src/models/types.ts
|
|
2
|
+
var UnsupportedInputError = class extends Error {};
|
|
3
|
+
// extensions/onnx/src/protocol.ts
|
|
4
|
+
var OnnxWorkerError = class extends Error {
|
|
5
|
+
constructor(code) {
|
|
6
|
+
super(`ONNX worker: ${code}`);
|
|
7
|
+
this.code = code;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
export { UnsupportedInputError as n, OnnxWorkerError as t };
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { n as findModel } from "./catalog-
|
|
2
|
-
import {
|
|
3
|
-
import { createDeferred } from "openclaw/plugin-sdk/concurrency-runtime";
|
|
1
|
+
import { n as findModel } from "./catalog-g9or975s.mjs";
|
|
2
|
+
import { n as UnsupportedInputError, t as OnnxWorkerError } from "./protocol-CG1ILdRP.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
|
// 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
|
// extensions/onnx/src/worker-client.ts
|
|
126
207
|
function workerEnv() {
|
|
127
208
|
const env = {};
|
|
@@ -139,29 +220,28 @@ function workerEnv() {
|
|
|
139
220
|
var InferenceWorkerClient = class {
|
|
140
221
|
constructor(options) {
|
|
141
222
|
this.queue = [];
|
|
142
|
-
this.nextId = 0;
|
|
143
223
|
this.closed = false;
|
|
144
|
-
this.workerUrl =
|
|
145
|
-
this.config =
|
|
224
|
+
this.workerUrl = options.workerUrl;
|
|
225
|
+
this.config = options.config;
|
|
146
226
|
}
|
|
147
|
-
async classify(model, inputs, signal) {
|
|
148
|
-
|
|
227
|
+
async classify(model, inputs, signal, isAdmissible) {
|
|
228
|
+
signal.throwIfAborted();
|
|
229
|
+
if (!model.length || !Guard.IsMaxLength(model, 128) || inputs.length < 1 || inputs.length > 32) throw new OnnxWorkerError("unsupported-input");
|
|
230
|
+
let bytes = 0;
|
|
231
|
+
for (const input of inputs) {
|
|
232
|
+
bytes += Buffer.byteLength(JSON.stringify(input));
|
|
233
|
+
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");
|
|
234
|
+
}
|
|
235
|
+
return (await this.enqueue({
|
|
149
236
|
kind: "classify",
|
|
150
|
-
id: ++this.nextId,
|
|
151
237
|
model,
|
|
152
|
-
inputs
|
|
153
|
-
|
|
154
|
-
labels: [...input.labels]
|
|
155
|
-
}))
|
|
156
|
-
}, signal);
|
|
157
|
-
if (reply.kind !== "results") throw new OnnxWorkerError("runtime");
|
|
158
|
-
return reply.results;
|
|
238
|
+
inputs
|
|
239
|
+
}, signal, isAdmissible)).results;
|
|
159
240
|
}
|
|
160
241
|
async warm(models, signal) {
|
|
161
242
|
await this.enqueue({
|
|
162
243
|
kind: "warm",
|
|
163
|
-
|
|
164
|
-
models: [...models]
|
|
244
|
+
models
|
|
165
245
|
}, signal);
|
|
166
246
|
}
|
|
167
247
|
stop() {
|
|
@@ -176,19 +256,14 @@ var InferenceWorkerClient = class {
|
|
|
176
256
|
this.stopping = worker?.closed ?? Promise.resolve();
|
|
177
257
|
return this.stopping;
|
|
178
258
|
}
|
|
179
|
-
enqueue(request, signal) {
|
|
259
|
+
enqueue(request, signal, isAdmissible) {
|
|
180
260
|
signal.throwIfAborted();
|
|
181
|
-
try {
|
|
182
|
-
parseWorkerRequest(request);
|
|
183
|
-
} catch {
|
|
184
|
-
return Promise.reject(new OnnxWorkerError("unsupported-input"));
|
|
185
|
-
}
|
|
186
261
|
if (this.closed || this.queue.length + (this.active ? 1 : 0) >= 4) return Promise.reject(new OnnxWorkerError("runtime"));
|
|
187
262
|
return new Promise((resolve, reject) => {
|
|
188
263
|
const task = {
|
|
189
264
|
request,
|
|
190
265
|
signal,
|
|
191
|
-
|
|
266
|
+
isAdmissible,
|
|
192
267
|
resolve,
|
|
193
268
|
reject,
|
|
194
269
|
abort: () => this.cancel(task)
|
|
@@ -216,20 +291,23 @@ var InferenceWorkerClient = class {
|
|
|
216
291
|
const task = this.queue.shift();
|
|
217
292
|
if (!task) return;
|
|
218
293
|
this.active = task;
|
|
294
|
+
try {
|
|
295
|
+
if (task.isAdmissible && !task.isAdmissible()) throw new OnnxWorkerError("runtime");
|
|
296
|
+
} catch (error) {
|
|
297
|
+
this.finish(void 0, error);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
219
300
|
if (!this.worker) {
|
|
220
301
|
try {
|
|
221
|
-
this.start();
|
|
302
|
+
this.start(task.request);
|
|
222
303
|
} catch {
|
|
223
304
|
this.finish(void 0, new OnnxWorkerError("runtime"));
|
|
224
305
|
}
|
|
225
306
|
return;
|
|
226
307
|
}
|
|
227
|
-
|
|
228
|
-
this.send(this.worker, task.request);
|
|
229
|
-
task.sent = true;
|
|
230
|
-
}
|
|
308
|
+
this.send(this.worker, task.request);
|
|
231
309
|
}
|
|
232
|
-
start() {
|
|
310
|
+
start(request) {
|
|
233
311
|
const child = spawnOomScoreAdjusted(process.execPath, resolveRuntimeWorkerArgv(this.workerUrl), {
|
|
234
312
|
env: workerEnv(),
|
|
235
313
|
shell: false,
|
|
@@ -244,13 +322,12 @@ var InferenceWorkerClient = class {
|
|
|
244
322
|
const { promise: closed, resolve: resolveClosed } = createDeferred();
|
|
245
323
|
const worker = {
|
|
246
324
|
child,
|
|
247
|
-
ready: false,
|
|
248
325
|
retiring: false,
|
|
249
326
|
closed,
|
|
250
327
|
resolveClosed
|
|
251
328
|
};
|
|
252
329
|
this.worker = worker;
|
|
253
|
-
child.on("message", (
|
|
330
|
+
child.on("message", (reply) => this.receive(worker, reply));
|
|
254
331
|
const onFailure = () => {
|
|
255
332
|
if (this.worker === worker) this.retire(new OnnxWorkerError("runtime"));
|
|
256
333
|
};
|
|
@@ -269,6 +346,7 @@ var InferenceWorkerClient = class {
|
|
|
269
346
|
kind: "init",
|
|
270
347
|
config: this.config
|
|
271
348
|
});
|
|
349
|
+
this.send(worker, request);
|
|
272
350
|
}
|
|
273
351
|
send(worker, request) {
|
|
274
352
|
try {
|
|
@@ -279,33 +357,13 @@ var InferenceWorkerClient = class {
|
|
|
279
357
|
if (this.worker === worker) this.retire(new OnnxWorkerError("runtime"));
|
|
280
358
|
}
|
|
281
359
|
}
|
|
282
|
-
receive(worker,
|
|
360
|
+
receive(worker, reply) {
|
|
283
361
|
if (this.worker !== worker || worker.retiring) return;
|
|
284
|
-
let reply;
|
|
285
|
-
try {
|
|
286
|
-
reply = parseWorkerReply(message);
|
|
287
|
-
} catch {
|
|
288
|
-
this.retire(new OnnxWorkerError("runtime"));
|
|
289
|
-
return;
|
|
290
|
-
}
|
|
291
|
-
const task = this.active;
|
|
292
|
-
if (reply.kind === "ready" && !worker.ready && task) {
|
|
293
|
-
worker.ready = true;
|
|
294
|
-
task.sent = true;
|
|
295
|
-
this.send(worker, task.request);
|
|
296
|
-
return;
|
|
297
|
-
}
|
|
298
|
-
if (!worker.ready || !task?.sent || reply.kind === "ready" || reply.id !== task.request.id) {
|
|
299
|
-
this.retire(new OnnxWorkerError("runtime"));
|
|
300
|
-
return;
|
|
301
|
-
}
|
|
302
362
|
if (reply.kind === "error") {
|
|
303
363
|
this.finish(void 0, new OnnxWorkerError(reply.code));
|
|
304
364
|
return;
|
|
305
365
|
}
|
|
306
|
-
|
|
307
|
-
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);
|
|
308
|
-
else this.retire(new OnnxWorkerError("runtime"));
|
|
366
|
+
this.finish(reply);
|
|
309
367
|
}
|
|
310
368
|
finish(reply, failure) {
|
|
311
369
|
const task = this.active;
|
|
@@ -324,4 +382,4 @@ var InferenceWorkerClient = class {
|
|
|
324
382
|
worker.child.kill("SIGKILL");
|
|
325
383
|
}
|
|
326
384
|
};
|
|
327
|
-
export { createOnnxProvider as n, InferenceWorkerClient as t };
|
|
385
|
+
export { createOnnxProvider as n, createPreparedOnnxProvider as r, InferenceWorkerClient as t };
|
|
@@ -1 +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-
|
|
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-DgGGpngs.mjs","sha256":"f24046fd61b468a1eeca5745cb1d1492cd181ed8b29e392030b21f9e6ea92580","facadeSource":null,"sources":["extensions/onnx/src/artifacts.ts"]},{"output":".setup/catalog-g9or975s.mjs","sha256":"987b247b64a95183a5c6d128f2c81cfcc9b24cd504376bb02658f7fb2fa41522","facadeSource":null,"sources":["extensions/onnx/src/catalog.ts"]},{"output":".setup/cli-wozJmsLz.mjs","sha256":"614dcbb83f3c5e175bab1b4959537e4870f226745f379a7be05a03b7ea7d2402","facadeSource":"extensions/onnx/src/cli.ts","sources":["extensions/onnx/src/cli.ts"]},{"output":".setup/model-loader-DDsav9p5.mjs","sha256":"0293e51b336449ee19d792f3c2bee6837dae8d30fe2f12ad9c85d9f9cbece661","facadeSource":"extensions/onnx/src/model-loader.ts","sources":["extensions/onnx/src/model-loader.ts","extensions/onnx/src/models/tokenize.ts"]},{"output":".setup/protocol-CG1ILdRP.mjs","sha256":"bd0d6764cdfe342a66c946c7bace8ce50ec6ca4bc6bbf154f6b828b0fd892cbc","facadeSource":null,"sources":["extensions/onnx/src/models/types.ts","extensions/onnx/src/protocol.ts"]},{"output":".setup/worker-client-C6PMT6Zd.mjs","sha256":"7417b2f61134059ce710b1415635558f66809ec86d74f6bb96ba77c9d5933952","facadeSource":null,"sources":["extensions/onnx/src/decisions.ts","extensions/onnx/src/worker-client.ts"]},{"output":"index.js","sha256":"d2ea1fc4c93e1bde3f2ec3caa08632662d261f19a8dbe0b24796345dd36cec32","facadeSource":"extensions/onnx/index.ts","sources":["extensions/onnx/index.ts","extensions/onnx/src/config.ts"]},{"output":"src/inference.worker.js","sha256":"c098d4e340450e9e922ddd0c636d7dddb0e46df3e270ec77c1aa0ef043b936c1","facadeSource":"extensions/onnx/src/inference.worker.ts","sources":["extensions/onnx/src/inference.worker.ts"]}],"unrenderedSources":[]}
|