@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.
Files changed (43) hide show
  1. package/README.md +38 -2
  2. package/lib/index.d.ts +18 -0
  3. package/lib/index.js +172 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/pure.d.ts +35 -0
  6. package/lib/pure.js +71 -0
  7. package/lib/pure.js.map +1 -0
  8. package/models.lock.json +63 -0
  9. package/package.json +39 -4
  10. package/schema/decision-choose.input.json +22 -0
  11. package/schema/decision-choose.output.json +20 -0
  12. package/schema/decision-score.input.json +18 -0
  13. package/schema/decision-score.output.json +18 -0
  14. package/schema/decision-test.input.json +10 -0
  15. package/schema/decision-test.output.json +18 -0
  16. package/tool-mode.extension.json +87 -0
  17. package/vendor/LICENSE.laya-ts +176 -0
  18. package/vendor/laya-ts/agent.d.ts +216 -0
  19. package/vendor/laya-ts/agent.js +631 -0
  20. package/vendor/laya-ts/common.d.ts +167 -0
  21. package/vendor/laya-ts/common.js +478 -0
  22. package/vendor/laya-ts/dx.d.ts +17 -0
  23. package/vendor/laya-ts/dx.js +46 -0
  24. package/vendor/laya-ts/email.d.ts +2 -0
  25. package/vendor/laya-ts/email.js +184 -0
  26. package/vendor/laya-ts/hooks.d.ts +134 -0
  27. package/vendor/laya-ts/hooks.js +379 -0
  28. package/vendor/laya-ts/index.d.ts +22 -0
  29. package/vendor/laya-ts/index.js +13 -0
  30. package/vendor/laya-ts/lang.d.ts +24 -0
  31. package/vendor/laya-ts/lang.js +590 -0
  32. package/vendor/laya-ts/presets.d.ts +5 -0
  33. package/vendor/laya-ts/presets.js +175 -0
  34. package/vendor/laya-ts/providers.d.ts +67 -0
  35. package/vendor/laya-ts/providers.js +668 -0
  36. package/vendor/laya-ts/router.d.ts +186 -0
  37. package/vendor/laya-ts/router.js +757 -0
  38. package/vendor/laya-ts/shortlist.d.ts +65 -0
  39. package/vendor/laya-ts/shortlist.js +407 -0
  40. package/vendor/laya-ts/structured.d.ts +89 -0
  41. package/vendor/laya-ts/structured.js +256 -0
  42. package/vendor/laya-ts/tokenizer.d.ts +66 -0
  43. package/vendor/laya-ts/tokenizer.js +482 -0
