@openclaw/onnx 2026.9.6
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 +36 -0
- package/assets/activity.svg +40 -0
- package/assets/icon.png +0 -0
- package/dist/.setup/artifacts-Du35Uk5d.mjs +156 -0
- package/dist/.setup/catalog-Bgbx4LHv.mjs +173 -0
- package/dist/.setup/cli-Ch_OkcD5.mjs +95 -0
- package/dist/.setup/model-loader-CWJMvEgT.mjs +223 -0
- package/dist/.setup/protocol-lN8zQ8J3.mjs +115 -0
- package/dist/.setup/worker-client-BfBezMH8.mjs +332 -0
- package/dist/index.js +85 -0
- package/dist/scripts/export-gliclass-instruct.py +224 -0
- package/dist/src/inference.worker.js +63 -0
- package/openclaw.plugin.json +98 -0
- package/package.json +70 -0
|
@@ -0,0 +1,223 @@
|
|
|
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-Du35Uk5d.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 get(id) {
|
|
175
|
+
const existing = this.models.get(id);
|
|
176
|
+
if (existing) {
|
|
177
|
+
this.models.delete(id);
|
|
178
|
+
this.models.set(id, existing);
|
|
179
|
+
return existing.adapter;
|
|
180
|
+
}
|
|
181
|
+
const model = findModel(id);
|
|
182
|
+
if (!model) throw new UnsupportedInputError("Unknown ONNX model.");
|
|
183
|
+
const files = await resolveModelFiles(this.config.modelDir, model);
|
|
184
|
+
const buffers = /* @__PURE__ */ new Map();
|
|
185
|
+
for (const file of files) buffers.set(file.name, await readModelArtifact(this.config.modelDir, model, file));
|
|
186
|
+
const modelBytes = buffers.get("model.onnx");
|
|
187
|
+
const tokenizerBytes = buffers.get("tokenizer.json");
|
|
188
|
+
if (!modelBytes || !tokenizerBytes) throw new OnnxWorkerError("model-integrity");
|
|
189
|
+
const tokenizerConfig = buffers.get("tokenizer_config.json");
|
|
190
|
+
const tokenizer = new Tokenizer(jsonObject(tokenizerBytes), tokenizerConfig ? jsonObject(tokenizerConfig) : {});
|
|
191
|
+
if (this.models.size >= this.config.maxLoadedModels) {
|
|
192
|
+
const first = this.models.entries().next().value;
|
|
193
|
+
if (first) {
|
|
194
|
+
this.models.delete(first[0]);
|
|
195
|
+
await first[1].session.release();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const session = await InferenceSession.create(modelBytes, {
|
|
199
|
+
executionProviders: ["cpu"],
|
|
200
|
+
intraOpNumThreads: this.config.threads,
|
|
201
|
+
interOpNumThreads: 1,
|
|
202
|
+
logSeverityLevel: 3
|
|
203
|
+
});
|
|
204
|
+
try {
|
|
205
|
+
const context = {
|
|
206
|
+
session,
|
|
207
|
+
tokenizer,
|
|
208
|
+
maxTokens: model.maxTokens
|
|
209
|
+
};
|
|
210
|
+
const adapter = model.family === "gliclass" ? createGliclassAdapter(context) : model.family === "gliner" ? createGlinerAdapter(context) : createDebertaAdapter(context);
|
|
211
|
+
this.models.set(id, {
|
|
212
|
+
session,
|
|
213
|
+
adapter
|
|
214
|
+
});
|
|
215
|
+
return adapter;
|
|
216
|
+
} catch (error) {
|
|
217
|
+
await session.release();
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
//#endregion
|
|
223
|
+
export { ModelCache };
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { Value } from "typebox/value";
|
|
3
|
+
//#region extensions/onnx/src/models/types.ts
|
|
4
|
+
var UnsupportedInputError = class extends Error {};
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region extensions/onnx/src/protocol.ts
|
|
7
|
+
const ModelInputSchema = Type.Object({
|
|
8
|
+
text: Type.String({ maxLength: 262144 }),
|
|
9
|
+
labels: Type.Array(Type.String({
|
|
10
|
+
minLength: 1,
|
|
11
|
+
maxLength: 16384
|
|
12
|
+
}), {
|
|
13
|
+
minItems: 2,
|
|
14
|
+
maxItems: 64
|
|
15
|
+
}),
|
|
16
|
+
task: Type.String({
|
|
17
|
+
minLength: 1,
|
|
18
|
+
maxLength: 1024
|
|
19
|
+
}),
|
|
20
|
+
instructions: Type.Optional(Type.String({ maxLength: 16384 })),
|
|
21
|
+
descriptions: Type.Optional(Type.Record(Type.String(), Type.String({ maxLength: 16384 })))
|
|
22
|
+
}, { additionalProperties: false });
|
|
23
|
+
const ConfigSchema = Type.Object({
|
|
24
|
+
modelDir: Type.String({
|
|
25
|
+
minLength: 1,
|
|
26
|
+
maxLength: 4096
|
|
27
|
+
}),
|
|
28
|
+
threads: Type.Integer({
|
|
29
|
+
minimum: 1,
|
|
30
|
+
maximum: 8
|
|
31
|
+
}),
|
|
32
|
+
maxLoadedModels: Type.Integer({
|
|
33
|
+
minimum: 1,
|
|
34
|
+
maximum: 5
|
|
35
|
+
})
|
|
36
|
+
}, { additionalProperties: false });
|
|
37
|
+
const RequestSchema = Type.Union([
|
|
38
|
+
Type.Object({
|
|
39
|
+
kind: Type.Literal("init"),
|
|
40
|
+
config: ConfigSchema
|
|
41
|
+
}, { additionalProperties: false }),
|
|
42
|
+
Type.Object({
|
|
43
|
+
kind: Type.Literal("classify"),
|
|
44
|
+
id: Type.Integer({ minimum: 1 }),
|
|
45
|
+
model: Type.String({
|
|
46
|
+
minLength: 1,
|
|
47
|
+
maxLength: 128
|
|
48
|
+
}),
|
|
49
|
+
inputs: Type.Array(ModelInputSchema, {
|
|
50
|
+
minItems: 1,
|
|
51
|
+
maxItems: 32
|
|
52
|
+
})
|
|
53
|
+
}, { additionalProperties: false }),
|
|
54
|
+
Type.Object({
|
|
55
|
+
kind: Type.Literal("warm"),
|
|
56
|
+
id: Type.Integer({ minimum: 1 }),
|
|
57
|
+
models: Type.Array(Type.String({
|
|
58
|
+
minLength: 1,
|
|
59
|
+
maxLength: 128
|
|
60
|
+
}), { maxItems: 5 })
|
|
61
|
+
}, { additionalProperties: false })
|
|
62
|
+
]);
|
|
63
|
+
const ErrorCodeSchema = Type.Union([
|
|
64
|
+
Type.Literal("unsupported-input"),
|
|
65
|
+
Type.Literal("model-missing"),
|
|
66
|
+
Type.Literal("model-integrity"),
|
|
67
|
+
Type.Literal("dependency-unavailable"),
|
|
68
|
+
Type.Literal("runtime")
|
|
69
|
+
]);
|
|
70
|
+
const ReplySchema = Type.Union([
|
|
71
|
+
Type.Object({ kind: Type.Literal("ready") }, { additionalProperties: false }),
|
|
72
|
+
Type.Object({
|
|
73
|
+
kind: Type.Literal("results"),
|
|
74
|
+
id: Type.Integer({ minimum: 1 }),
|
|
75
|
+
results: Type.Array(Type.Object({
|
|
76
|
+
logits: Type.Array(Type.Number(), {
|
|
77
|
+
minItems: 2,
|
|
78
|
+
maxItems: 64
|
|
79
|
+
}),
|
|
80
|
+
inputTokens: Type.Integer({ minimum: 1 })
|
|
81
|
+
}, { additionalProperties: false }), { maxItems: 32 })
|
|
82
|
+
}, { additionalProperties: false }),
|
|
83
|
+
Type.Object({
|
|
84
|
+
kind: Type.Literal("warmed"),
|
|
85
|
+
id: Type.Integer({ minimum: 1 })
|
|
86
|
+
}, { additionalProperties: false }),
|
|
87
|
+
Type.Object({
|
|
88
|
+
kind: Type.Literal("error"),
|
|
89
|
+
id: Type.Integer({ minimum: 1 }),
|
|
90
|
+
code: ErrorCodeSchema
|
|
91
|
+
}, { additionalProperties: false })
|
|
92
|
+
]);
|
|
93
|
+
function parseWorkerRequest(value) {
|
|
94
|
+
if (!Value.Check(RequestSchema, value)) throw new Error("Invalid ONNX worker request");
|
|
95
|
+
if (value.kind === "classify") {
|
|
96
|
+
let bytes = 0;
|
|
97
|
+
for (const input of value.inputs) {
|
|
98
|
+
bytes += Buffer.byteLength(JSON.stringify(input));
|
|
99
|
+
if (bytes > 1048576) throw new Error("ONNX inputs exceed one MiB");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
function parseWorkerReply(value) {
|
|
105
|
+
if (!Value.Check(ReplySchema, value)) throw new Error("Invalid ONNX worker reply");
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
var OnnxWorkerError = class extends Error {
|
|
109
|
+
constructor(code) {
|
|
110
|
+
super(`ONNX worker: ${code}`);
|
|
111
|
+
this.code = code;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
//#endregion
|
|
115
|
+
export { UnsupportedInputError as i, parseWorkerReply as n, parseWorkerRequest as r, OnnxWorkerError as t };
|
|
@@ -0,0 +1,332 @@
|
|
|
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 { spawn } from "node:child_process";
|
|
4
|
+
import { resolveRuntimeWorkerArgv } from "openclaw/plugin-sdk/process-runtime";
|
|
5
|
+
//#region extensions/onnx/src/decisions.ts
|
|
6
|
+
function render(value) {
|
|
7
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
8
|
+
}
|
|
9
|
+
function rubric(question) {
|
|
10
|
+
if (question.type === "choice") {
|
|
11
|
+
const labels = Object.keys(question.criteria);
|
|
12
|
+
return {
|
|
13
|
+
labels,
|
|
14
|
+
descriptions: Object.fromEntries(labels.map((label) => {
|
|
15
|
+
const value = question.criteria[label];
|
|
16
|
+
return [label, value === null || value === void 0 ? label : render(value)];
|
|
17
|
+
}))
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
if (question.type === "score") return {
|
|
21
|
+
labels: question.criteria.map((_, index) => String(index)),
|
|
22
|
+
descriptions: Object.fromEntries(question.criteria.flatMap((value, index) => value === null ? [] : [[String(index), render(value)]]))
|
|
23
|
+
};
|
|
24
|
+
if (question.criteria?.true == null || question.criteria.false == null) throw new UnsupportedInputError("ONNX Boolean questions require true and false criterion descriptions.");
|
|
25
|
+
return {
|
|
26
|
+
labels: ["true", "false"],
|
|
27
|
+
descriptions: {
|
|
28
|
+
true: render(question.criteria.true),
|
|
29
|
+
false: render(question.criteria.false)
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function probabilities(logits) {
|
|
34
|
+
if (logits.length < 2 || logits.some((value) => !Number.isFinite(value))) throw new Error("ONNX returned invalid label logits.");
|
|
35
|
+
const max = Math.max(...logits);
|
|
36
|
+
const weights = logits.map((value) => Math.exp(value - max));
|
|
37
|
+
const sum = weights.reduce((total, value) => total + value, 0);
|
|
38
|
+
return weights.map((value) => value / sum);
|
|
39
|
+
}
|
|
40
|
+
function createOnnxProvider(client, warn) {
|
|
41
|
+
return {
|
|
42
|
+
id: "onnx",
|
|
43
|
+
contractVersion: 1,
|
|
44
|
+
async evaluate(batch, context) {
|
|
45
|
+
context.signal.throwIfAborted();
|
|
46
|
+
if (!findModel(context.model)) return {
|
|
47
|
+
status: "unavailable",
|
|
48
|
+
reason: "unsupported-input"
|
|
49
|
+
};
|
|
50
|
+
try {
|
|
51
|
+
const entries = Object.entries(batch.questions);
|
|
52
|
+
if (entries.length === 0 || entries.length > 32) throw new UnsupportedInputError("Unsupported batch size.");
|
|
53
|
+
const text = render(batch.state);
|
|
54
|
+
const inputs = entries.map(([, question]) => {
|
|
55
|
+
const selected = rubric(question);
|
|
56
|
+
if (selected.labels.length < 2 || selected.labels.length > 64) throw new UnsupportedInputError("Unsupported label count.");
|
|
57
|
+
return {
|
|
58
|
+
text,
|
|
59
|
+
task: "decision",
|
|
60
|
+
...selected,
|
|
61
|
+
...question.instructions == null ? {} : { instructions: render(question.instructions) }
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
const results = await client.classify(context.model, inputs, context.signal);
|
|
65
|
+
context.signal.throwIfAborted();
|
|
66
|
+
if (results.length !== entries.length) throw new Error("ONNX returned an incomplete batch.");
|
|
67
|
+
const answers = /* @__PURE__ */ new Map();
|
|
68
|
+
let inputTokens = 0;
|
|
69
|
+
entries.forEach(([id, question], index) => {
|
|
70
|
+
const result = results[index];
|
|
71
|
+
const labels = inputs[index].labels;
|
|
72
|
+
if (result.logits.length !== labels.length) throw new Error("ONNX returned an incomplete distribution.");
|
|
73
|
+
const values = probabilities(result.logits);
|
|
74
|
+
inputTokens += result.inputTokens;
|
|
75
|
+
if (question.type === "boolean") answers.set(id, {
|
|
76
|
+
type: "boolean",
|
|
77
|
+
probabilityTrue: values[0]
|
|
78
|
+
});
|
|
79
|
+
else if (question.type === "score") {
|
|
80
|
+
const score = Math.min(values.length - 1, values.reduce((sum, value, position) => sum + value * position, 0));
|
|
81
|
+
answers.set(id, {
|
|
82
|
+
type: "score",
|
|
83
|
+
score,
|
|
84
|
+
probabilities: values
|
|
85
|
+
});
|
|
86
|
+
} else {
|
|
87
|
+
const best = values.indexOf(Math.max(...values));
|
|
88
|
+
answers.set(id, {
|
|
89
|
+
type: "choice",
|
|
90
|
+
choice: labels[best],
|
|
91
|
+
probabilities: Object.fromEntries(labels.map((label, position) => [label, values[position]]))
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
return {
|
|
96
|
+
status: "ok",
|
|
97
|
+
result: {
|
|
98
|
+
model: context.model,
|
|
99
|
+
answers: Object.fromEntries(answers),
|
|
100
|
+
usage: { inputTokens }
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
} catch (error) {
|
|
104
|
+
context.signal.throwIfAborted();
|
|
105
|
+
if (error instanceof UnsupportedInputError || error instanceof OnnxWorkerError && error.code === "unsupported-input") return {
|
|
106
|
+
status: "unavailable",
|
|
107
|
+
reason: "unsupported-input"
|
|
108
|
+
};
|
|
109
|
+
if (error instanceof OnnxWorkerError) {
|
|
110
|
+
if (error.code === "model-missing" || error.code === "model-integrity") warn(`ONNX model ${context.model} is missing or invalid. Run openclaw onnx verify ${context.model}; use download or prepare a local export as listed by openclaw onnx models.`);
|
|
111
|
+
else if (error.code === "dependency-unavailable") warn("ONNX Runtime is unavailable. Install the optional ONNX plugin dependencies for this platform.");
|
|
112
|
+
return {
|
|
113
|
+
status: "unavailable",
|
|
114
|
+
reason: "transport"
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
status: "unavailable",
|
|
119
|
+
reason: "invalid-response"
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region extensions/onnx/src/worker-client.ts
|
|
127
|
+
function workerEnv() {
|
|
128
|
+
const env = {};
|
|
129
|
+
for (const key of [
|
|
130
|
+
"SystemRoot",
|
|
131
|
+
"SYSTEMROOT",
|
|
132
|
+
"WINDIR",
|
|
133
|
+
"TEMP",
|
|
134
|
+
"TMP",
|
|
135
|
+
"TMPDIR"
|
|
136
|
+
]) if (process.env[key]) env[key] = process.env[key];
|
|
137
|
+
return env;
|
|
138
|
+
}
|
|
139
|
+
/** One warm, OS-killable inference process; native work retains its slot until close. */
|
|
140
|
+
var InferenceWorkerClient = class {
|
|
141
|
+
constructor(options) {
|
|
142
|
+
this.queue = [];
|
|
143
|
+
this.nextId = 0;
|
|
144
|
+
this.closed = false;
|
|
145
|
+
this.workerUrl = new URL(options.workerUrl.href);
|
|
146
|
+
this.config = { ...options.config };
|
|
147
|
+
}
|
|
148
|
+
async classify(model, inputs, signal) {
|
|
149
|
+
const reply = await this.enqueue({
|
|
150
|
+
kind: "classify",
|
|
151
|
+
id: ++this.nextId,
|
|
152
|
+
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;
|
|
160
|
+
}
|
|
161
|
+
async warm(models, signal) {
|
|
162
|
+
await this.enqueue({
|
|
163
|
+
kind: "warm",
|
|
164
|
+
id: ++this.nextId,
|
|
165
|
+
models: [...models]
|
|
166
|
+
}, signal);
|
|
167
|
+
}
|
|
168
|
+
stop() {
|
|
169
|
+
if (this.stopping) return this.stopping;
|
|
170
|
+
this.closed = true;
|
|
171
|
+
for (const task of this.queue.splice(0)) {
|
|
172
|
+
task.signal.removeEventListener("abort", task.abort);
|
|
173
|
+
task.reject(new OnnxWorkerError("runtime"));
|
|
174
|
+
}
|
|
175
|
+
const worker = this.worker;
|
|
176
|
+
this.retire(new OnnxWorkerError("runtime"));
|
|
177
|
+
this.stopping = worker?.closed ?? Promise.resolve();
|
|
178
|
+
return this.stopping;
|
|
179
|
+
}
|
|
180
|
+
enqueue(request, signal) {
|
|
181
|
+
signal.throwIfAborted();
|
|
182
|
+
try {
|
|
183
|
+
parseWorkerRequest(request);
|
|
184
|
+
} catch {
|
|
185
|
+
return Promise.reject(new OnnxWorkerError("unsupported-input"));
|
|
186
|
+
}
|
|
187
|
+
if (this.closed || this.queue.length + (this.active ? 1 : 0) >= 4) return Promise.reject(new OnnxWorkerError("runtime"));
|
|
188
|
+
return new Promise((resolve, reject) => {
|
|
189
|
+
const task = {
|
|
190
|
+
request,
|
|
191
|
+
signal,
|
|
192
|
+
sent: false,
|
|
193
|
+
resolve,
|
|
194
|
+
reject,
|
|
195
|
+
abort: () => this.cancel(task)
|
|
196
|
+
};
|
|
197
|
+
this.queue.push(task);
|
|
198
|
+
signal.addEventListener("abort", task.abort, { once: true });
|
|
199
|
+
if (signal.aborted) this.cancel(task);
|
|
200
|
+
else this.dispatch();
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
cancel(task) {
|
|
204
|
+
if (this.active === task) {
|
|
205
|
+
this.retire(task.signal.reason);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const index = this.queue.indexOf(task);
|
|
209
|
+
if (index !== -1) {
|
|
210
|
+
this.queue.splice(index, 1);
|
|
211
|
+
task.signal.removeEventListener("abort", task.abort);
|
|
212
|
+
task.reject(task.signal.reason);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
dispatch() {
|
|
216
|
+
if (this.closed || this.active || this.worker?.retiring) return;
|
|
217
|
+
const task = this.queue.shift();
|
|
218
|
+
if (!task) return;
|
|
219
|
+
this.active = task;
|
|
220
|
+
if (!this.worker) {
|
|
221
|
+
try {
|
|
222
|
+
this.start();
|
|
223
|
+
} catch {
|
|
224
|
+
this.finish(void 0, new OnnxWorkerError("runtime"));
|
|
225
|
+
}
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (this.worker.ready) {
|
|
229
|
+
this.send(this.worker, task.request);
|
|
230
|
+
task.sent = true;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
start() {
|
|
234
|
+
const child = spawn(process.execPath, resolveRuntimeWorkerArgv(this.workerUrl), {
|
|
235
|
+
env: workerEnv(),
|
|
236
|
+
shell: false,
|
|
237
|
+
windowsHide: true,
|
|
238
|
+
stdio: [
|
|
239
|
+
"ignore",
|
|
240
|
+
"ignore",
|
|
241
|
+
"ignore",
|
|
242
|
+
"ipc"
|
|
243
|
+
]
|
|
244
|
+
});
|
|
245
|
+
let resolveClosed;
|
|
246
|
+
const worker = {
|
|
247
|
+
child,
|
|
248
|
+
ready: false,
|
|
249
|
+
retiring: false,
|
|
250
|
+
closed: new Promise((resolve) => {
|
|
251
|
+
resolveClosed = resolve;
|
|
252
|
+
}),
|
|
253
|
+
resolveClosed: () => resolveClosed()
|
|
254
|
+
};
|
|
255
|
+
this.worker = worker;
|
|
256
|
+
child.on("message", (message) => this.receive(worker, message));
|
|
257
|
+
child.on("error", () => {
|
|
258
|
+
if (this.worker === worker) this.retire(new OnnxWorkerError("runtime"));
|
|
259
|
+
});
|
|
260
|
+
child.once("disconnect", () => {
|
|
261
|
+
if (this.worker === worker) this.retire(new OnnxWorkerError("runtime"));
|
|
262
|
+
});
|
|
263
|
+
child.once("close", () => {
|
|
264
|
+
if (this.worker === worker) {
|
|
265
|
+
this.worker = void 0;
|
|
266
|
+
const task = this.active;
|
|
267
|
+
if (task) this.finish(void 0, task.signal.aborted ? task.signal.reason : worker.failure ?? new OnnxWorkerError("runtime"));
|
|
268
|
+
else this.dispatch();
|
|
269
|
+
}
|
|
270
|
+
worker.resolveClosed();
|
|
271
|
+
});
|
|
272
|
+
this.send(worker, {
|
|
273
|
+
kind: "init",
|
|
274
|
+
config: this.config
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
send(worker, request) {
|
|
278
|
+
try {
|
|
279
|
+
worker.child.send(request, (error) => {
|
|
280
|
+
if (error && this.worker === worker) this.retire(new OnnxWorkerError("runtime"));
|
|
281
|
+
});
|
|
282
|
+
} catch {
|
|
283
|
+
if (this.worker === worker) this.retire(new OnnxWorkerError("runtime"));
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
receive(worker, message) {
|
|
287
|
+
if (this.worker !== worker || worker.retiring) return;
|
|
288
|
+
let reply;
|
|
289
|
+
try {
|
|
290
|
+
reply = parseWorkerReply(message);
|
|
291
|
+
} catch {
|
|
292
|
+
this.retire(new OnnxWorkerError("runtime"));
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const task = this.active;
|
|
296
|
+
if (reply.kind === "ready" && !worker.ready && task) {
|
|
297
|
+
worker.ready = true;
|
|
298
|
+
task.sent = true;
|
|
299
|
+
this.send(worker, task.request);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (!worker.ready || !task?.sent || reply.kind === "ready" || reply.id !== task.request.id) {
|
|
303
|
+
this.retire(new OnnxWorkerError("runtime"));
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (reply.kind === "error") {
|
|
307
|
+
this.finish(void 0, new OnnxWorkerError(reply.code));
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
const request = task.request;
|
|
311
|
+
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);
|
|
312
|
+
else this.retire(new OnnxWorkerError("runtime"));
|
|
313
|
+
}
|
|
314
|
+
finish(reply, failure) {
|
|
315
|
+
const task = this.active;
|
|
316
|
+
if (!task) return;
|
|
317
|
+
this.active = void 0;
|
|
318
|
+
task.signal.removeEventListener("abort", task.abort);
|
|
319
|
+
if (reply) task.resolve(reply);
|
|
320
|
+
else task.reject(failure);
|
|
321
|
+
this.dispatch();
|
|
322
|
+
}
|
|
323
|
+
retire(failure) {
|
|
324
|
+
const worker = this.worker;
|
|
325
|
+
if (!worker || worker.retiring) return;
|
|
326
|
+
worker.retiring = true;
|
|
327
|
+
worker.failure = failure;
|
|
328
|
+
worker.child.kill("SIGKILL");
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
//#endregion
|
|
332
|
+
export { createOnnxProvider as n, InferenceWorkerClient as t };
|