@try-works/extension-laya 0.0.0-stage → 1.0.0
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 +38 -2
- package/lib/index.d.ts +18 -0
- package/lib/index.js +172 -0
- package/lib/index.js.map +1 -0
- package/lib/pure.d.ts +35 -0
- package/lib/pure.js +71 -0
- package/lib/pure.js.map +1 -0
- package/models.lock.json +63 -0
- package/package.json +39 -4
- package/schema/decision-choose.input.json +22 -0
- package/schema/decision-choose.output.json +20 -0
- package/schema/decision-score.input.json +18 -0
- package/schema/decision-score.output.json +18 -0
- package/schema/decision-test.input.json +10 -0
- package/schema/decision-test.output.json +18 -0
- package/tool-mode.extension.json +87 -0
- package/vendor/LICENSE.laya-ts +176 -0
- package/vendor/laya-ts/agent.d.ts +216 -0
- package/vendor/laya-ts/agent.js +631 -0
- package/vendor/laya-ts/common.d.ts +167 -0
- package/vendor/laya-ts/common.js +478 -0
- package/vendor/laya-ts/dx.d.ts +17 -0
- package/vendor/laya-ts/dx.js +46 -0
- package/vendor/laya-ts/email.d.ts +2 -0
- package/vendor/laya-ts/email.js +184 -0
- package/vendor/laya-ts/hooks.d.ts +134 -0
- package/vendor/laya-ts/hooks.js +379 -0
- package/vendor/laya-ts/index.d.ts +22 -0
- package/vendor/laya-ts/index.js +13 -0
- package/vendor/laya-ts/lang.d.ts +24 -0
- package/vendor/laya-ts/lang.js +590 -0
- package/vendor/laya-ts/presets.d.ts +5 -0
- package/vendor/laya-ts/presets.js +175 -0
- package/vendor/laya-ts/providers.d.ts +67 -0
- package/vendor/laya-ts/providers.js +668 -0
- package/vendor/laya-ts/router.d.ts +186 -0
- package/vendor/laya-ts/router.js +757 -0
- package/vendor/laya-ts/shortlist.d.ts +65 -0
- package/vendor/laya-ts/shortlist.js +407 -0
- package/vendor/laya-ts/structured.d.ts +89 -0
- package/vendor/laya-ts/structured.js +256 -0
- package/vendor/laya-ts/tokenizer.d.ts +66 -0
- package/vendor/laya-ts/tokenizer.js +482 -0
|
@@ -0,0 +1,668 @@
|
|
|
1
|
+
/** ONNX session shim: Node (onnxruntime-node) + browser (onnxruntime-web).
|
|
2
|
+
* Lazy imports only — unit tests with a fake provider never touch onnxruntime. */
|
|
3
|
+
/** Opt-in reviewed commit SHAs of the published checkpoints (mirror of laya/revisions.py).
|
|
4
|
+
* They are not applied implicitly, so existing Hub/offline caches keep working. */
|
|
5
|
+
export const PINNED_REVISIONS = {
|
|
6
|
+
"convaiinnovations/laya": "55cf4c4ebb4ebe31b2550e8bdf3bd21b99753851",
|
|
7
|
+
"convaiinnovations/laya-multilingual": "e4e9ddf21a7b1903b7acffd8814ad4307bf63a67",
|
|
8
|
+
"convaiinnovations/laya-typed-decisions": "1a793eb568e6718f15941d08f85432581df534e3",
|
|
9
|
+
};
|
|
10
|
+
/** Return an explicit revision unchanged; otherwise preserve the Hub default and cache. */
|
|
11
|
+
export function resolveRevision(_repoOrId, revision) {
|
|
12
|
+
return revision || null;
|
|
13
|
+
}
|
|
14
|
+
/** SHA-256 hex via Web Crypto (browsers and modern Node expose globalThis.crypto). */
|
|
15
|
+
async function sha256Hex(data) {
|
|
16
|
+
const subtle = globalThis.crypto?.subtle;
|
|
17
|
+
if (!subtle) {
|
|
18
|
+
throw new Error("laya-ts: SHA-256 verification requires Web Crypto (globalThis.crypto.subtle)");
|
|
19
|
+
}
|
|
20
|
+
const digest = await subtle.digest("SHA-256", data);
|
|
21
|
+
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
22
|
+
}
|
|
23
|
+
/** Reject absolute or escaping digest paths before they ever reach the filesystem. */
|
|
24
|
+
function normaliseDigestPath(rel) {
|
|
25
|
+
const raw = String(rel).replace(/\\/g, "/");
|
|
26
|
+
if (/^(?:[A-Za-z]:|\/)/.test(raw)) {
|
|
27
|
+
throw new Error(`laya-ts: unsafe absolute path in expectedSha256: ${JSON.stringify(rel)}`);
|
|
28
|
+
}
|
|
29
|
+
const norm = raw;
|
|
30
|
+
if (!norm || norm === ".." || norm.startsWith("../") || norm.includes("/../")) {
|
|
31
|
+
throw new Error(`laya-ts: unsafe path in expectedSha256: ${JSON.stringify(rel)}`);
|
|
32
|
+
}
|
|
33
|
+
return norm;
|
|
34
|
+
}
|
|
35
|
+
/** Verify `data` against expectedSha256[rel]; artifacts not listed are left unchecked. */
|
|
36
|
+
async function expectDigest(rel, data, expected) {
|
|
37
|
+
const want = expected[rel] ?? expected[normaliseDigestPath(rel)];
|
|
38
|
+
if (want === undefined)
|
|
39
|
+
return;
|
|
40
|
+
const got = await sha256Hex(data);
|
|
41
|
+
if (got.toLowerCase() !== String(want).trim().toLowerCase()) {
|
|
42
|
+
throw new Error(`laya-ts: SHA-256 mismatch for ${rel}: expected ${want}, got ${got}. Refusing to load the artifact.`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function toNested(data, dims) {
|
|
46
|
+
// Single-pass copy + precomputed steps; no per-node slice/reduce.
|
|
47
|
+
let total = 1;
|
|
48
|
+
for (const d of dims)
|
|
49
|
+
total *= d;
|
|
50
|
+
const flat = new Array(total);
|
|
51
|
+
for (let i = 0; i < total; i++) {
|
|
52
|
+
const v = data[i];
|
|
53
|
+
flat[i] = typeof v === "bigint" ? Number(v) : v;
|
|
54
|
+
}
|
|
55
|
+
if (dims.length === 0)
|
|
56
|
+
return flat[0];
|
|
57
|
+
const steps = new Array(dims.length);
|
|
58
|
+
for (let d = 0; d < dims.length; d++) {
|
|
59
|
+
let s = 1;
|
|
60
|
+
for (let k = d + 1; k < dims.length; k++)
|
|
61
|
+
s *= dims[k];
|
|
62
|
+
steps[d] = s;
|
|
63
|
+
}
|
|
64
|
+
const rec = (d, off) => {
|
|
65
|
+
if (d === dims.length - 1)
|
|
66
|
+
return flat.slice(off, off + dims[d]);
|
|
67
|
+
const out = new Array(dims[d]);
|
|
68
|
+
for (let i = 0; i < dims[d]; i++)
|
|
69
|
+
out[i] = rec(d + 1, off + i * steps[d]);
|
|
70
|
+
return out;
|
|
71
|
+
};
|
|
72
|
+
return rec(0, 0);
|
|
73
|
+
}
|
|
74
|
+
function i64(ort, arr, dims) {
|
|
75
|
+
// Rank <= 2 by construction; direct loop avoids flat(Infinity) intermediates.
|
|
76
|
+
const out = new BigInt64Array(dims.reduce((a, b) => a * b, 1));
|
|
77
|
+
let p = 0;
|
|
78
|
+
if (Array.isArray(arr[0])) {
|
|
79
|
+
for (const row of arr)
|
|
80
|
+
for (const v of row)
|
|
81
|
+
out[p++] = BigInt(Math.trunc(v));
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
for (const v of arr)
|
|
85
|
+
out[p++] = BigInt(Math.trunc(v));
|
|
86
|
+
}
|
|
87
|
+
return new ort.Tensor("int64", out, dims);
|
|
88
|
+
}
|
|
89
|
+
/** Encoder feeds: input_ids + attention_mask (int64). */
|
|
90
|
+
export function feed(ort, b) {
|
|
91
|
+
const n = b.inputIds.length;
|
|
92
|
+
let L = 1;
|
|
93
|
+
for (const r of b.inputIds)
|
|
94
|
+
if (r.length > L)
|
|
95
|
+
L = r.length;
|
|
96
|
+
return {
|
|
97
|
+
input_ids: i64(ort, b.inputIds, [n, L]),
|
|
98
|
+
attention_mask: i64(ort, b.attentionMask, [n, L]),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** Head feeds: encoder hidden + marker_pos/mask + qtype. */
|
|
102
|
+
export function feedHead(ort, hidden, b) {
|
|
103
|
+
const n = b.markerPos.length;
|
|
104
|
+
let k = 1;
|
|
105
|
+
for (const r of b.markerPos)
|
|
106
|
+
if (r.length > k)
|
|
107
|
+
k = r.length;
|
|
108
|
+
// Direct flatten into typed arrays; no flat(Infinity)+map intermediates.
|
|
109
|
+
const nH = hidden.length ?? n;
|
|
110
|
+
const S = hidden[0]?.length ?? 1;
|
|
111
|
+
const Hd = hidden[0]?.[0]?.length ?? 1;
|
|
112
|
+
const flatH = new Float32Array(nH * S * Hd);
|
|
113
|
+
let p = 0;
|
|
114
|
+
for (let i = 0; i < nH; i++) {
|
|
115
|
+
const bi = hidden[i] ?? [];
|
|
116
|
+
for (let j = 0; j < S; j++) {
|
|
117
|
+
const hj = bi[j] ?? [];
|
|
118
|
+
for (let h = 0; h < Hd; h++)
|
|
119
|
+
flatH[p++] = Number(hj[h] ?? 0);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const H = new ort.Tensor("float32", flatH, [nH, S, Hd]);
|
|
123
|
+
// Pad/trim mask rows to S so the mask always matches hidden_states even
|
|
124
|
+
// if a caller passes unpadded rows.
|
|
125
|
+
const maskRows = b.attentionMask.map((r) => {
|
|
126
|
+
const row = r.slice(0, S);
|
|
127
|
+
while (row.length < S)
|
|
128
|
+
row.push(0);
|
|
129
|
+
return row;
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
hidden_states: H,
|
|
133
|
+
marker_pos: i64(ort, b.markerPos, [n, k]),
|
|
134
|
+
marker_mask: new ort.Tensor("bool", (() => {
|
|
135
|
+
const out = new Uint8Array(n * k);
|
|
136
|
+
let q = 0;
|
|
137
|
+
for (const row of b.markerMask)
|
|
138
|
+
for (let j = 0; j < k; j++)
|
|
139
|
+
out[q++] = row[j] ? 1 : 0;
|
|
140
|
+
return out;
|
|
141
|
+
})(), [n, k]),
|
|
142
|
+
qtype: i64(ort, b.qtype.map((v) => [v]), [n, 1]),
|
|
143
|
+
// Padding mask for the head transformer (py DecisionModel.forward).
|
|
144
|
+
// Without it, batch mates of unequal length corrupt each other's markers.
|
|
145
|
+
attention_mask: i64(ort, maskRows, [n, S]),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function pickOutput(out, names) {
|
|
149
|
+
for (const n of names)
|
|
150
|
+
if (out[n] !== undefined)
|
|
151
|
+
return out[n];
|
|
152
|
+
const vals = Object.values(out);
|
|
153
|
+
return vals[0];
|
|
154
|
+
}
|
|
155
|
+
function applyNumThreads(ort, numThreads) {
|
|
156
|
+
try {
|
|
157
|
+
const raw = numThreads ??
|
|
158
|
+
(typeof process !== "undefined" ? Number(process.env?.["LAYA_THREADS"]) : NaN);
|
|
159
|
+
if (Number.isFinite(raw) && raw > 0 && ort?.env) {
|
|
160
|
+
ort.env.numThreads = Math.trunc(raw);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
/* best-effort only */
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function isOomError(e) {
|
|
168
|
+
const m = String(e?.message ?? e).toLowerCase();
|
|
169
|
+
return m.includes("memory") || m.includes("cuda") || m.includes("out of memory") || m.includes("oom");
|
|
170
|
+
}
|
|
171
|
+
const CACHE_KEY = "laya-ts";
|
|
172
|
+
const TOKENIZER_CANDIDATES = ["tokenizer.json", "tokenizer/tokenizer.json"];
|
|
173
|
+
function sleep(ms) {
|
|
174
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
175
|
+
}
|
|
176
|
+
/** fetch with 2 retries on network errors + 429/5xx; 404s fail fast. */
|
|
177
|
+
async function fetchWithRetry(url, init, retries = 2) {
|
|
178
|
+
let last = null;
|
|
179
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
180
|
+
if (init?.signal?.aborted)
|
|
181
|
+
throw new DOMException("aborted", "AbortError");
|
|
182
|
+
try {
|
|
183
|
+
const res = await fetch(url, init);
|
|
184
|
+
if (res.ok)
|
|
185
|
+
return res;
|
|
186
|
+
if ((res.status === 429 || res.status >= 500) && attempt < retries) {
|
|
187
|
+
await sleep(100 * (attempt + 1));
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
return res;
|
|
191
|
+
}
|
|
192
|
+
catch (e) {
|
|
193
|
+
last = e;
|
|
194
|
+
if (e?.name === "AbortError")
|
|
195
|
+
throw e;
|
|
196
|
+
if (attempt < retries) {
|
|
197
|
+
await sleep(100 * (attempt + 1));
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
throw e;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
throw last instanceof Error ? last : new Error(`fetch failed for ${url}`);
|
|
204
|
+
}
|
|
205
|
+
/** Online-first fetch: try network, cache on success, fall back to CacheStorage. */
|
|
206
|
+
async function fetchArrayBuffer(url, opts) {
|
|
207
|
+
const g = globalThis;
|
|
208
|
+
let cache = null;
|
|
209
|
+
let hit = null;
|
|
210
|
+
try {
|
|
211
|
+
if (g.caches && typeof g.caches.open === "function") {
|
|
212
|
+
try {
|
|
213
|
+
cache = await g.caches.open(CACHE_KEY);
|
|
214
|
+
try {
|
|
215
|
+
hit = await cache.match(url);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
hit = null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
cache = null;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
cache = null;
|
|
228
|
+
}
|
|
229
|
+
if (cache) {
|
|
230
|
+
try {
|
|
231
|
+
const res = await fetchWithRetry(url, { signal: opts?.signal ?? undefined });
|
|
232
|
+
opts?.onHeaders?.(res);
|
|
233
|
+
if (res.ok) {
|
|
234
|
+
try {
|
|
235
|
+
await cache.put(url, res.clone());
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
/* cache full/blocked: still return network bytes */
|
|
239
|
+
}
|
|
240
|
+
return await res.arrayBuffer();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
catch (e) {
|
|
244
|
+
if (hit) {
|
|
245
|
+
try {
|
|
246
|
+
return await hit.arrayBuffer();
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
/* fall through to throw original */
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
throw e;
|
|
253
|
+
}
|
|
254
|
+
if (hit) {
|
|
255
|
+
try {
|
|
256
|
+
return await hit.arrayBuffer();
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
/* fall through to direct error below */
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
throw new Error(`fetch failed for ${url}`);
|
|
263
|
+
}
|
|
264
|
+
const res = await fetchWithRetry(url, { signal: opts?.signal ?? undefined });
|
|
265
|
+
opts?.onHeaders?.(res);
|
|
266
|
+
if (!res.ok)
|
|
267
|
+
throw new Error(`fetch failed for ${url}: ${res.status}`);
|
|
268
|
+
return await res.arrayBuffer();
|
|
269
|
+
}
|
|
270
|
+
export async function loadNodeBundle(modelDirOrRepo, opts) {
|
|
271
|
+
const fs = await import("node:fs/promises");
|
|
272
|
+
const path = await import("node:path");
|
|
273
|
+
const os = await import("node:os");
|
|
274
|
+
const sub = opts?.subfolder ?? null;
|
|
275
|
+
let dir = opts?.localDir ?? modelDirOrRepo;
|
|
276
|
+
let resolvedRevision = null;
|
|
277
|
+
try {
|
|
278
|
+
const st = await fs.stat(sub ? path.join(dir, sub) : dir);
|
|
279
|
+
if (st.isDirectory())
|
|
280
|
+
dir = sub ? path.join(dir, sub) : dir;
|
|
281
|
+
else
|
|
282
|
+
dir = path.dirname(dir);
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
// An explicit revision joins the cache key so differently-pinned artifacts never collide;
|
|
286
|
+
// otherwise the existing Hub-default cache is reused.
|
|
287
|
+
const revision = resolveRevision(modelDirOrRepo, opts?.revision);
|
|
288
|
+
resolvedRevision = revision;
|
|
289
|
+
const cache = path.join(os.homedir(), ".cache", "laya-ts", "hf", modelDirOrRepo.replace(/\//g, "__"), sub ?? "root", ...(revision && revision !== "main" ? [revision] : []));
|
|
290
|
+
await fs.mkdir(cache, { recursive: true });
|
|
291
|
+
const token = opts?.token ?? (typeof process !== "undefined" ? process.env?.["HF_TOKEN"] : undefined);
|
|
292
|
+
const files = ["rl_agent_config.json", "tokenizer.json", "tokenizer/tokenizer.json", "encoder.onnx", "head.onnx"];
|
|
293
|
+
let done = 0;
|
|
294
|
+
for (const f of files) {
|
|
295
|
+
try {
|
|
296
|
+
await fs.stat(path.join(cache, f));
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
const url = `https://huggingface.co/${modelDirOrRepo}/resolve/${revision ?? "main"}/${sub ? sub + "/" : ""}${f}`;
|
|
300
|
+
const res = await fetchWithRetry(url, {
|
|
301
|
+
...(token ? { headers: { Authorization: `Bearer ${token}` } } : {}),
|
|
302
|
+
signal: opts?.signal ?? undefined,
|
|
303
|
+
});
|
|
304
|
+
const commit = res.headers?.get?.("x-repo-commit");
|
|
305
|
+
if (commit)
|
|
306
|
+
resolvedRevision = commit;
|
|
307
|
+
if (!res.ok) {
|
|
308
|
+
if (f === "rl_agent_config.json") {
|
|
309
|
+
throw new Error(`Incompatible model: ${JSON.stringify(modelDirOrRepo)} does not contain 'rl_agent_config.json'.`);
|
|
310
|
+
}
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
const target = path.join(cache, f);
|
|
314
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
315
|
+
// Write-then-rename so an interrupted download never leaves a truncated
|
|
316
|
+
// artifact that later loads treat as complete.
|
|
317
|
+
const tmp = `${target}.tmp-${typeof process !== "undefined" ? process.pid : 0}`;
|
|
318
|
+
await fs.writeFile(tmp, new Uint8Array(await res.arrayBuffer()));
|
|
319
|
+
await fs.rename(tmp, target);
|
|
320
|
+
}
|
|
321
|
+
done++;
|
|
322
|
+
opts?.onProgress?.(done, files.length, f);
|
|
323
|
+
}
|
|
324
|
+
dir = cache;
|
|
325
|
+
}
|
|
326
|
+
// Opt-in integrity check over the resolved directory (covers local dirs, warm cache,
|
|
327
|
+
// and fresh downloads alike) before any artifact is parsed or executed.
|
|
328
|
+
if (opts?.expectedSha256) {
|
|
329
|
+
const { createHash } = await import("node:crypto");
|
|
330
|
+
for (const [rel, want] of Object.entries(opts.expectedSha256)) {
|
|
331
|
+
const norm = normaliseDigestPath(rel);
|
|
332
|
+
let buf;
|
|
333
|
+
try {
|
|
334
|
+
buf = new Uint8Array(await fs.readFile(path.join(dir, norm)));
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
throw new Error(`laya-ts: cannot verify ${JSON.stringify(rel)}: not found under ${dir}`);
|
|
338
|
+
}
|
|
339
|
+
const got = createHash("sha256").update(buf).digest("hex");
|
|
340
|
+
if (got.toLowerCase() !== String(want).trim().toLowerCase()) {
|
|
341
|
+
throw new Error(`laya-ts: SHA-256 mismatch for ${rel}: expected ${want}, got ${got}. Refusing to load the artifact.`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
let cfg = {};
|
|
346
|
+
try {
|
|
347
|
+
cfg = JSON.parse(await fs.readFile(path.join(dir, "rl_agent_config.json"), "utf8"));
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
throw new Error(`Incompatible model: ${JSON.stringify(modelDirOrRepo)} does not contain 'rl_agent_config.json'.`);
|
|
351
|
+
}
|
|
352
|
+
let tokenizerJson = null;
|
|
353
|
+
for (const candidate of TOKENIZER_CANDIDATES) {
|
|
354
|
+
try {
|
|
355
|
+
tokenizerJson = JSON.parse(await fs.readFile(path.join(dir, candidate), "utf8"));
|
|
356
|
+
break;
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
// Try the next supported Hugging Face layout.
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return { dir, cfg, tokenizerJson, revision: resolvedRevision };
|
|
363
|
+
}
|
|
364
|
+
// Scanning from the ends avoids quadratic backtracking over interior slash runs.
|
|
365
|
+
function trimSlashes(value, leading = false) {
|
|
366
|
+
let start = 0;
|
|
367
|
+
let end = value.length;
|
|
368
|
+
if (leading)
|
|
369
|
+
while (start < end && value[start] === "/")
|
|
370
|
+
start++;
|
|
371
|
+
while (end > start && value[end - 1] === "/")
|
|
372
|
+
end--;
|
|
373
|
+
return value.slice(start, end);
|
|
374
|
+
}
|
|
375
|
+
function baseUrlFor(repoOrUrl, subfolder, revision) {
|
|
376
|
+
const sub = subfolder ? `/${trimSlashes(subfolder, true)}` : "";
|
|
377
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(repoOrUrl)) {
|
|
378
|
+
return `${trimSlashes(repoOrUrl)}${sub}`;
|
|
379
|
+
}
|
|
380
|
+
return `https://huggingface.co/${repoOrUrl}/resolve/${revision ?? "main"}${sub}`;
|
|
381
|
+
}
|
|
382
|
+
export async function loadWebBundle(repoOrUrl, opts) {
|
|
383
|
+
const revision = resolveRevision(repoOrUrl, opts?.revision);
|
|
384
|
+
const base = baseUrlFor(repoOrUrl, opts?.subfolder ?? null, revision);
|
|
385
|
+
let reportedRevision = revision;
|
|
386
|
+
const fetchVerifiedJson = async (rel) => {
|
|
387
|
+
const buf = await fetchArrayBuffer(`${base}/${rel}`, {
|
|
388
|
+
signal: opts?.signal ?? undefined,
|
|
389
|
+
onHeaders: (response) => {
|
|
390
|
+
const commit = response.headers?.get?.("x-repo-commit");
|
|
391
|
+
if (commit)
|
|
392
|
+
reportedRevision = commit;
|
|
393
|
+
},
|
|
394
|
+
});
|
|
395
|
+
if (opts?.expectedSha256)
|
|
396
|
+
await expectDigest(rel, buf, opts.expectedSha256);
|
|
397
|
+
return JSON.parse(new TextDecoder().decode(buf));
|
|
398
|
+
};
|
|
399
|
+
let cfg;
|
|
400
|
+
try {
|
|
401
|
+
cfg = await fetchVerifiedJson("rl_agent_config.json");
|
|
402
|
+
}
|
|
403
|
+
catch (e) {
|
|
404
|
+
if (e instanceof Error && e.message.startsWith("laya-ts: SHA-256 mismatch"))
|
|
405
|
+
throw e;
|
|
406
|
+
if (e?.name === "AbortError")
|
|
407
|
+
throw e;
|
|
408
|
+
throw new Error(`Incompatible model: ${JSON.stringify(repoOrUrl)} does not contain 'rl_agent_config.json'.`);
|
|
409
|
+
}
|
|
410
|
+
opts?.onProgress?.(1, 2, "rl_agent_config.json");
|
|
411
|
+
let tokenizerJson = null;
|
|
412
|
+
for (const candidate of TOKENIZER_CANDIDATES) {
|
|
413
|
+
try {
|
|
414
|
+
tokenizerJson = await fetchVerifiedJson(candidate);
|
|
415
|
+
break;
|
|
416
|
+
}
|
|
417
|
+
catch (e) {
|
|
418
|
+
if (e instanceof Error && e.message.startsWith("laya-ts: SHA-256 mismatch"))
|
|
419
|
+
throw e;
|
|
420
|
+
// Try the next supported Hugging Face layout.
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
opts?.onProgress?.(2, 2, "tokenizer.json");
|
|
424
|
+
return { dir: base, cfg, tokenizerJson, revision: reportedRevision };
|
|
425
|
+
}
|
|
426
|
+
export async function createNodeProvider(modelDir, opts) {
|
|
427
|
+
const fs = await import("node:fs/promises");
|
|
428
|
+
const path = await import("node:path");
|
|
429
|
+
// Verify the artifacts and their digests BEFORE importing the native runtime. `onnxruntime-node`
|
|
430
|
+
// is an optional dependency, so a caller that names a bad or missing artifact must still get that
|
|
431
|
+
// error on a machine where npm skipped the native module; importing it first masked the digest
|
|
432
|
+
// check with `Cannot find package 'onnxruntime-node'` (an intermittent `laya-ts` CI failure). A
|
|
433
|
+
// mismatch also should not pay for loading the runtime.
|
|
434
|
+
for (const f of ["encoder.onnx", "head.onnx"]) {
|
|
435
|
+
const p = path.join(modelDir, f);
|
|
436
|
+
try {
|
|
437
|
+
await fs.stat(p);
|
|
438
|
+
}
|
|
439
|
+
catch {
|
|
440
|
+
throw new Error(`Incompatible model: '${f}' not found in ${JSON.stringify(modelDir)} (expected ${p}).`);
|
|
441
|
+
}
|
|
442
|
+
if (opts?.expectedSha256)
|
|
443
|
+
await expectDigest(f, await fs.readFile(p), opts.expectedSha256);
|
|
444
|
+
}
|
|
445
|
+
const spec = "onnxruntime-" + "node";
|
|
446
|
+
const ort = await import(/* @vite-ignore */ spec);
|
|
447
|
+
applyNumThreads(ort, opts?.numThreads);
|
|
448
|
+
const dev = String(opts?.device ?? "cpu").toLowerCase();
|
|
449
|
+
const want = dev === "cuda" ? "cuda" : dev === "dml" ? "dml" : "cpu";
|
|
450
|
+
const make = async (ep) => {
|
|
451
|
+
const e = await ort.InferenceSession.create(`${modelDir}/encoder.onnx`, {
|
|
452
|
+
executionProviders: [ep],
|
|
453
|
+
});
|
|
454
|
+
const h = await ort.InferenceSession.create(`${modelDir}/head.onnx`, {
|
|
455
|
+
executionProviders: ["cpu"],
|
|
456
|
+
});
|
|
457
|
+
return { e, h };
|
|
458
|
+
};
|
|
459
|
+
let enc;
|
|
460
|
+
let head;
|
|
461
|
+
let activeEP = want;
|
|
462
|
+
try {
|
|
463
|
+
({ e: enc, h: head } = await make(want));
|
|
464
|
+
}
|
|
465
|
+
catch (e) {
|
|
466
|
+
if (want !== "cpu") {
|
|
467
|
+
console.warn(`Warning: ${want.toUpperCase()} requested but not available. Falling back to CPU.`);
|
|
468
|
+
({ e: enc, h: head } = await make("cpu"));
|
|
469
|
+
activeEP = "cpu";
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
throw e;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
let cpuEnc = null;
|
|
476
|
+
let cpuHead = null;
|
|
477
|
+
const ensureCpu = async () => {
|
|
478
|
+
if (!cpuEnc) {
|
|
479
|
+
cpuEnc = await ort.InferenceSession.create(`${modelDir}/encoder.onnx`, {
|
|
480
|
+
executionProviders: ["cpu"],
|
|
481
|
+
});
|
|
482
|
+
cpuHead = await ort.InferenceSession.create(`${modelDir}/head.onnx`, {
|
|
483
|
+
executionProviders: ["cpu"],
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
return { cpuEnc, cpuHead };
|
|
487
|
+
};
|
|
488
|
+
const runWithCpuFallback = async (fn) => {
|
|
489
|
+
try {
|
|
490
|
+
return await fn(enc, head);
|
|
491
|
+
}
|
|
492
|
+
catch (e) {
|
|
493
|
+
if (activeEP !== "cpu" && isOomError(e)) {
|
|
494
|
+
console.warn("Warning: GPU memory exceeded during inference. Falling back to CPU...");
|
|
495
|
+
const { cpuEnc: ce, cpuHead: ch } = await ensureCpu();
|
|
496
|
+
enc = ce;
|
|
497
|
+
head = ch;
|
|
498
|
+
activeEP = "cpu";
|
|
499
|
+
return await fn(enc, head);
|
|
500
|
+
}
|
|
501
|
+
if (isOomError(e)) {
|
|
502
|
+
throw new Error(`${e.message} (GPU out of memory; try device: "cpu")`);
|
|
503
|
+
}
|
|
504
|
+
throw e;
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
return {
|
|
508
|
+
runEncoder: async (b) => runWithCpuFallback(async (e) => {
|
|
509
|
+
const out = await e.run(feed(ort, b));
|
|
510
|
+
const t = pickOutput(out, ["last_hidden_state", "lastHidden", "hidden_states"]);
|
|
511
|
+
return { lastHidden: toNested(t.data, t.dims) };
|
|
512
|
+
}),
|
|
513
|
+
runHead: async (h, b) => runWithCpuFallback(async (_e, hd) => {
|
|
514
|
+
const out = await hd.run(feedHead(ort, h, b));
|
|
515
|
+
const vals = Object.values(out);
|
|
516
|
+
const lt = pickOutput(out, ["logits"]);
|
|
517
|
+
const at = pickOutput(out, ["act_logits", "act"]) ?? vals[1] ?? vals[0];
|
|
518
|
+
return { logits: toNested(lt.data, lt.dims), act: toNested(at.data, at.dims) };
|
|
519
|
+
}),
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
/** Best-effort fetch of a `<model>.data` sidecar; null when the model is single-file. */
|
|
523
|
+
async function fetchSidecar(url) {
|
|
524
|
+
const name = `${url.split("/").pop()}.data`;
|
|
525
|
+
const sidecarUrl = `${trimSlashes(url).split("/").slice(0, -1).join("/")}/${name}`;
|
|
526
|
+
try {
|
|
527
|
+
const buf = await fetchArrayBuffer(sidecarUrl);
|
|
528
|
+
return { path: name, data: new Uint8Array(buf) };
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
export async function createWebProvider(modelUrl, opts) {
|
|
535
|
+
const spec = "onnxruntime-" + "web";
|
|
536
|
+
const ort = await import(/* @vite-ignore */ spec);
|
|
537
|
+
applyNumThreads(ort, opts?.numThreads);
|
|
538
|
+
const base = trimSlashes(modelUrl);
|
|
539
|
+
const encUrl = `${base}/encoder.onnx`;
|
|
540
|
+
const headUrl = `${base}/head.onnx`;
|
|
541
|
+
// (Re-)read through fetchArrayBuffer so repeat reads hit CacheStorage.
|
|
542
|
+
// Nothing pin-worthy is retained: after each create, buffers are droppable.
|
|
543
|
+
const readEncoderParts = async (signal) => {
|
|
544
|
+
const buf = await fetchArrayBuffer(encUrl, { signal: signal ?? undefined });
|
|
545
|
+
const sidecar = await fetchSidecar(encUrl);
|
|
546
|
+
return { buf, extra: sidecar ? { externalData: [sidecar] } : {} };
|
|
547
|
+
};
|
|
548
|
+
let encBuf;
|
|
549
|
+
let encExtra;
|
|
550
|
+
try {
|
|
551
|
+
({ buf: encBuf, extra: encExtra } = await readEncoderParts(opts?.signal));
|
|
552
|
+
}
|
|
553
|
+
catch (e) {
|
|
554
|
+
if (e?.name === "AbortError")
|
|
555
|
+
throw e;
|
|
556
|
+
throw new Error(`Incompatible model: 'encoder.onnx' not found (expected ${encUrl}).`);
|
|
557
|
+
}
|
|
558
|
+
opts?.onProgress?.(1, 2, "encoder.onnx");
|
|
559
|
+
let headBuf;
|
|
560
|
+
try {
|
|
561
|
+
headBuf = await fetchArrayBuffer(headUrl, { signal: opts?.signal ?? undefined });
|
|
562
|
+
}
|
|
563
|
+
catch (e) {
|
|
564
|
+
if (e?.name === "AbortError")
|
|
565
|
+
throw e;
|
|
566
|
+
throw new Error(`Incompatible model: 'head.onnx' not found (expected ${headUrl}).`);
|
|
567
|
+
}
|
|
568
|
+
opts?.onProgress?.(2, 2, "head.onnx");
|
|
569
|
+
// Verify before the bytes reach the runtime: a tampered ONNX never becomes a session.
|
|
570
|
+
if (opts?.expectedSha256) {
|
|
571
|
+
await expectDigest("encoder.onnx", encBuf, opts.expectedSha256);
|
|
572
|
+
await expectDigest("head.onnx", headBuf, opts.expectedSha256);
|
|
573
|
+
}
|
|
574
|
+
// Split ONNX references its weights relatively ("encoder.onnx.data"); buffered
|
|
575
|
+
// sessions have no filesystem, so mount the sidecar via externalData.
|
|
576
|
+
const headSidecar = await fetchSidecar(headUrl);
|
|
577
|
+
const headExtra = headSidecar ? { externalData: [headSidecar] } : {};
|
|
578
|
+
let enc;
|
|
579
|
+
try {
|
|
580
|
+
// "basic" skips the Skip+LayerNorm fusion whose fused Beta shape the
|
|
581
|
+
// WebGPU kernel rejects; unfused LayerNormalization runs fine on GPU.
|
|
582
|
+
enc = await ort.InferenceSession.create(new Uint8Array(encBuf), {
|
|
583
|
+
executionProviders: ["webgpu", "wasm"],
|
|
584
|
+
graphOptimizationLevel: "basic",
|
|
585
|
+
...encExtra,
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
catch (e) {
|
|
589
|
+
enc = await ort.InferenceSession.create(new Uint8Array(encBuf), {
|
|
590
|
+
executionProviders: ["wasm"],
|
|
591
|
+
...encExtra,
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
const head = await ort.InferenceSession.create(new Uint8Array(headBuf), {
|
|
595
|
+
executionProviders: ["wasm"],
|
|
596
|
+
...headExtra,
|
|
597
|
+
});
|
|
598
|
+
// Lazy WASM encoder: some graphs pass WebGPU session creation but hit an
|
|
599
|
+
// unsupported kernel at run time (e.g. SkipLayerNormalization shape gaps).
|
|
600
|
+
// On the first such failure we build a WASM session and stick with it.
|
|
601
|
+
let encWasm = null;
|
|
602
|
+
const runEncoderOn = async (session, b) => {
|
|
603
|
+
const out = await session.run(feed(ort, b));
|
|
604
|
+
const t = pickOutput(out, ["last_hidden_state", "lastHidden", "hidden_states"]);
|
|
605
|
+
return { lastHidden: toNested(t.data, t.dims) };
|
|
606
|
+
};
|
|
607
|
+
return {
|
|
608
|
+
runEncoder: async (b) => {
|
|
609
|
+
if (encWasm) {
|
|
610
|
+
try {
|
|
611
|
+
return await runEncoderOn(encWasm, b);
|
|
612
|
+
}
|
|
613
|
+
catch (e) {
|
|
614
|
+
if (isOomError(e))
|
|
615
|
+
throw new Error(`${e.message} (out of memory; try fewer questions per call)`);
|
|
616
|
+
throw e;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
try {
|
|
620
|
+
return await runEncoderOn(enc, b);
|
|
621
|
+
}
|
|
622
|
+
catch (e) {
|
|
623
|
+
if (isOomError(e))
|
|
624
|
+
throw new Error(`${e.message} (WebGPU out of memory; WASM fallback already active)`);
|
|
625
|
+
if (/\[webgpu\]/i.test(String(e?.message ?? e))) {
|
|
626
|
+
console.warn(`laya: WebGPU encoder run failed (${String(e?.message ?? e)}); falling back to WASM.`);
|
|
627
|
+
if (!encWasm) {
|
|
628
|
+
// Re-read through the cache instead of pinning 1GB+ for the agent's life.
|
|
629
|
+
let parts;
|
|
630
|
+
try {
|
|
631
|
+
parts = await readEncoderParts();
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
throw e;
|
|
635
|
+
}
|
|
636
|
+
encWasm = await ort.InferenceSession.create(new Uint8Array(parts.buf), {
|
|
637
|
+
executionProviders: ["wasm"],
|
|
638
|
+
...parts.extra,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
try {
|
|
642
|
+
return await runEncoderOn(encWasm, b);
|
|
643
|
+
}
|
|
644
|
+
catch (e2) {
|
|
645
|
+
if (isOomError(e2))
|
|
646
|
+
throw new Error(`${e2.message} (out of memory; try fewer questions per call)`);
|
|
647
|
+
throw e2;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
throw e;
|
|
651
|
+
}
|
|
652
|
+
},
|
|
653
|
+
runHead: async (h, b) => {
|
|
654
|
+
try {
|
|
655
|
+
const out = await head.run(feedHead(ort, h, b));
|
|
656
|
+
const vals = Object.values(out);
|
|
657
|
+
const lt = pickOutput(out, ["logits"]);
|
|
658
|
+
const at = pickOutput(out, ["act_logits", "act"]) ?? vals[1] ?? vals[0];
|
|
659
|
+
return { logits: toNested(lt.data, lt.dims), act: toNested(at.data, at.dims) };
|
|
660
|
+
}
|
|
661
|
+
catch (e) {
|
|
662
|
+
if (isOomError(e))
|
|
663
|
+
throw new Error(`${e.message} (out of memory; try fewer questions per call)`);
|
|
664
|
+
throw e;
|
|
665
|
+
}
|
|
666
|
+
},
|
|
667
|
+
};
|
|
668
|
+
}
|