@@ -0,0 +1,631 @@
1
+ import { TEMP_MAX, TEMP_MIN, applyBinningMap, buildQuestionPrefix, checkBinningMap, clampTemperature, collateItems, collapsedOptions, confidenceFromProbs, answerConfidence, checkMinConfidence, flagLowConfidence, renderCriterion, renderOptions, sequenceWithState, serializeState, softmax, tempBucket, } from "./common.js";
2
+ import { encodeWithData, parseTokenizerJson } from "./tokenizer.js";
3
+ import { decide } from "./structured.js";
4
+ import { HookRegistry, PredictContext, aggregateUsage, composeHooks, defaultsAlreadyRan, dispatchAsync, normaliseHooks, } from "./hooks.js";
5
+ export const QTYPES = { choice: 0, score: 1, noul: 2 };
6
+ function qidStr(qid) {
7
+ return JSON.stringify(qid);
8
+ }
9
+ export function checkQuestion(qid, qdef) {
10
+ if (typeof qid !== "string" || !qid.trim()) {
11
+ throw new Error(`question id must be a non-empty string, got ${qidStr(qid)}`);
12
+ }
13
+ if (typeof qdef !== "object" || qdef === null || Array.isArray(qdef)) {
14
+ const got = Array.isArray(qdef) ? "list" : qdef === null ? "NoneType" : typeof qdef;
15
+ throw new Error(`question ${qidStr(qid)}: definition must be a dict, got ${got}`);
16
+ }
17
+ const q = qdef;
18
+ const t = q["type"];
19
+ if (t !== "choice" && t !== "score" && t !== "noul") {
20
+ throw new Error(`question ${qidStr(qid)}: unknown type ${JSON.stringify(t)}; use one of ${JSON.stringify(Object.keys(QTYPES).sort())}`);
21
+ }
22
+ if (!("instructions" in q)) {
23
+ throw new Error(`question ${qidStr(qid)}: no 'instructions'; add the text the model should answer`);
24
+ }
25
+ // `instructions` is the text the model is asked, so a null or empty one is not a weak question
26
+ // but a question with nothing to answer. Only the key's presence was checked, and `toInternal`
27
+ // then serialised whatever it found, so a null reached the model as the literal prompt "null",
28
+ // an empty dict as "{}", and a blank string stayed blank -- the caller's error answered
29
+ // silently. Python's `Agent._check_question` rejects all of these; these are the same three
30
+ // rejections in the same order.
31
+ const ins = q["instructions"];
32
+ if (ins === null || ins === undefined) {
33
+ throw new Error(`question ${qidStr(qid)}: 'instructions' must not be None; add the text the model should answer`);
34
+ }
35
+ if (typeof ins === "string" && !ins.trim()) {
36
+ throw new Error(`question ${qidStr(qid)}: 'instructions' must not be empty; add the text the model should answer`);
37
+ }
38
+ // An object here is a list or a dict, and both are empty exactly when they own no keys.
39
+ if (typeof ins === "object" && Object.keys(ins).length === 0) {
40
+ throw new Error(`question ${qidStr(qid)}: 'instructions' must not be empty; add the text the model should answer`);
41
+ }
42
+ // Python allows str, dict, list, int and float. A bool is an int there, so it passes as well;
43
+ // a function or a symbol is nothing either side can turn into a question.
44
+ if (!["string", "object", "number", "bigint", "boolean"].includes(typeof ins)) {
45
+ throw new Error(`question ${qidStr(qid)}: 'instructions' must be a string, dict, or list, got ${typeof ins}`);
46
+ }
47
+ const crit = q["criteria"];
48
+ if (t === "choice") {
49
+ if (typeof crit !== "object" || crit === null) {
50
+ throw new Error(`question ${qidStr(qid)}: a choice question takes 'criteria' as a dict of label -> description, or a list of labels`);
51
+ }
52
+ if (Object.keys(crit).length === 0) {
53
+ throw new Error(`question ${qidStr(qid)}: a choice question needs at least one criterion`);
54
+ }
55
+ if (Array.isArray(crit)) {
56
+ // An indexed loop, not forEach: a hole in a sparse list is an undefined label too.
57
+ for (let i = 0; i < crit.length; i++) {
58
+ const label = crit[i];
59
+ if (label === null || label === undefined) {
60
+ // A null label becomes the answer key "null", which a client cannot tell apart from
61
+ // the string "null", and `criteria[choice]` never finds it. Python rejects it (#508).
62
+ throw new Error(`question ${qidStr(qid)}: choice label ${i} is null; a label is rendered as option text and used ` +
63
+ `as the answer key, so it must be a string, number or bool`);
64
+ }
65
+ if (typeof label !== "object")
66
+ continue;
67
+ throw new Error(`question ${qidStr(qid)}: choice label ${i} is a ${Array.isArray(label) ? "list" : "dict"}; a label is ` +
68
+ `rendered as option text and used as the answer key, so it must be a scalar (a string, number or ` +
69
+ `bool), got ${JSON.stringify(label)}`);
70
+ }
71
+ // toInternal turns the list into an object, so each label's String() is its answer key;
72
+ // two labels on one key would silently drop an option. Python rejects them (#496).
73
+ const seen = new Map();
74
+ crit.forEach((label, i) => {
75
+ const key = String(label);
76
+ const first = seen.get(key);
77
+ if (first === undefined) {
78
+ seen.set(key, i);
79
+ return;
80
+ }
81
+ throw new Error(`question ${qidStr(qid)}: choice label ${i} (${JSON.stringify(label)}) repeats label ${first}; the ` +
82
+ `labels are the answer keys, so every option needs its own (1 and "1" are one key)`);
83
+ });
84
+ }
85
+ }
86
+ else if (t === "score") {
87
+ if (!Array.isArray(crit)) {
88
+ throw new Error(`question ${qidStr(qid)}: a score question takes 'criteria' as a list of level descriptions, index 0 first`);
89
+ }
90
+ if (crit.length === 0) {
91
+ throw new Error(`question ${qidStr(qid)}: a score question needs at least one level`);
92
+ }
93
+ const nullAt = crit.findIndex((c) => c === null || c === undefined);
94
+ if (nullAt >= 0) {
95
+ throw new Error(`question ${qidStr(qid)}: score level ${nullAt} is null; give every level a description, index 0 first`);
96
+ }
97
+ }
98
+ else if (crit !== undefined && crit !== null && (typeof crit !== "object" || Array.isArray(crit))) {
99
+ throw new Error(`question ${qidStr(qid)}: a noul question takes 'criteria' as a dict with optional 'true'/'false' descriptions, or omits it`);
100
+ }
101
+ else if (crit && typeof crit === "object" && !Array.isArray(crit)) {
102
+ const invalid = Object.keys(crit).filter((key) => key.toLowerCase() !== "true" && key.toLowerCase() !== "false");
103
+ if (invalid.length > 0) {
104
+ throw new Error(`question ${qidStr(qid)}: noul criteria may contain only 'true' and 'false'; got ${JSON.stringify(invalid)}`);
105
+ }
106
+ }
107
+ if ("labels" in q && t !== "noul") {
108
+ throw new Error(`question ${qidStr(qid)}: 'labels' is only supported for noul questions`);
109
+ }
110
+ if (t === "noul" && q["labels"] !== null && q["labels"] !== undefined) {
111
+ const labels = q["labels"];
112
+ if (typeof labels !== "object" || labels === null || Array.isArray(labels)) {
113
+ throw new Error(`question ${qidStr(qid)}: noul labels must be an object with 'false' and 'true'`);
114
+ }
115
+ const entries = Object.entries(labels);
116
+ const keys = entries.map(([key]) => key).sort();
117
+ if (keys.length !== 2 || keys[0] !== "false" || keys[1] !== "true" ||
118
+ entries.some(([, value]) => typeof value !== "string" || value.trim() === "")) {
119
+ throw new Error(`question ${qidStr(qid)}: noul labels must map exactly 'false' and 'true' to distinct non-empty strings`);
120
+ }
121
+ const falseLabel = String(labels["false"]).trim();
122
+ const trueLabel = String(labels["true"]).trim();
123
+ if (falseLabel === trueLabel) {
124
+ throw new Error(`question ${qidStr(qid)}: noul labels must be distinct`);
125
+ }
126
+ }
127
+ }
128
+ function isPlainDict(o) {
129
+ if (typeof o !== "object" || o === null || Array.isArray(o))
130
+ return false;
131
+ const proto = Object.getPrototypeOf(o);
132
+ return proto === null || proto === Object.prototype;
133
+ }
134
+ /** Whether a `temperature_by_options` value means "no override" in Python.
135
+ *
136
+ * `cfg.get("temperature_by_options") or {}` turns every Python-falsy value into `{}`, and the
137
+ * two languages disagree about which values those are: an empty array is truthy in JavaScript,
138
+ * and NaN is falsy here while truthy in Python. So the set is named rather than inferred from
139
+ * JavaScript truthiness. Python's own falsy values are `[]`, `{}`, `0`, `0.0`, `False`, `None`
140
+ * and `""`; `{}` needs no case here because a dict is accepted either way.
141
+ */
142
+ function isEmptyOverride(v) {
143
+ if (v === null || v === undefined || v === false || v === "")
144
+ return true;
145
+ if (v === 0)
146
+ return true; // `===`, not Object.is: that distinguishes -0 from 0
147
+ return Array.isArray(v) && v.length === 0; // [] -- truthy in JavaScript
148
+ }
149
+ export function toInternal(qdef) {
150
+ const t = qdef["type"];
151
+ let crit = qdef["criteria"];
152
+ if (t === "choice" && Array.isArray(crit)) {
153
+ crit = Object.fromEntries(crit.map((c) => [c, null]));
154
+ }
155
+ else if (t === "noul" && crit !== null && crit !== undefined && typeof crit === "object" && !Array.isArray(crit)) {
156
+ crit = Object.fromEntries(Object.entries(crit).map(([k, v]) => [String(k).toLowerCase(), v]));
157
+ }
158
+ let ins = qdef["instructions"];
159
+ if (typeof ins !== "string")
160
+ ins = serializeState(ins);
161
+ const out = {
162
+ t, ins: ins, crit,
163
+ };
164
+ if (t === "noul" && qdef["labels"] && typeof qdef["labels"] === "object" && !Array.isArray(qdef["labels"])) {
165
+ const labels = qdef["labels"];
166
+ out.labels = { false: String(labels["false"]).trim(), true: String(labels["true"]).trim() };
167
+ }
168
+ return out;
169
+ }
170
+ export function defaultTokenizer() {
171
+ return {
172
+ clsId: 101,
173
+ sepId: 102,
174
+ maskId: 103,
175
+ padId: 0,
176
+ maskToken: "[MASK]",
177
+ encode(text) {
178
+ return text
179
+ .split(/\s+/)
180
+ .filter(Boolean)
181
+ .map((w, i) => 1000 + ((w.length * 31 + i * 7) % 20000));
182
+ },
183
+ };
184
+ }
185
+ function tokenizerFromHF(tokenizerJson) {
186
+ const data = parseTokenizerJson(tokenizerJson);
187
+ if (!data)
188
+ return null;
189
+ return {
190
+ clsId: data.ids.cls,
191
+ sepId: data.ids.sep,
192
+ maskId: data.ids.mask,
193
+ padId: data.ids.pad,
194
+ maskToken: data.maskToken,
195
+ encode: (text) => encodeWithData(data, text),
196
+ };
197
+ }
198
+ const r4 = (v) => Math.round(v * 1e4) / 1e4;
199
+ export class Agent extends HookRegistry {
200
+ hooksRaise;
201
+ hooksTimeout;
202
+ cfg;
203
+ provider;
204
+ revision;
205
+ tok;
206
+ maxLen;
207
+ headMaxLen;
208
+ temperatureRaw;
209
+ temperatureByOptionsRaw;
210
+ temperature;
211
+ temperatureByOptions;
212
+ binningMap;
213
+ langTemperatures;
214
+ constructor(opts) {
215
+ super();
216
+ if (!opts || !opts.provider)
217
+ throw new Error("Agent needs a provider");
218
+ this.provider = opts.provider;
219
+ this.revision = opts.revision ?? null;
220
+ // Hooks are opt-in; an unset hook list is a no-op. See hooks.ts.
221
+ this.hooks = normaliseHooks(opts.hooks, opts.onPredictStart, opts.onPredictEnd);
222
+ this.hooksRaise = opts.hooksRaise ?? true;
223
+ this.hooksTimeout = opts.hooksTimeout ?? null;
224
+ const cfg = { ...(opts.cfg ?? {}) };
225
+ if (opts.max_len !== undefined)
226
+ cfg.max_len = opts.max_len;
227
+ if (opts.head_max_len !== undefined)
228
+ cfg.head_max_len = opts.head_max_len;
229
+ if (opts.temperature !== undefined)
230
+ cfg.temperature = opts.temperature;
231
+ if (opts.temperature_by_options !== undefined)
232
+ cfg.temperature_by_options = opts.temperature_by_options;
233
+ if (opts.binning_map !== undefined)
234
+ cfg.binning_map = opts.binning_map;
235
+ if (opts.binningMap !== undefined)
236
+ cfg.binning_map = opts.binningMap;
237
+ this.cfg = cfg;
238
+ this.maxLen = Number(cfg.max_len ?? 512);
239
+ this.headMaxLen = Number(cfg.head_max_len ?? 192);
240
+ this.tok = opts.tok ?? defaultTokenizer();
241
+ const bmapRaw = cfg.binning_map;
242
+ this.binningMap = bmapRaw !== undefined && bmapRaw !== null ? checkBinningMap(bmapRaw) : null;
243
+ const raw = (cfg.temperature ?? [1.0, 1.0, 1.0]);
244
+ this.temperatureRaw = raw;
245
+ // The decode indexes this by question type, so refuse any other shape here, as Python's
246
+ // Agent.__init__ does (#502): a short list silently fell back to 1.0 per missing type.
247
+ if (!Array.isArray(raw) || raw.length !== 3) {
248
+ throw new Error(`Incompatible model: temperature must be a list of 3 floats, got ${JSON.stringify(raw)}`);
249
+ }
250
+ const rawList = raw;
251
+ this.temperature = rawList.map((t) => clampTemperature(t));
252
+ this.temperatureByOptionsRaw = (cfg.temperature_by_options ?? {});
253
+ this.temperatureByOptions = Object.fromEntries(Object.entries(this.temperatureByOptionsRaw).map(([k, v]) => [k, clampTemperature(v)]));
254
+ const entries = [
255
+ ...Object.entries(this.temperatureByOptionsRaw).map(([k, v]) => [k, v, this.temperatureByOptions[k]]),
256
+ ...[0, 1, 2].map((i) => [`temperature[${i}]`, rawList[i], this.temperature[i]]),
257
+ ];
258
+ const rejected = [];
259
+ for (const [name, rawV, applied] of entries) {
260
+ if (Number(rawV) === applied)
261
+ continue;
262
+ rejected.push(`${name}=${JSON.stringify(rawV) ?? String(rawV)} -> ${applied}`);
263
+ }
264
+ if (rejected.length > 0) {
265
+ console.warn(`laya: this checkpoint ships invalid temperatures or values outside [${TEMP_MIN}, ${TEMP_MAX}]; ` +
266
+ `using ${rejected.join(", ")}. Treat confidence from the affected entries as uncalibrated.`);
267
+ }
268
+ // Mirrors Agent.__init__ (agent.py): keys normalise to the base subtag, an omitted
269
+ // temperature defaults to the base raw temperature, and every value is clamped.
270
+ this.langTemperatures = {};
271
+ for (const [l, lc] of Object.entries(opts.lang_temperatures ?? {})) {
272
+ const normL = l.split("-")[0].toLowerCase();
273
+ const tRaw = lc?.temperature ?? rawList;
274
+ if (!Array.isArray(tRaw) || tRaw.length !== 3) {
275
+ throw new Error(`Language override ${JSON.stringify(l)} temperature must be a list of 3 floats`);
276
+ }
277
+ const tboRaw = lc?.temperature_by_options;
278
+ // Python: `cfg.get("temperature_by_options") or {}`, then `isinstance(..., dict)`. So a
279
+ // Python-falsy value is an empty override, a dict is kept, and anything else is rejected
280
+ // naming the language. isPlainDict is the module's own mapping test, so a Map, Set or Date
281
+ // is refused instead of being read as {} by Object.entries -- a configured override that
282
+ // silently does nothing is the same failure as no override at all.
283
+ if (!isEmptyOverride(tboRaw) && !isPlainDict(tboRaw)) {
284
+ throw new Error(`Language override ${JSON.stringify(l)} temperature_by_options must be a mapping of ` +
285
+ `bucket -> float, got ${Array.isArray(tboRaw) ? "list" : typeof tboRaw}`);
286
+ }
287
+ const tboDict = isPlainDict(tboRaw) ? tboRaw : {};
288
+ this.langTemperatures[normL] = {
289
+ temperature: [0, 1, 2].map((i) => clampTemperature(tRaw[i])),
290
+ temperatureByOptions: Object.fromEntries(Object.entries(tboDict).map(([k, v]) => [k, clampTemperature(v)])),
291
+ };
292
+ }
293
+ }
294
+ /**
295
+ * Evaluate typed questions across one state in a single forward pass.
296
+ *
297
+ * `hooks` / `onPredictStart` / `onPredictEnd` observe or shape the prediction, appended
298
+ * after any hooks installed on the Agent; a start hook may rewrite the state/questions or
299
+ * call `ctx.skip(...)` to short-circuit inference, an end hook may rewrite the results.
300
+ * See hooks.ts. `hooksRaise` overrides the Agent's setting for this call.
301
+ */
302
+ async systemOne(state, questions, opts = {}) {
303
+ return (await this._predictHooked([state], questions, opts))[0];
304
+ }
305
+ async _predictHooked(states, questions, opts) {
306
+ const mcOpt = opts.minConfidence ?? opts.min_confidence;
307
+ const mc = mcOpt !== undefined && mcOpt !== null ? checkMinConfidence(mcOpt) : null;
308
+ const active = defaultsAlreadyRan(opts)
309
+ ? [...this.hooks, ...normaliseHooks(opts.hooks, opts.onPredictStart, opts.onPredictEnd)]
310
+ : composeHooks(this.hooks, opts.hooks, opts.onPredictStart, opts.onPredictEnd);
311
+ const raiseErrors = opts.hooksRaise ?? this.hooksRaise;
312
+ const hooksTimeout = opts.hooksTimeout ?? this.hooksTimeout;
313
+ const timeoutMs = typeof hooksTimeout === "number" ? hooksTimeout * 1000 : null;
314
+ const ctx = new PredictContext({
315
+ states,
316
+ questions: questions,
317
+ agent: this,
318
+ maxLen: opts.maxLen ?? null,
319
+ headMaxLen: opts.headMaxLen ?? null,
320
+ });
321
+ try {
322
+ await dispatchAsync(active, "onPredictStart", ctx, { raiseErrors, timeoutMs });
323
+ if (ctx.results === null) {
324
+ if (!Array.isArray(ctx.states)) {
325
+ throw new TypeError("predictBatch expects an array of states; pass a single state to predict()/systemOne().");
326
+ }
327
+ if (!isPlainDict(ctx.questions)) {
328
+ const typeName = ctx.questions === null
329
+ ? "NoneType"
330
+ : Array.isArray(ctx.questions)
331
+ ? "list"
332
+ : typeof ctx.questions === "object"
333
+ ? (ctx.questions.constructor?.name ?? "object")
334
+ : typeof ctx.questions;
335
+ throw new TypeError(`questions must be a dict of question id -> definition, got ${typeName}`);
336
+ }
337
+ for (const st of ctx.states) {
338
+ if (st === null || st === undefined) {
339
+ throw new TypeError("state must not be None; pass a string, dict, or list");
340
+ }
341
+ }
342
+ const out = await this._systemOneMany(ctx.states, ctx.questions, {
343
+ maxLen: ctx.maxLen,
344
+ headMaxLen: ctx.headMaxLen,
345
+ batchSize: opts.batchSize ?? null,
346
+ lang: opts.lang ?? null,
347
+ });
348
+ ctx.results = out;
349
+ ctx.model ??= out[0]?.model ?? null;
350
+ }
351
+ }
352
+ catch (err) {
353
+ ctx.error = err;
354
+ try {
355
+ await dispatchAsync(active, "onError", ctx, { raiseErrors });
356
+ }
357
+ catch {
358
+ // A failing onError hook must not hide the failure that triggered it.
359
+ }
360
+ throw err;
361
+ }
362
+ finally {
363
+ ctx.markElapsed();
364
+ if (ctx.results !== null) {
365
+ ctx.usage = aggregateUsage(ctx.results);
366
+ if (mc !== null) {
367
+ flagLowConfidence(ctx.results, mc);
368
+ }
369
+ }
370
+ try {
371
+ await dispatchAsync(active, "onPredictEnd", ctx, { raiseErrors, timeoutMs });
372
+ }
373
+ catch (hookErr) {
374
+ // End hooks run on the failure path too; do not let one mask the real error.
375
+ if (ctx.error === null)
376
+ throw hookErr;
377
+ }
378
+ }
379
+ return ctx.results;
380
+ }
381
+ /** Encode one state into one sequence row per question; the state text is tokenized once. */
382
+ _encodeItems(state, ids, internals, maxLen, headMaxLen) {
383
+ // The state text is shared by every question and is usually the longest text in the
384
+ // sequence — encode it once and compose the per-question prefixes onto it.
385
+ const stAll = this.tok.encode(serializeState(state).split(this.tok.maskToken).join(" "));
386
+ const items = [];
387
+ const stats = [];
388
+ for (let qi = 0; qi < ids.length; qi++) {
389
+ const qid = ids[qi];
390
+ const q = internals[qi];
391
+ const prefix = buildQuestionPrefix(this.tok, q, maxLen, headMaxLen);
392
+ const seq = sequenceWithState(prefix, stAll, this.tok.sepId, maxLen, Array.isArray(state));
393
+ if (seq.markers.length !== renderOptions(q).length) {
394
+ throw new Error(`question ${qidStr(qid)} options exceed head_max_len=${headMaxLen}`);
395
+ }
396
+ items.push({ ids: seq.ids, markers: seq.markers, qtype: QTYPES[q.t] });
397
+ stats.push(seq.stats);
398
+ }
399
+ return { items, nTokens: items.reduce((a, it) => a + it.ids.length, 0), stats };
400
+ }
401
+ /**
402
+ * Evaluate one shared question schema over many states. Each chunk of up to `batchSize`
403
+ * states is collated into a single encoder+head forward pass; results align with `states`
404
+ * by index. (Python `Agent.predict_batch` parity; its `sort_by_length` is not ported.)
405
+ */
406
+ async _systemOneMany(states, questions, opts = {}) {
407
+ if (states.length === 0)
408
+ return [];
409
+ const ids = Object.keys(questions ?? {});
410
+ if (ids.length === 0) {
411
+ return states.map(() => ({
412
+ model: "laya-rl-agent",
413
+ answers: {},
414
+ usage: { input_tokens: 0, output_tokens: 0 },
415
+ }));
416
+ }
417
+ const maxLen = opts.maxLen ?? this.maxLen;
418
+ const headMaxLen = opts.headMaxLen ?? this.headMaxLen;
419
+ const internals = ids.map((qid) => {
420
+ checkQuestion(qid, questions[qid]);
421
+ return toInternal(questions[qid]);
422
+ });
423
+ const chunkSize = opts.batchSize && opts.batchSize > 0 ? Math.floor(opts.batchSize) : states.length;
424
+ const out = [];
425
+ for (let start = 0; start < states.length; start += chunkSize) {
426
+ const chunk = states.slice(start, start + chunkSize);
427
+ const built = chunk.map((st) => this._encodeItems(st, ids, internals, maxLen, headMaxLen));
428
+ const collated = collateItems(built.map((b) => b.items), this.tok.padId);
429
+ if (!collated)
430
+ throw new Error("no items to collate");
431
+ const batch = collated;
432
+ const { lastHidden } = await this.provider.runEncoder(batch);
433
+ const { logits, act } = await this.provider.runHead(lastHidden, batch);
434
+ const rows = chunk.length * ids.length;
435
+ if (!Array.isArray(logits) || !Array.isArray(act) || logits.length < rows || act.length < rows) {
436
+ throw new Error("model provider returned fewer output rows than input items");
437
+ }
438
+ for (let s = 0; s < chunk.length; s++) {
439
+ for (let qi = 0; qi < ids.length; qi++) {
440
+ const r = s * ids.length + qi;
441
+ const k = built[s].items[qi].markers.length;
442
+ const logitRow = logits[r];
443
+ const actRow = act[r];
444
+ if (!Array.isArray(logitRow) || logitRow.length < k ||
445
+ !Array.isArray(actRow) || actRow.length === 0 ||
446
+ logitRow.some((v) => !Number.isFinite(v)) || actRow.some((v) => !Number.isFinite(v))) {
447
+ throw new Error(`model provider returned invalid output for question ${ids[qi]}`);
448
+ }
449
+ }
450
+ }
451
+ let row = 0;
452
+ for (let s = 0; s < chunk.length; s++) {
453
+ const answers = {};
454
+ for (let qi = 0; qi < ids.length; qi++) {
455
+ answers[ids[qi]] = this._decodeRow(logits[row], act[row] ?? [1, 0], internals[qi], built[s].items[qi].markers.length, opts.lang ?? null);
456
+ row++;
457
+ }
458
+ // How much of the state actually reached the encoder. Truncation is a token budget, so it
459
+ // moves with maxLen, headMaxLen and each question's rendered head — a caller cannot infer
460
+ // it from the length of the state it sent (issue #174, Python #181 parity).
461
+ const st = built[s].stats;
462
+ const dropped = st.reduce((a, x) => Math.max(a, x.state_tokens_dropped), 0);
463
+ // Only when a question actually lost options to the head budget, as Python's
464
+ // `Agent.predict_batch` does: an answer chosen from 42 distinguishable spans of 58 has a
465
+ // ceiling the caller cannot otherwise see.
466
+ const collapsed = collapsedOptions(ids, st);
467
+ out.push({
468
+ model: "laya-rl-agent",
469
+ answers,
470
+ usage: {
471
+ input_tokens: built[s].nTokens,
472
+ output_tokens: 0,
473
+ state_tokens: st[0]?.state_tokens ?? 0,
474
+ state_tokens_dropped: dropped,
475
+ truncated: dropped > 0,
476
+ truncated_questions: ids.filter((_, qi) => st[qi].truncated),
477
+ ...(Object.keys(collapsed).length ? { options: collapsed } : {}),
478
+ },
479
+ });
480
+ }
481
+ }
482
+ return out;
483
+ }
484
+ /** Decode one head row into the answer for its question. */
485
+ _decodeRow(logitsRow, actRow, q, k, lang = null) {
486
+ const qt = QTYPES[q.t];
487
+ const bucket = tempBucket(qt, k);
488
+ // Python parity (_decode_answers): a matching lang override replaces the scale
489
+ // wholesale — its own temperature_by_options first, then its 3-slot temperature —
490
+ // so an override without buckets intentionally ignores the base per-bucket entries.
491
+ const langCfg = lang ? this.langTemperatures[lang.split("-")[0].toLowerCase()] : undefined;
492
+ const scale = langCfg
493
+ ? (langCfg.temperatureByOptions[bucket] ?? langCfg.temperature[qt] ?? 1.0)
494
+ : (this.temperatureByOptions[bucket] ?? this.temperature[qt] ?? 1.0);
495
+ const z = logitsRow.slice(0, k).map((v) => v / scale);
496
+ const p = softmax(z);
497
+ const actP = softmax(actRow.slice(0, Math.max(2, actRow.length)));
498
+ const ext = { act_probability: r4(actP[0]) };
499
+ // Same quantity on every question type (max(p)), so callers can gate across types on
500
+ // one number; `confidence` stays as-is for existing callers (entropy for choice/score).
501
+ // Histogram-binning recalibration (issue #871, Python parity) recalibrates ans_raw
502
+ // per temp_bucket unless a language override is active.
503
+ const ansRaw = answerConfidence(p);
504
+ const langOverride = Boolean(lang && lang.split("-")[0].toLowerCase() in this.langTemperatures);
505
+ const ansConf = r4(this.binningMap && !langOverride
506
+ ? applyBinningMap(ansRaw, bucket, this.binningMap)
507
+ : ansRaw);
508
+ if (q.t === "choice") {
509
+ const keys = Object.keys(q.crit);
510
+ let best = 0;
511
+ for (let i = 1; i < p.length; i++)
512
+ if (p[i] > p[best])
513
+ best = i;
514
+ return {
515
+ type: "choice",
516
+ choice: keys[best],
517
+ probabilities: Object.fromEntries(keys.map((kk, i) => [kk, r4(p[i] ?? 0)])),
518
+ confidence: r4(confidenceFromProbs(p)),
519
+ answer_confidence: ansConf,
520
+ action: ext,
521
+ };
522
+ }
523
+ if (q.t === "score") {
524
+ const exp = p.reduce((a, v, i) => a + i * v, 0);
525
+ return {
526
+ type: "score",
527
+ score: r4(exp),
528
+ // `renderCriterion`, not the raw `c`: a legend maps an index to the TEXT of a level, and
529
+ // the keys are already strings. A numeric scale written directly used to come back with
530
+ // the caller's own JSON types (`{"0": 1}`), so a client that reads a level as a string
531
+ // had to handle a number, a boolean and null as well -- and `{"0": null}` is not even
532
+ // parseable by a Jev client (#302). Same change as the Python `agent.py` and
533
+ // `onnx_agent.py` legends, so the two runtimes return the same value types.
534
+ legend: Object.fromEntries(q.crit.map((c, i) => [String(i), renderCriterion(c)])),
535
+ probabilities: Object.fromEntries(p.map((v, i) => [String(i), r4(v)])),
536
+ confidence: r4(confidenceFromProbs(p)),
537
+ answer_confidence: ansConf,
538
+ action: ext,
539
+ };
540
+ }
541
+ const pt = p[1] ?? 0;
542
+ return {
543
+ type: "noul",
544
+ noul: r4(pt),
545
+ confidence: r4(Math.max(pt, 1 - pt)),
546
+ // over two options max(p_true, 1 - p_true) is max(p): identical to confidence here
547
+ answer_confidence: ansConf,
548
+ action: ext,
549
+ };
550
+ }
551
+ async predict(state, questions, opts = {}) {
552
+ return this.systemOne(state, questions, opts);
553
+ }
554
+ /**
555
+ * Evaluate the same questions over many states, packing each chunk of up to
556
+ * `opts.batchSize` states into one shared forward pass (Python `Agent.predict_batch`
557
+ * parity). This is the throughput path: `systemOne`/`predict` run one state per forward
558
+ * pass, which leaves most of the batch dimension idle on GPU. Results align with
559
+ * `states` by index and are identical in shape to `systemOne`'s output.
560
+ *
561
+ * `opts.maxLen` / `opts.headMaxLen` override the agent config for this call; a start
562
+ * hook may also set `ctx.maxLen` / `ctx.headMaxLen` or call `ctx.skip(results)`.
563
+ * Python's `sort_by_length` grouping is not ported.
564
+ */
565
+ async predictBatch(states, questions, opts = {}) {
566
+ return this._predictHooked(states, questions, opts);
567
+ }
568
+ async decide(state, schema, opts = {}) {
569
+ return decide(this, state, schema, opts);
570
+ }
571
+ static async load(modelDirOrRepo, opts) {
572
+ const sub = opts?.subfolder ?? null;
573
+ const isBrowser = typeof globalThis.window !== "undefined";
574
+ let cfg = {};
575
+ let tokenizerJson = null;
576
+ let dir = opts?.localDir ?? modelDirOrRepo;
577
+ let revision = null;
578
+ let provider;
579
+ if (isBrowser) {
580
+ const { loadWebBundle, createWebProvider } = await import("./providers.js");
581
+ const bundle = await loadWebBundle(modelDirOrRepo, {
582
+ subfolder: sub,
583
+ revision: opts?.revision,
584
+ expectedSha256: opts?.expectedSha256,
585
+ signal: opts?.signal,
586
+ onProgress: opts?.onProgress,
587
+ });
588
+ cfg = bundle.cfg;
589
+ tokenizerJson = bundle.tokenizerJson;
590
+ dir = bundle.dir;
591
+ revision = bundle.revision;
592
+ provider = await createWebProvider(dir, {
593
+ numThreads: opts?.numThreads,
594
+ expectedSha256: opts?.expectedSha256,
595
+ });
596
+ }
597
+ else {
598
+ const { loadNodeBundle, createNodeProvider } = await import("./providers.js");
599
+ const bundle = await loadNodeBundle(modelDirOrRepo, {
600
+ subfolder: sub,
601
+ localDir: opts?.localDir,
602
+ token: opts?.token,
603
+ revision: opts?.revision,
604
+ expectedSha256: opts?.expectedSha256,
605
+ signal: opts?.signal,
606
+ onProgress: opts?.onProgress,
607
+ });
608
+ cfg = bundle.cfg;
609
+ tokenizerJson = bundle.tokenizerJson;
610
+ dir = bundle.dir;
611
+ revision = bundle.revision;
612
+ provider = await createNodeProvider(dir, {
613
+ device: opts?.device, numThreads: opts?.numThreads, expectedSha256: opts?.expectedSha256,
614
+ });
615
+ }
616
+ if (!tokenizerJson) {
617
+ throw new Error(`Incompatible model: tokenizer.json is missing or invalid in ${JSON.stringify(dir)}`);
618
+ }
619
+ let tok;
620
+ try {
621
+ const parsed = tokenizerFromHF(tokenizerJson);
622
+ if (!parsed)
623
+ throw new Error("unsupported tokenizer.json format");
624
+ tok = parsed;
625
+ }
626
+ catch (error) {
627
+ throw new Error(`Incompatible model: tokenizer.json is missing or invalid in ${JSON.stringify(dir)}: ${String(error)}`);
628
+ }
629
+ return new Agent({ provider, tok, cfg, revision, lang_temperatures: opts?.lang_temperatures });
630
+ }
631
+ }