engine7 7.1.124 → 7.1.126

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.
@@ -0,0 +1,90 @@
1
+ const require=(await import('node:module')).createRequire(import.meta.url)
2
+
3
+ // src/router/cpu-router-worker.mjs
4
+ import { parentPort, workerData } from "node:worker_threads";
5
+ import fs from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { createHash } from "node:crypto";
8
+ import { Tokenizer } from "@huggingface/tokenizers";
9
+ import * as ort from "onnxruntime-node";
10
+
11
+ // src/router/cpu-router-data.mjs
12
+ function sanitizeText(text) {
13
+ return String(text).replace(/\b(sk|ghp|github_pat|xox[baprs])[-_][a-z0-9_-]{12,}/gi, "[SECRET]").replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, "$1[SECRET]@").replace(/((?:api[_-]?key|access[_-]?token|auth[_-]?token|password|passwd|secret|密码)\s*["']?\s*[:=]\s*["']?)[^\s,"'}]+/gi, "$1[SECRET]").replace(/\bBearer\s+[^\s"']+/gi, "Bearer [SECRET]").replace(/-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----/gs, "[SECRET]").replace(/[\p{L}\p{N}_.+-]+@[\p{L}\p{N}_.-]+\.[a-zA-Z]{2,}/gu, "[EMAIL]");
14
+ }
15
+ function encodeWindow(context, text, tokenizer2, maxLength = 384) {
16
+ if (!Number.isInteger(maxLength) || maxLength < 16 || maxLength > 384) throw new Error("Invalid token budget");
17
+ const encode = (value) => tokenizer2.encode(sanitizeText(value), { add_special_tokens: false }).ids;
18
+ let target = encode(text);
19
+ const history = context.slice(-3).map(encode);
20
+ const available = maxLength - 3;
21
+ const historySize = history.reduce((sum, value) => sum + value.length + 1, 0);
22
+ const contextBudget = history.length ? Math.min(historySize, Math.max(Math.floor(available / 3), available - target.length)) : 0;
23
+ const targetBudget = available - contextBudget;
24
+ if (target.length > targetBudget) {
25
+ const head = Math.floor((targetBudget + 1) / 2);
26
+ target = [...target.slice(0, head), ...target.slice(-(targetBudget - head))];
27
+ }
28
+ let retained = [];
29
+ const sep = tokenizer2.token_to_id("[SEP]");
30
+ const cls = tokenizer2.token_to_id("[CLS]");
31
+ if (sep === void 0 || cls === void 0) throw new Error("Missing BERT special tokens");
32
+ for (const message of history.reverse()) {
33
+ const remaining = contextBudget - retained.length;
34
+ if (remaining <= 1) break;
35
+ retained = [...message.slice(-(remaining - 1)), sep, ...retained];
36
+ }
37
+ const prefix = [cls, ...retained, sep];
38
+ const ids = [...prefix, ...target, sep];
39
+ return {
40
+ input_ids: ids,
41
+ attention_mask: ids.map(() => 1),
42
+ token_type_ids: [...prefix.map(() => 0), ...target.map(() => 1), 1]
43
+ };
44
+ }
45
+ function decodeRouterOutputs(outputs, trainedTasks) {
46
+ const result = { dev: null, mode: null };
47
+ for (const [task, labels] of [["dev", ["nodev", "dev"]], ["mode", ["emotion", "work"]]]) {
48
+ if (!trainedTasks.includes(task)) continue;
49
+ const logits = outputs[`${task}_logits`];
50
+ if (!logits || logits.length !== 2 || !Array.from(logits).every(Number.isFinite)) continue;
51
+ const best = logits[1] > logits[0] ? 1 : 0;
52
+ result[task] = { label: labels[best], confidence: 1 / (1 + Math.exp(logits[1 - best] - logits[best])) };
53
+ }
54
+ return result;
55
+ }
56
+
57
+ // src/router/cpu-router-worker.mjs
58
+ var { modelDir, threads } = workerData;
59
+ var readJson = async (name) => JSON.parse(await fs.readFile(path.join(modelDir, name), "utf8"));
60
+ var metadata = await readJson("runtime.json");
61
+ var files = ["router.fp32.onnx", "tokenizer.json", "tokenizer_config.json", "metadata.json"];
62
+ if (metadata.schemaVersion !== 1 || metadata.maxLength !== 384) throw new Error("Unsupported CPU router manifest");
63
+ for (const file of files) {
64
+ const data = await fs.readFile(path.join(modelDir, file));
65
+ if (createHash("sha256").update(data).digest("hex") !== metadata.sha256?.[file]) throw new Error("CPU router integrity check failed");
66
+ }
67
+ var trained = await readJson("metadata.json");
68
+ if (trained.schema_version !== 1 || !Array.isArray(trained.trained_tasks) || JSON.stringify(trained.task_labels?.dev) !== JSON.stringify(["nodev", "dev"]) || JSON.stringify(trained.task_labels?.mode) !== JSON.stringify(["emotion", "work"])) throw new Error("Unsupported CPU router labels");
69
+ var tokenizer = new Tokenizer(await readJson("tokenizer.json"), await readJson("tokenizer_config.json"));
70
+ var session = await ort.InferenceSession.create(path.join(modelDir, "router.fp32.onnx"), {
71
+ executionProviders: ["cpu"],
72
+ intraOpNumThreads: threads,
73
+ interOpNumThreads: 1,
74
+ executionMode: "sequential"
75
+ });
76
+ var chain = Promise.resolve();
77
+ parentPort.on("message", (message) => {
78
+ chain = chain.then(async () => {
79
+ const { id, context, text } = message;
80
+ try {
81
+ const encoded = encodeWindow(context, text, tokenizer, metadata.maxLength);
82
+ const feeds = Object.fromEntries(Object.entries(encoded).map(([name, values]) => [name, new ort.Tensor("int64", BigInt64Array.from(values, BigInt), [1, values.length])]));
83
+ const outputs = await session.run(feeds);
84
+ const result = decodeRouterOutputs(Object.fromEntries(Object.entries(outputs).map(([name, tensor]) => [name, tensor.data])), trained.trained_tasks);
85
+ parentPort.postMessage({ id, result });
86
+ } catch {
87
+ parentPort.postMessage({ id, result: null });
88
+ }
89
+ });
90
+ });