@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,757 @@
1
+ import { analyse } from "./lang.js";
2
+ import { checkMinConfidence, flagLowConfidence } from "./common.js";
3
+ import { decide } from "./structured.js";
4
+ import { HookRegistry, PredictContext, aggregateUsage, composeHooks, dispatch, markDefaultsRan, dispatchAsync, normaliseHooks, } from "./hooks.js";
5
+ export const BUNDLE_REPO = "convaiinnovations/laya";
6
+ export const DEFAULT_MODELS = {
7
+ english: { repo: BUNDLE_REPO, subfolder: null },
8
+ multilingual: { repo: BUNDLE_REPO, subfolder: "multilingual" },
9
+ "typed-decisions": { repo: BUNDLE_REPO, subfolder: "typed-decisions" },
10
+ };
11
+ export const STANDALONE_MODELS = {
12
+ english: "convaiinnovations/laya",
13
+ multilingual: "convaiinnovations/laya-multilingual",
14
+ "typed-decisions": "convaiinnovations/laya-typed-decisions",
15
+ };
16
+ const ALIASES = {
17
+ en: "english",
18
+ laya: "english",
19
+ default: "english",
20
+ multi: "multilingual",
21
+ ml: "multilingual",
22
+ "laya-multilingual": "multilingual",
23
+ typed: "typed-decisions",
24
+ typed_decisions: "typed-decisions",
25
+ "laya-typed-decisions": "typed-decisions",
26
+ decisions: "typed-decisions",
27
+ };
28
+ export function normaliseName(name) {
29
+ const raw = String(name).trim().toLowerCase();
30
+ const key = ALIASES[raw] ?? raw;
31
+ if (!(key in DEFAULT_MODELS)) {
32
+ throw new Error(`unknown model ${JSON.stringify(name)}; choose one of ${JSON.stringify(Object.keys(DEFAULT_MODELS).sort())} (or an alias: ${JSON.stringify(Object.keys(ALIASES).sort())})`);
33
+ }
34
+ return key;
35
+ }
36
+ const TYPED_DECISION_WORKFLOWS = {
37
+ agent_trace_observability: new Set(["action", "needs_review", "outcome", "risk", "urgency"]),
38
+ customer_service: new Set(["action", "category", "churn_risk", "needs_human", "urgency"]),
39
+ invoice_processing: new Set(["discrepancy_severity", "disposition", "duplicate", "matches_order", "urgency"]),
40
+ security_incidents: new Set(["credential_compromise", "disposition", "severity", "true_positive", "urgency"]),
41
+ };
42
+ export function matchTypedDecisionsWorkflow(questions) {
43
+ const ids = new Set(Object.keys(questions ?? {}));
44
+ for (const [wf, sig] of Object.entries(TYPED_DECISION_WORKFLOWS)) {
45
+ if (sig.size === ids.size && [...sig].every((id) => ids.has(id)))
46
+ return wf;
47
+ }
48
+ return null;
49
+ }
50
+ const ENGLISH_SUBTAGS = new Set(["en", "eng", "english"]);
51
+ // Valid `$LANG` values that name no language, so they answer nothing about the state: `C`,
52
+ // `POSIX` and `C.UTF-8` (the official Python image's default), plus the ISO 639-2 special codes
53
+ // `und` (undetermined), `zxx` (no linguistic content) and `mul` (multiple). They abstain like a
54
+ // blank code instead of forcing the multilingual checkpoint on English text (Python parity).
55
+ const LANGUAGE_AGNOSTIC_CODES = new Set(["c", "posix", "und", "zxx", "mul"]);
56
+ export function englishFromCode(value) {
57
+ if (value === null || value === undefined)
58
+ return null;
59
+ let code = String(value).trim().toLowerCase();
60
+ if (!code)
61
+ return null;
62
+ code = code.split(".", 1)[0]; // en_US.UTF-8 -> en_US
63
+ const primary = code.replace(/_/g, "-").split("-", 1)[0]; // en_US -> en
64
+ if (!primary || LANGUAGE_AGNOSTIC_CODES.has(primary))
65
+ return null;
66
+ return ENGLISH_SUBTAGS.has(primary);
67
+ }
68
+ /** Parity alias for the Python `_english_from_code` name. */
69
+ export const _englishFromCode = englishFromCode;
70
+ function questionSchema(questions) {
71
+ // Python groups on json.dumps(sort_keys=False, default=str): insertion order is significant
72
+ // at every nesting level because options are positional in the rendered sequence, so two
73
+ // equal schemas with different key orders must not share a forward pass. JSON.stringify
74
+ // preserves insertion order for string keys; the replacer stands in for default=str on
75
+ // the few value types JSON cannot represent.
76
+ return JSON.stringify(questions, (_key, value) => typeof value === "function" || typeof value === "symbol" || typeof value === "bigint"
77
+ ? String(value)
78
+ : value);
79
+ }
80
+ /** Turn `LAYA_SHA256_DIGESTS` into per-checkpoint digest maps when it names models. */
81
+ export function digestsFromEnv(models) {
82
+ if (typeof process === "undefined" || !process.env)
83
+ return {};
84
+ const raw = (process.env["LAYA_SHA256_DIGESTS"] ?? "").trim();
85
+ if (!raw)
86
+ return {};
87
+ let data;
88
+ try {
89
+ data = JSON.parse(raw);
90
+ }
91
+ catch {
92
+ return {};
93
+ }
94
+ if (typeof data !== "object" || data === null || Array.isArray(data))
95
+ return {};
96
+ const entries = Object.entries(data);
97
+ if (entries.length === 0)
98
+ return {};
99
+ const values = entries.map(([, v]) => v);
100
+ if (values.every((v) => typeof v === "string")) {
101
+ return {}; // flat: providers already applies it
102
+ }
103
+ if (!values.every((v) => typeof v === "object" && v !== null && !Array.isArray(v))) {
104
+ throw new Error(`LAYA_SHA256_DIGESTS must be either {artifact: digest} for every checkpoint or {model: {artifact: digest}} per checkpoint; ${JSON.stringify(Object.keys(data).sort())} mixes the two or holds a value that is neither`);
105
+ }
106
+ const perModel = {};
107
+ for (const [k, v] of entries) {
108
+ perModel[normaliseName(k)] = v;
109
+ }
110
+ for (const name of Object.keys(models)) {
111
+ const norm = normaliseName(name);
112
+ if (!(norm in perModel)) {
113
+ perModel[norm] = {};
114
+ }
115
+ }
116
+ return perModel;
117
+ }
118
+ export const _digestsFromEnv = digestsFromEnv;
119
+ export const _digests_from_env = digestsFromEnv;
120
+ function toSpec(spec) {
121
+ if (typeof spec === "string")
122
+ return { repo: spec, subfolder: null };
123
+ if (Array.isArray(spec)) {
124
+ const [repo, sub] = [...spec, null].slice(0, 2);
125
+ return { repo, subfolder: sub ?? null };
126
+ }
127
+ return { repo: spec.repo, subfolder: spec.subfolder ?? null };
128
+ }
129
+ function repoStr(spec) {
130
+ return spec.subfolder ? `${spec.repo}/${spec.subfolder}` : spec.repo;
131
+ }
132
+ export class Router extends HookRegistry {
133
+ hooksRaise;
134
+ models;
135
+ device;
136
+ token;
137
+ revision;
138
+ revisions;
139
+ sha256Digests;
140
+ get sha256_digests() {
141
+ return this.sha256Digests;
142
+ }
143
+ maxLoaded;
144
+ default;
145
+ autoTaskDetection;
146
+ langGuess;
147
+ loader;
148
+ _agents = new Map();
149
+ _order = []; // least-recently-used first
150
+ _loading = new Map();
151
+ constructor(opts = {}) {
152
+ super();
153
+ // Hooks are opt-in; an unset hook list is a no-op. Router-level onPredictStart /
154
+ // onPredictEnd hooks wrap the whole route+infer call and see ctx.decision; see hooks.ts.
155
+ this.hooks = normaliseHooks(opts.hooks, opts.onPredictStart, opts.onPredictEnd);
156
+ this.hooksRaise = opts.hooksRaise ?? true;
157
+ const base = opts.standaloneRepos ?? opts.standalone_repos
158
+ ? { ...STANDALONE_MODELS }
159
+ : Object.fromEntries(Object.entries(DEFAULT_MODELS).map(([k, v]) => [k, { ...v }]));
160
+ this.models = Object.fromEntries(Object.entries(base).map(([k, v]) => [k, toSpec(v)]));
161
+ if (opts.models) {
162
+ for (const [k, v] of Object.entries(opts.models)) {
163
+ this.models[normaliseName(k)] = toSpec(v);
164
+ }
165
+ }
166
+ this.device = opts.device ?? null;
167
+ this.token = opts.token ?? (typeof process !== "undefined" ? process.env?.["HF_TOKEN"] : undefined);
168
+ // Optional hub revision applied to every checkpoint load. Per-model overrides support
169
+ // standalone repositories whose reviewed commits differ.
170
+ this.revision = opts.revision ?? null;
171
+ this.revisions = Object.fromEntries(Object.entries(opts.revisions ?? {}).map(([name, value]) => [normaliseName(name), value]));
172
+ // Per checkpoint SHA-256 map: seeded from a model-named LAYA_SHA256_DIGESTS, then
173
+ // overridden checkpoint by checkpoint by the argument. Keyed and normalised exactly like
174
+ // revisions, so a misspelled model name fails here rather than leaving that checkpoint
175
+ // unverified.
176
+ this.sha256Digests = digestsFromEnv(this.models);
177
+ const rawDigests = opts.sha256Digests ?? opts.sha256_digests;
178
+ if (rawDigests) {
179
+ for (const [name, val] of Object.entries(rawDigests)) {
180
+ this.sha256Digests[normaliseName(name)] = val;
181
+ }
182
+ }
183
+ this.maxLoaded = Math.max(1, Math.trunc(Number(opts.maxLoaded ?? opts.max_loaded ?? 2)));
184
+ this.default = normaliseName(opts.default ?? "multilingual");
185
+ this.autoTaskDetection = Boolean(opts.autoTaskDetection ?? opts.auto_task_detection ?? false);
186
+ this.langGuess = opts.langGuess ?? opts.lang_guess ?? null;
187
+ this.loader = opts.loader ?? null;
188
+ if (opts.preload === true) {
189
+ void this.preload();
190
+ }
191
+ else if (Array.isArray(opts.preload)) {
192
+ void this.preload(opts.preload);
193
+ }
194
+ }
195
+ async load(name) {
196
+ const key = normaliseName(name);
197
+ if (this._agents.has(key)) {
198
+ this._touch(key);
199
+ return this._agents.get(key);
200
+ }
201
+ const loading = this._loading.get(key);
202
+ if (loading)
203
+ return loading;
204
+ // Start in a microtask so even a synchronous loader sees its in-flight entry.
205
+ const pending = Promise.resolve().then(async () => {
206
+ let agent;
207
+ if (this.loader) {
208
+ agent = await this.loader(key, this.models[key]);
209
+ }
210
+ else {
211
+ const { Agent } = await import("./agent.js");
212
+ const spec = this.models[key];
213
+ const revision = Object.prototype.hasOwnProperty.call(this.revisions, key)
214
+ ? this.revisions[key]
215
+ : this.revision;
216
+ const opts = {
217
+ subfolder: spec.subfolder,
218
+ device: this.device ?? undefined,
219
+ token: this.token ?? undefined,
220
+ };
221
+ if (revision)
222
+ opts.revision = revision;
223
+ if (Object.prototype.hasOwnProperty.call(this.sha256Digests, key)) {
224
+ opts.expectedSha256 = this.sha256Digests[key] ?? {};
225
+ }
226
+ agent = await Agent.load(spec.repo, opts);
227
+ }
228
+ this._agents.set(key, agent);
229
+ this._order.push(key);
230
+ const evicted = this._evict();
231
+ // Lifecycle hooks fire after the maps settle, so a hook can safely call the Router.
232
+ for (const victim of evicted) {
233
+ await dispatchAsync(composeHooks(this.hooks), "onEvict", new PredictContext({ states: [], questions: {}, model: victim, router: this }), { raiseErrors: this.hooksRaise });
234
+ }
235
+ await dispatchAsync(composeHooks(this.hooks), "onLoad", new PredictContext({ states: [], questions: {}, model: key, agent, router: this }), { raiseErrors: this.hooksRaise });
236
+ return agent;
237
+ });
238
+ this._loading.set(key, pending);
239
+ try {
240
+ return await pending;
241
+ }
242
+ finally {
243
+ this._loading.delete(key);
244
+ }
245
+ }
246
+ _touch(key) {
247
+ const i = this._order.indexOf(key);
248
+ if (i !== -1)
249
+ this._order.splice(i, 1);
250
+ this._order.push(key);
251
+ }
252
+ /** Drop least-recently-used agents until `maxLoaded` holds. Returns evicted names. */
253
+ _evict() {
254
+ const evicted = [];
255
+ while (this._order.length > this.maxLoaded) {
256
+ const victim = this._order.shift();
257
+ if (this._agents.delete(victim))
258
+ evicted.push(victim);
259
+ }
260
+ // Keep the two views consistent.
261
+ if (this._order.length < this._agents.size) {
262
+ for (const k of [...this._agents.keys()]) {
263
+ if (!this._order.includes(k)) {
264
+ this._agents.delete(k);
265
+ evicted.push(k);
266
+ }
267
+ }
268
+ }
269
+ return evicted;
270
+ }
271
+ attach(name, agent) {
272
+ const key = normaliseName(name);
273
+ this._agents.set(key, agent);
274
+ this._touch(key);
275
+ this.maxLoaded = Math.max(this.maxLoaded, this._agents.size);
276
+ return agent;
277
+ }
278
+ async preload(names) {
279
+ const keys = (names ?? Object.keys(this.models)).map((n) => normaliseName(n));
280
+ this.maxLoaded = Math.max(this.maxLoaded, new Set([...keys, ...this._agents.keys()]).size);
281
+ for (const n of keys) {
282
+ if (!this._agents.has(n))
283
+ await this.load(n);
284
+ }
285
+ return this;
286
+ }
287
+ unload(name) {
288
+ if (name === null || name === undefined) {
289
+ this._agents.clear();
290
+ this._order = [];
291
+ }
292
+ else {
293
+ const key = normaliseName(name);
294
+ this._agents.delete(key);
295
+ const i = this._order.indexOf(key);
296
+ if (i !== -1)
297
+ this._order.splice(i, 1);
298
+ }
299
+ }
300
+ get loaded() {
301
+ return [...this._order];
302
+ }
303
+ _resolveHint(hint, state) {
304
+ if (hint === null || hint === undefined)
305
+ return null;
306
+ const value = typeof hint === "function" ? hint(state) : hint;
307
+ return englishFromCode(value);
308
+ }
309
+ /**
310
+ * Decide which checkpoint to use, then let `onRoute` hooks observe or replace the decision.
311
+ *
312
+ * `ctx.decision` is the RouteDecision; a hook may replace it (for example to pin a
313
+ * checkpoint) and the replacement is what gets returned and used. `opts.hooks` are
314
+ * per-call hooks, appended after any installed on the Router.
315
+ */
316
+ route(state, questions = null, opts = {}) {
317
+ const decision = this._route(state, questions, opts);
318
+ const raiseErrors = opts.hooksRaise ?? this.hooksRaise;
319
+ const active = composeHooks(this.hooks, opts.hooks);
320
+ const ctx = new PredictContext({
321
+ states: [state],
322
+ questions: (questions ?? {}),
323
+ decision: decision,
324
+ router: this,
325
+ });
326
+ dispatch(active, "onRoute", ctx, { raiseErrors });
327
+ return ctx.decision;
328
+ }
329
+ /** Decide which checkpoint to use, without loading, running, or hooking anything. */
330
+ _route(state, questions = null, opts = {}) {
331
+ const { model = null, task = null, lang = null } = opts;
332
+ const langGuessOpt = opts.langGuess ?? opts.lang_guess ?? null;
333
+ if (model !== null && model !== undefined) {
334
+ const key = normaliseName(model);
335
+ return {
336
+ model: key,
337
+ repo: repoStr(this.models[key]),
338
+ reason: `explicit model=${JSON.stringify(model)}`,
339
+ detection: null,
340
+ workflow: null,
341
+ };
342
+ }
343
+ if (task !== null && task !== undefined) {
344
+ const key = normaliseName(task);
345
+ return {
346
+ model: key,
347
+ repo: repoStr(this.models[key]),
348
+ reason: `explicit task=${JSON.stringify(task)}`,
349
+ detection: null,
350
+ workflow: null,
351
+ };
352
+ }
353
+ const workflow = matchTypedDecisionsWorkflow(questions ?? {});
354
+ if (workflow && this.autoTaskDetection) {
355
+ return {
356
+ model: "typed-decisions",
357
+ repo: repoStr(this.models["typed-decisions"]),
358
+ reason: `question ids match the ${JSON.stringify(workflow)} typed-decisions workflow`,
359
+ detection: null,
360
+ workflow,
361
+ };
362
+ }
363
+ // An explicit `lang` is decisive only when the code names a language. Blank or whitespace
364
+ // resolves to no usable hint, so it falls through to langGuess/detection exactly as an
365
+ // abstaining hint does (Python parity); real English/non-English codes still route now.
366
+ const resolvedLang = englishFromCode(lang);
367
+ if (resolvedLang !== null) {
368
+ const key = resolvedLang ? "english" : "multilingual";
369
+ return {
370
+ model: key,
371
+ repo: repoStr(this.models[key]),
372
+ reason: `explicit lang=${JSON.stringify(lang)}`,
373
+ detection: null,
374
+ workflow,
375
+ };
376
+ }
377
+ const hints = [
378
+ ["lang_guess", langGuessOpt],
379
+ ["Router(lang_guess=...)", this.langGuess],
380
+ ];
381
+ for (const [source, hint] of hints) {
382
+ const resolved = this._resolveHint(hint, state);
383
+ if (resolved !== null && resolved !== undefined) {
384
+ const key = resolved ? "english" : "multilingual";
385
+ return {
386
+ model: key,
387
+ repo: repoStr(this.models[key]),
388
+ reason: `${source}: the caller identified this as ${resolved ? "English" : "non-English"} text`,
389
+ detection: null,
390
+ workflow,
391
+ };
392
+ }
393
+ }
394
+ const det = analyse(state);
395
+ let key;
396
+ let reason;
397
+ if (det.script === "unknown") {
398
+ key = this.default;
399
+ reason = `no letters detected in state; using default (${key})`;
400
+ }
401
+ else if (det.script !== "latin") {
402
+ key = "multilingual";
403
+ reason =
404
+ `non-Latin script (${det.script}, ${Math.round(100 * det.nonLatinFraction)}% of letters); ` +
405
+ "the English checkpoint cannot read it";
406
+ }
407
+ else if (!det.isEnglish) {
408
+ key = "multilingual";
409
+ if (det.mixedSegment) {
410
+ reason =
411
+ `Latin script, mostly English, but a line or field reads as ${JSON.stringify(det.language)} ` +
412
+ `(${JSON.stringify(det.mixedSegment.slice(0, 60))}); the English checkpoint cannot read it`;
413
+ }
414
+ else if (det.language) {
415
+ reason = `Latin script but language looks like ${JSON.stringify(det.language)}, not English`;
416
+ }
417
+ else {
418
+ reason =
419
+ `Latin script, language not identified but ${Math.round(100 * det.diacriticRate)}% ` +
420
+ "non-English letters; not safe for the English checkpoint";
421
+ }
422
+ }
423
+ else if (det.languageUndecided) {
424
+ key = this.default;
425
+ reason = `Latin script, language not identified and no non-English letters; using default (${key})`;
426
+ }
427
+ else {
428
+ key = "english";
429
+ reason = "English Latin text";
430
+ }
431
+ return { model: key, repo: repoStr(this.models[key]), reason, detection: det, workflow };
432
+ }
433
+ /**
434
+ * Route, then answer every question in one forward pass on the chosen checkpoint.
435
+ *
436
+ * The result is the usual systemOne payload plus a `routing` key recording the decision.
437
+ * Router-level `onPredictStart` / `onPredictEnd` hooks wrap the whole route+infer call and
438
+ * see `ctx.decision`; see hooks.ts.
439
+ */
440
+ async predict(state, questions, opts = {}) {
441
+ const mcOpt = opts.minConfidence ?? opts.min_confidence;
442
+ const mc = mcOpt !== undefined && mcOpt !== null ? checkMinConfidence(mcOpt) : null;
443
+ const active = composeHooks(this.hooks, opts.hooks, opts.onPredictStart, opts.onPredictEnd);
444
+ const raiseErrors = opts.hooksRaise ?? this.hooksRaise;
445
+ // Per-call hooks apply to the whole call, including onRoute inside route().
446
+ const decision = this.route(state, questions, opts);
447
+ const agent = (await this.load(decision.model));
448
+ const ctx = new PredictContext({
449
+ states: [state],
450
+ questions: questions,
451
+ decision: { ...decision },
452
+ model: decision.model,
453
+ agent,
454
+ router: this,
455
+ });
456
+ try {
457
+ await dispatchAsync(active, "onPredictStart", ctx, { raiseErrors });
458
+ if (ctx.results === null) {
459
+ // Python parity (router.py predict): the request's language also shapes the answer
460
+ // distribution through the agent's lang_temperatures. An explicit lang wins;
461
+ // otherwise forward the language the router detected for the routing decision.
462
+ // TS analyse() names English "en" where Python's analyse returns None (it only
463
+ // ever names non-English), so a detected "en" forwards as null — in Python only an
464
+ // explicit lang="en" can select an "en" override.
465
+ const detected = decision.detection?.language;
466
+ const effectiveLang = opts.lang ?? (detected && detected !== "en" ? detected : null);
467
+ const agentOpts = { lang: effectiveLang };
468
+ if (mc !== null)
469
+ agentOpts.minConfidence = mc;
470
+ markDefaultsRan(agentOpts);
471
+ const result = (await agent.systemOne(ctx.states[0], ctx.questions, agentOpts));
472
+ result["routing"] = { ...decision };
473
+ ctx.results = [result];
474
+ }
475
+ else {
476
+ // A cache hit short-circuits inference, but predict still promises a `routing` key.
477
+ // Add it without overwriting a routing the cached payload already has.
478
+ for (const result of ctx.results) {
479
+ if (result && typeof result === "object" && !("routing" in result)) {
480
+ result.routing = { ...decision };
481
+ }
482
+ }
483
+ }
484
+ }
485
+ catch (err) {
486
+ ctx.error = err;
487
+ try {
488
+ await dispatchAsync(active, "onError", ctx, { raiseErrors });
489
+ }
490
+ catch {
491
+ // A failing onError hook must not hide the failure that triggered it.
492
+ }
493
+ throw err;
494
+ }
495
+ finally {
496
+ ctx.markElapsed();
497
+ if (ctx.results !== null) {
498
+ ctx.usage = aggregateUsage(ctx.results);
499
+ if (mc !== null) {
500
+ flagLowConfidence(ctx.results, mc);
501
+ }
502
+ }
503
+ try {
504
+ await dispatchAsync(active, "onPredictEnd", ctx, { raiseErrors });
505
+ }
506
+ catch (hookErr) {
507
+ // End hooks run on the failure path too; do not let one mask the real error.
508
+ if (ctx.error === null)
509
+ throw hookErr;
510
+ }
511
+ }
512
+ return ctx.results[0];
513
+ }
514
+ async decide(state, schema, opts = {}) {
515
+ return decide(this, state, schema, opts);
516
+ }
517
+ async systemOne(state, questions, opts = {}) {
518
+ return this.predict(state, questions, opts);
519
+ }
520
+ /**
521
+ * Route many requests in one call (Python `Router.route_batch` parity). Every request is
522
+ * validated before anything loads, so a malformed batch fails fast. Entries keep input
523
+ * order; routing is deterministic, so repeated batches route identically.
524
+ */
525
+ routeBatch(requests, opts = {}) {
526
+ if (!Array.isArray(requests)) {
527
+ throw new TypeError("requests must be an array of request objects");
528
+ }
529
+ const decisions = [];
530
+ for (let i = 0; i < requests.length; i++) {
531
+ const request = requests[i];
532
+ if (typeof request !== "object" || request === null || Array.isArray(request)) {
533
+ const got = Array.isArray(request) ? "list" : request === null ? "null" : typeof request;
534
+ throw new TypeError(`request ${i} must be an object, got ${got}`);
535
+ }
536
+ if (!("state" in request)) {
537
+ throw new Error(`request ${i} is missing required key 'state'`);
538
+ }
539
+ if (request.state === null || request.state === undefined) {
540
+ throw new TypeError(`request ${i} 'state' must not be None; pass a string, dict, or list`);
541
+ }
542
+ if (!("questions" in request)) {
543
+ throw new Error(`request ${i} is missing required key 'questions'`);
544
+ }
545
+ const questions = request.questions;
546
+ if (typeof questions !== "object" || questions === null || Array.isArray(questions)) {
547
+ const got = Array.isArray(questions) ? "list" : questions === null ? "null" : typeof questions;
548
+ throw new TypeError(`request ${i} 'questions' must be an object, got ${got}`);
549
+ }
550
+ decisions.push(this.route(request.state, questions, {
551
+ model: request.model ?? null,
552
+ task: request.task ?? null,
553
+ lang: request.lang ?? null,
554
+ langGuess: request.langGuess ?? request.lang_guess ?? null,
555
+ hooks: opts.hooks,
556
+ hooksRaise: opts.hooksRaise,
557
+ }));
558
+ }
559
+ return decisions;
560
+ }
561
+ /**
562
+ * Route and run many requests in one call (Python `Router.predict_batch` parity).
563
+ * Requests are routed first, then grouped by checkpoint so each loaded Agent scores its
564
+ * requests in as few forward passes as possible; results are restored to input order.
565
+ * Requests routed to the same checkpoint still split into separate `predictBatch` calls
566
+ * when their question schemas differ (order-sensitively), when per-request start hooks
567
+ * set different maxLen/headMaxLen overrides, or — for an agent carrying
568
+ * `lang_temperatures` — when their languages differ: each request's effective language
569
+ * (an explicit `lang`, otherwise the detected non-English one) is forwarded so the
570
+ * batched path scores exactly like `predict`.
571
+ *
572
+ * Router-level predict hooks run per request: each request gets its own PredictContext
573
+ * carrying `decision`; `onPredictStart` may rewrite a request or `ctx.skip()` it, and
574
+ * `onPredictEnd` runs once per started request even when the batch fails.
575
+ * `opts.hooks`, `opts.onPredictStart` and `opts.onPredictEnd` are composed the way `predict`
576
+ * composes them: `setDefaultHooks` defaults, then installed hooks, then this call's hooks.
577
+ * `null` and `[]` add nothing. `hooks`
578
+ * also run `onRoute`. `opts.hooksRaise` overrides the Router's policy for this call, the way
579
+ * `predict` uses `opts.hooksRaise ?? this.hooksRaise`.
580
+ */
581
+ async predictBatch(requests, batchSize = null, opts = {}) {
582
+ const decisions = this.routeBatch(requests, opts);
583
+ if (decisions.length === 0)
584
+ return [];
585
+ const groups = new Map();
586
+ for (let i = 0; i < decisions.length; i++) {
587
+ const model = decisions[i].model;
588
+ const bucket = groups.get(model);
589
+ if (bucket)
590
+ bucket.push(i);
591
+ else
592
+ groups.set(model, [i]);
593
+ }
594
+ const results = new Array(requests.length).fill(null);
595
+ // `composeHooks`, not `this.hooks`: `setDefaultHooks` defaults, then installed hooks,
596
+ // then per-call `opts.hooks`, then `opts.onPredictStart` / `opts.onPredictEnd`. The instance
597
+ // list alone would drop every default `predict` keeps. `routeBatch` has already validated
598
+ // `opts.hooks`; start and end are validated here, after routing and before a checkpoint loads.
599
+ const active = composeHooks(this.hooks, opts.hooks, opts.onPredictStart, opts.onPredictEnd);
600
+ const raiseErrors = opts.hooksRaise ?? this.hooksRaise;
601
+ for (const [modelName, indices] of groups) {
602
+ const agent = (await this.load(modelName));
603
+ const started = [];
604
+ try {
605
+ for (const i of indices) {
606
+ const ctx = new PredictContext({
607
+ states: [requests[i].state],
608
+ questions: requests[i].questions,
609
+ decision: { ...decisions[i] },
610
+ model: modelName,
611
+ agent,
612
+ router: this,
613
+ });
614
+ started.push(ctx);
615
+ dispatch(active, "onPredictStart", ctx, { raiseErrors });
616
+ }
617
+ // Order-sensitive at every nesting level (#166): options are positional, so two
618
+ // equal schemas with different key orders must not share a group.
619
+ //
620
+ // Python parity (router.py predict_batch): `predict` forwards the request's language so
621
+ // the agent can apply its per-language temperatures; the batched path forwarded only the
622
+ // token budgets, so the same request scored differently depending on the entry point.
623
+ // Only computed for an agent that actually carries overrides: `lang` is otherwise
624
+ // unused, and adding it to the group key would split a group that shares one forward
625
+ // pass today.
626
+ const hasLangOverrides = Object.keys(agent.langTemperatures ?? {}).length > 0;
627
+ const questionGroups = [];
628
+ for (let s = 0; s < indices.length; s++) {
629
+ const i = indices[s];
630
+ const ctx = started[s];
631
+ if (ctx.results !== null) {
632
+ // A cache hit short-circuits inference, but predict still promises a `routing`
633
+ // key. Add it without overwriting a routing the cached payload already has.
634
+ for (const result of ctx.results) {
635
+ if (result && typeof result === "object" && !("routing" in result)) {
636
+ result.routing = { ...decisions[i] };
637
+ }
638
+ }
639
+ continue;
640
+ }
641
+ // An explicit `lang` wins; otherwise forward the language the router detected for the
642
+ // routing decision. TS analyse() names English "en" where Python's returns None (it
643
+ // only ever names non-English), so a detected "en" forwards as null — in Python only
644
+ // an explicit lang="en" can select an "en" override. Same rule as `predict`.
645
+ const detectedLang = decisions[i].detection?.language ?? null;
646
+ const effectiveLang = requests[i].lang ?? (detectedLang && detectedLang !== "en" ? detectedLang : null);
647
+ const langKey = hasLangOverrides ? effectiveLang : null;
648
+ const schema = questionSchema(ctx.questions);
649
+ const found = questionGroups.find((g) => g.schema === schema &&
650
+ g.maxLen === ctx.maxLen &&
651
+ g.headMaxLen === ctx.headMaxLen &&
652
+ g.lang === langKey);
653
+ if (found)
654
+ found.items.push([i, ctx]);
655
+ else {
656
+ questionGroups.push({
657
+ questions: ctx.questions,
658
+ schema,
659
+ maxLen: ctx.maxLen,
660
+ headMaxLen: ctx.headMaxLen,
661
+ lang: langKey,
662
+ items: [[i, ctx]],
663
+ });
664
+ }
665
+ }
666
+ for (const group of questionGroups) {
667
+ const agentOpts = { batchSize };
668
+ // Only pass overrides when set, so an Agent-like object that does not accept
669
+ // them still works.
670
+ if (group.maxLen !== null)
671
+ agentOpts.maxLen = group.maxLen;
672
+ if (group.headMaxLen !== null)
673
+ agentOpts.headMaxLen = group.headMaxLen;
674
+ if (group.lang !== null)
675
+ agentOpts.lang = group.lang;
676
+ let batchResults;
677
+ if (typeof agent.predictBatch === "function") {
678
+ batchResults = await agent.predictBatch(group.items.map(([, ctx]) => ctx.states[0]), group.questions, agentOpts);
679
+ }
680
+ else {
681
+ // Agent-like objects that only implement systemOne (light wrappers, tests)
682
+ // still work; their states simply share no forward pass.
683
+ batchResults = [];
684
+ for (const [, ctx] of group.items) {
685
+ batchResults.push(await agent.systemOne(ctx.states[0], group.questions, group.lang === null ? undefined : { lang: group.lang }));
686
+ }
687
+ }
688
+ if (batchResults.length !== group.items.length) {
689
+ throw new Error(`internal error: Agent.predictBatch returned ${batchResults.length} results for ${group.items.length} states`);
690
+ }
691
+ for (let s = 0; s < group.items.length; s++) {
692
+ const [i, ctx] = group.items[s];
693
+ const result = batchResults[s];
694
+ result.routing = { ...decisions[i] };
695
+ ctx.results = [result];
696
+ }
697
+ }
698
+ }
699
+ catch (err) {
700
+ for (const ctx of started) {
701
+ if (ctx.results === null) {
702
+ ctx.error = err;
703
+ try {
704
+ dispatch(active, "onError", ctx, { raiseErrors });
705
+ }
706
+ catch {
707
+ // Chained onto the batch failure, which is the one that propagates.
708
+ }
709
+ }
710
+ }
711
+ try {
712
+ this._endContexts(active, started, raiseErrors);
713
+ }
714
+ catch {
715
+ // A failing end hook is chained onto the batch failure, not raised instead.
716
+ }
717
+ throw err;
718
+ }
719
+ this._endContexts(active, started, raiseErrors);
720
+ for (let s = 0; s < indices.length; s++) {
721
+ results[indices[s]] = started[s].results[0];
722
+ }
723
+ }
724
+ if (results.some((r) => r === null)) {
725
+ throw new Error("internal error: batch execution did not produce every result");
726
+ }
727
+ return results;
728
+ }
729
+ /** Alias of predictBatch, mirroring Python's `Router.predict_many`. */
730
+ async predictMany(requests, batchSize = null, opts = {}) {
731
+ return this.predictBatch(requests, batchSize, opts);
732
+ }
733
+ /**
734
+ * Run onPredictEnd for every started per-request context and raise the first hook
735
+ * failure, if any. Elapsed and usage are stamped on every context before any end hook
736
+ * runs, so one request's end hooks never inflate another request's elapsed time.
737
+ */
738
+ _endContexts(active, contexts, raiseErrors) {
739
+ for (const ctx of contexts) {
740
+ ctx.markElapsed();
741
+ if (ctx.results !== null)
742
+ ctx.usage = aggregateUsage(ctx.results);
743
+ }
744
+ let firstError = null;
745
+ for (const ctx of contexts) {
746
+ try {
747
+ dispatch(active, "onPredictEnd", ctx, { raiseErrors });
748
+ }
749
+ catch (hookErr) {
750
+ if (ctx.error === null && firstError === null)
751
+ firstError = hookErr;
752
+ }
753
+ }
754
+ if (firstError !== null)
755
+ throw firstError;
756
+ }
757
+ }