@try-works/extension-laya 0.0.0-stage → 1.0.1

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,167 @@
1
+ import type { TokenizerLike } from "./tokenizer.js";
2
+ export type QType = "choice" | "score" | "noul";
3
+ export interface InternalQ {
4
+ t: QType;
5
+ ins: string;
6
+ crit: unknown;
7
+ labels?: {
8
+ false: string;
9
+ true: string;
10
+ };
11
+ }
12
+ export declare function serializeState(state: unknown): string;
13
+ /** The text of a criterion: the string itself, else the JSON the model was shown.
14
+ *
15
+ * Exported because `agent.ts` needs it for a `score` answer's `legend`, which maps an index to the
16
+ * text of that level. Putting the raw value in made the response's JSON types depend on the
17
+ * caller's input -- a numeric scale came back as `{"0": 1}`, a boolean as `{"0": true}` and a null
18
+ * as `{"0": null}`, which a Jev client refuses to parse (#302).
19
+ */
20
+ export declare function renderCriterion(v: unknown): string;
21
+ export declare function renderOptions(q: InternalQ): string[];
22
+ export interface OptionStats {
23
+ /** Options the question defines, not the markers that survived the sequence clamp. */
24
+ total: number;
25
+ /** How many of them still have a token span of their own. */
26
+ distinct: number;
27
+ /** The per-option cap the head budget forced, or null when none was applied. */
28
+ tokens_per_option: number | null;
29
+ }
30
+ export interface QuestionPrefix {
31
+ /** [CLS] head [SEP] options [SEP] — the state-independent part of the sequence. */
32
+ ids: number[];
33
+ /** Mask-marker positions (absolute; the prefix sits at the start of the final sequence). */
34
+ markers: number[];
35
+ nOptions: number;
36
+ optionStats: OptionStats;
37
+ }
38
+ export declare function buildQuestionPrefix(tok: TokenizerLike, q: InternalQ, maxLen?: number, headMaxLen?: number, optionOrder?: number[]): QuestionPrefix;
39
+ export interface SequenceStats {
40
+ /** Encoded length of the full state, before the window clamp. */
41
+ state_tokens: number;
42
+ /** State tokens that actually reached the encoder after the final maxLen clamp. */
43
+ state_tokens_used: number;
44
+ /** State tokens dropped by the clamp: state_tokens - state_tokens_used. */
45
+ state_tokens_dropped: number;
46
+ /** True when the clamp dropped any state token. */
47
+ truncated: boolean;
48
+ /** What the head budget did to this question's options (Python `build_sequence`'s other stats). */
49
+ options: OptionStats;
50
+ }
51
+ /** Append pre-encoded state tokens to a question prefix. Identical output to building the
52
+ * whole sequence in one pass, but the state only needs encoding once per state, not once
53
+ * per (state, question) pair.
54
+ *
55
+ * The state is clamped to whatever room the head leaves; `stats` reports that clamp so callers
56
+ * never have to guess it from the character length of what they sent (issue #174, Python #181). */
57
+ export declare function sequenceWithState(prefix: QuestionPrefix, stateIds: number[], sepId: number, maxLen?: number, truncateLeft?: boolean): {
58
+ ids: number[];
59
+ markers: number[];
60
+ stats: SequenceStats;
61
+ };
62
+ /** The questions whose options no longer have a token span each, keyed by question id.
63
+ *
64
+ * `total` is what the question defines, not the number of markers that reached the sequence, so a
65
+ * report cannot say "43 of 43" about a question whose 28 missing options never entered the input
66
+ * at all. Mirrors Python `laya.common.collapsed_options`; empty when nothing collapsed, which is
67
+ * the overwhelming majority of requests, so the agents add the key only when it says something. */
68
+ export declare function collapsedOptions(qids: string[], stats: (SequenceStats | undefined)[]): Record<string, OptionStats>;
69
+ export declare function buildSequence(tok: TokenizerLike, state: unknown, q: InternalQ, maxLen?: number, headMaxLen?: number, optionOrder?: number[], truncateLeft?: boolean): {
70
+ ids: number[];
71
+ markers: number[];
72
+ stats: SequenceStats;
73
+ };
74
+ export declare function softmax(z: number[]): number[];
75
+ export declare function confidenceFromProbs(p: number[]): number;
76
+ export declare function answerConfidence(p: number[]): number;
77
+ /** The option types and option-count sizes `optionBucket`/`tempBucket` can produce. The bucket
78
+ * type and the runtime `BUCKET_KEY` check below are both derived from these, so what the type
79
+ * accepts cannot drift from the keys the runtime produces. */
80
+ declare const BUCKET_TYPES: readonly ["choice", "score", "noul"];
81
+ declare const BUCKET_SIZES: readonly ["2", "3-5", "6-10", "11+"];
82
+ /** One bucket key the runtime can produce, e.g. "choice:2" or "score:11+". */
83
+ export type MinConfidenceBucket = `${(typeof BUCKET_TYPES)[number]}:${(typeof BUCKET_SIZES)[number]}`;
84
+ /** A `MinConfidenceMap` key: a bucket the runtime can produce, or "default" for the rest. */
85
+ export type MinConfidenceKey = MinConfidenceBucket | "default";
86
+ export type MinConfidenceMap = {
87
+ [K in MinConfidenceKey]?: number;
88
+ };
89
+ export type MinConfidence = number | MinConfidenceMap;
90
+ /**
91
+ * Validate a per-bucket abstention-threshold map (#394).
92
+ *
93
+ * Keys are option-count bucket strings like "choice:2", "choice:3-5", "score:6-10", "noul:2",
94
+ * plus an optional "default". Values are numbers in [0.0, 1.0].
95
+ */
96
+ export declare function checkMinConfidenceMap(m: unknown): MinConfidenceMap;
97
+ /**
98
+ * Validate opt-in abstention threshold `min_confidence` (#361, #394).
99
+ *
100
+ * Either a real number in [0.0, 1.0] or a per-bucket mapping. Booleans are rejected.
101
+ */
102
+ export declare function checkMinConfidence(v: unknown): MinConfidence;
103
+ export declare function optionBucket(answer: Record<string, unknown>): string | null;
104
+ export declare function resolveMinConfidence(answer: Record<string, unknown>, thresholds: MinConfidenceMap, defaultVal?: number): number;
105
+ /**
106
+ * Opt-in abstention marker (#361, #394): flag answers whose confidence falls below `min_confidence`.
107
+ *
108
+ * Reads `answer_confidence` (the calibrated max(p) confidence, invariant to label count k),
109
+ * falling back to `confidence` whenever `answer_confidence` is not a usable number -- see
110
+ * `gateConfidence`, which mirrors Python's `_gate_confidence`.
111
+ * The raw answer and confidence stay intact; `low_confidence: true` is added when the answer
112
+ * falls below the threshold, and removed if a previously-flagged answer now clears it (e.g.
113
+ * when a result dict is reused or re-evaluated with a different threshold).
114
+ *
115
+ * Supports both a scalar number in [0.0, 1.0] and a per-bucket mapping of thresholds.
116
+ *
117
+ * Exactly 0.0 runs this same loop rather than short-circuiting out of it. Nothing falls below
118
+ * it, so it marks no answer -- and the pass is what clears a marker an earlier, stricter threshold
119
+ * left on a reused payload (#910).
120
+ */
121
+ export declare function flagLowConfidence(results: Array<Record<string, unknown>> | Record<string, unknown>, minConfidence: MinConfidence): void;
122
+ export declare const TEMP_MIN = 0.5, TEMP_MAX = 5;
123
+ export declare function clampTemperature(t: unknown): number;
124
+ export declare function tempBucket(qtype: number, k: number): string;
125
+ export interface BinningEntry {
126
+ bins: number;
127
+ values: number[];
128
+ }
129
+ export type BinningMap = Record<string, BinningEntry>;
130
+ /**
131
+ * Validate a histogram-binning recalibration map.
132
+ *
133
+ * Keys are option-count bucket strings like "choice:2", "choice:3-5", "score:6-10", "noul:2".
134
+ * Values are objects with an integer `bins >= 1` and a `values` array of length `bins`
135
+ * where each number is in [0.0, 1.0].
136
+ */
137
+ export declare function checkBinningMap(m: unknown): BinningMap;
138
+ /**
139
+ * Recalibrate one `answer_confidence` for its option-count `bucket` (tempBucket).
140
+ *
141
+ * Returns the confidence unchanged when the map has no entry for the bucket, so a bucket the map
142
+ * was not fit for passes through rather than being forced to a wrong value.
143
+ */
144
+ export declare function applyBinningMap(confidence: number, bucket: string, binningMap?: BinningMap | null): number;
145
+ /** Max of a length list without spread (Math.max(...arr) throws RangeError past ~100k args). */
146
+ export declare function maxOf(values: ArrayLike<number>, fallback?: number): number;
147
+ export interface CollateItem {
148
+ ids: number[];
149
+ markers: number[];
150
+ qtype: number;
151
+ label?: number;
152
+ target?: number[];
153
+ [k: string]: unknown;
154
+ }
155
+ export interface CollatedBatch {
156
+ inputIds: number[][];
157
+ attentionMask: number[][];
158
+ markerPos: number[][];
159
+ markerMask: boolean[][];
160
+ qtype: number[];
161
+ label: number[];
162
+ meta: Record<string, unknown>[];
163
+ target?: number[][];
164
+ }
165
+ /** TS parity of py `collate_items(batch, pad_id)`: batch = list of groups. */
166
+ export declare function collateItems(batch: CollateItem[][], padId: number): CollatedBatch | null;
167
+ export {};
@@ -0,0 +1,478 @@
1
+ /** Python `json.dumps` for a finite number. JavaScript prints the same shortest round-trip
2
+ digits, but Python switches to exponent notation below 1e-4 (JavaScript: below 1e-6) and pads the
3
+ exponent to two digits (`5e-05`, not `5e-5`). An integer-valued number prints as before, which
4
+ matches a Python int below 1e21: JavaScript cannot tell Python's `49.0` from `49`. */
5
+ function pyNumber(v) {
6
+ const [mant, exp] = v.toExponential().split("e");
7
+ const e = Number(exp);
8
+ return e >= -4 ? String(v) : `${mant}e-${String(-e).padStart(2, "0")}`;
9
+ }
10
+ /** Python `json.dumps(v, ensure_ascii=False)` replica: separators (", ", ": "),
11
+ unicode raw, unknown types fall back to undefined (caller applies str()). */
12
+ function pyJson(v) {
13
+ if (v === null)
14
+ return "null";
15
+ if (typeof v === "string" || typeof v === "boolean")
16
+ return JSON.stringify(v);
17
+ if (typeof v === "number") {
18
+ if (Number.isNaN(v))
19
+ return "NaN";
20
+ if (v === Infinity)
21
+ return "Infinity";
22
+ if (v === -Infinity)
23
+ return "-Infinity";
24
+ return pyNumber(v);
25
+ }
26
+ if (Array.isArray(v))
27
+ return `[${v.map((x) => pyJson(x) ?? "null").join(", ")}]`;
28
+ if (typeof v === "object") {
29
+ const proto = Object.getPrototypeOf(v);
30
+ if (proto !== Object.prototype && proto !== null)
31
+ return undefined;
32
+ const parts = [];
33
+ for (const [k, x] of Object.entries(v)) {
34
+ const s = pyJson(x);
35
+ if (s !== undefined)
36
+ parts.push(`${JSON.stringify(k)}: ${s}`);
37
+ }
38
+ return `{${parts.join(", ")}}`;
39
+ }
40
+ return undefined;
41
+ }
42
+ export function serializeState(state) {
43
+ if (typeof state === "string")
44
+ return state;
45
+ return pyJson(state) ?? String(state);
46
+ }
47
+ /** The text of a criterion: the string itself, else the JSON the model was shown.
48
+ *
49
+ * Exported because `agent.ts` needs it for a `score` answer's `legend`, which maps an index to the
50
+ * text of that level. Putting the raw value in made the response's JSON types depend on the
51
+ * caller's input -- a numeric scale came back as `{"0": 1}`, a boolean as `{"0": true}` and a null
52
+ * as `{"0": null}`, which a Jev client refuses to parse (#302).
53
+ */
54
+ export function renderCriterion(v) {
55
+ return typeof v === "string" ? v : pyJson(v) ?? String(v);
56
+ }
57
+ export function renderOptions(q) {
58
+ if (q.t === "choice") {
59
+ const crit = q.crit;
60
+ return Object.entries(crit).map(([k, v]) => v === null || v === undefined || v === "" ? k : `${k}: ${renderCriterion(v)}`);
61
+ }
62
+ if (q.t === "score") {
63
+ return q.crit.map((c, i) => `level ${i}: ${renderCriterion(c)}`);
64
+ }
65
+ const crit = (q.crit ?? {});
66
+ const labels = q.labels ?? { false: "false", true: "true" };
67
+ const f = crit["false"], t = crit["true"];
68
+ return [
69
+ labels.false + ": " + (f !== null && f !== undefined && f !== "" ? renderCriterion(f) : "no, the statement does not hold"),
70
+ labels.true + ": " + (t !== null && t !== undefined && t !== "" ? renderCriterion(t) : "yes, the statement holds"),
71
+ ];
72
+ }
73
+ /** The question half of `buildSequence`: everything before the state tokens. Hoisted out so
74
+ * callers asking several questions about the same state can encode the state text only once. */
75
+ // Per-tokenizer prefix cache (cap 1k, clear on overflow); repeat triage skips re-encode.
76
+ const prefixCache = new WeakMap();
77
+ export function buildQuestionPrefix(tok, q, maxLen = 512, headMaxLen = 192, optionOrder) {
78
+ let per = prefixCache.get(tok);
79
+ if (!per) {
80
+ per = new Map();
81
+ prefixCache.set(tok, per);
82
+ }
83
+ // Key on what actually builds the prefix: raw criteria lie (JSON.stringify
84
+ // drops undefined values and throws on BigInt), rendered options don't.
85
+ const key = JSON.stringify([q.t, q.ins, renderOptions(q), maxLen, headMaxLen, optionOrder ?? null]);
86
+ const hit = per.get(key);
87
+ if (hit)
88
+ return hit;
89
+ const built = buildQuestionPrefixUncached(tok, q, maxLen, headMaxLen, optionOrder);
90
+ if (per.size > 1000)
91
+ per.clear();
92
+ per.set(key, built);
93
+ return built;
94
+ }
95
+ function buildQuestionPrefixUncached(tok, q, maxLen = 512, headMaxLen = 192, optionOrder) {
96
+ const maskTok = tok.maskToken;
97
+ const opts = renderOptions(q);
98
+ const order = optionOrder ?? opts.map((_, i) => i);
99
+ const ins = String(q.ins).split(maskTok).join(" ");
100
+ let headIds = tok.encode(`${q.t} question: ${ins}`);
101
+ let optIds = order.map((i) => [tok.maskId, ...tok.encode(" " + opts[i].split(maskTok).join(" ")).slice(0, 48)]);
102
+ let budget = headMaxLen - optIds.reduce((a, o) => a + o.length, 0);
103
+ let tokensPerOption = null;
104
+ if (budget < 16) {
105
+ const per = Math.max(4, Math.floor((headMaxLen - 16) / Math.max(1, optIds.length)));
106
+ optIds = optIds.map((o) => o.slice(0, per));
107
+ budget = headMaxLen - optIds.reduce((a, o) => a + o.length, 0);
108
+ tokensPerOption = per;
109
+ }
110
+ headIds = headIds.slice(0, Math.max(8, budget));
111
+ const ids = [tok.clsId, ...headIds, tok.sepId];
112
+ const markers = [];
113
+ for (const o of optIds) {
114
+ markers.push(ids.length);
115
+ ids.push(...o);
116
+ }
117
+ ids.push(tok.sepId);
118
+ // Counted on the capped option ids, before assembly, exactly as Python's `build_head` does:
119
+ // re-slicing the finished sequence cannot close the last option's span, so the last option
120
+ // always looks distinguishable however it collided (#538).
121
+ return {
122
+ ids, markers, nOptions: opts.length,
123
+ optionStats: {
124
+ total: opts.length,
125
+ distinct: new Set(optIds.map((o) => o.join(","))).size,
126
+ tokens_per_option: tokensPerOption,
127
+ },
128
+ };
129
+ }
130
+ /** Append pre-encoded state tokens to a question prefix. Identical output to building the
131
+ * whole sequence in one pass, but the state only needs encoding once per state, not once
132
+ * per (state, question) pair.
133
+ *
134
+ * The state is clamped to whatever room the head leaves; `stats` reports that clamp so callers
135
+ * never have to guess it from the character length of what they sent (issue #174, Python #181). */
136
+ export function sequenceWithState(prefix, stateIds, sepId, maxLen = 512, truncateLeft = false) {
137
+ const room = Math.max(0, maxLen - prefix.ids.length - 1);
138
+ // not stateIds.slice(-room): with no room left, slice(-0) is the whole state rather than none of it
139
+ const kept = truncateLeft ? stateIds.slice(Math.max(0, stateIds.length - room)) : stateIds.slice(0, room);
140
+ const ids = [...prefix.ids, ...kept, sepId].slice(0, maxLen);
141
+ // Count against the final clamp rather than `kept`: the clamp is what actually decided
142
+ // which state tokens reached the encoder.
143
+ const used = Math.max(0, Math.min(kept.length, maxLen - prefix.ids.length));
144
+ return {
145
+ ids,
146
+ markers: prefix.markers.filter((m) => m < maxLen),
147
+ stats: {
148
+ state_tokens: stateIds.length,
149
+ state_tokens_used: used,
150
+ state_tokens_dropped: stateIds.length - used,
151
+ truncated: used < stateIds.length,
152
+ options: prefix.optionStats,
153
+ },
154
+ };
155
+ }
156
+ /** The questions whose options no longer have a token span each, keyed by question id.
157
+ *
158
+ * `total` is what the question defines, not the number of markers that reached the sequence, so a
159
+ * report cannot say "43 of 43" about a question whose 28 missing options never entered the input
160
+ * at all. Mirrors Python `laya.common.collapsed_options`; empty when nothing collapsed, which is
161
+ * the overwhelming majority of requests, so the agents add the key only when it says something. */
162
+ export function collapsedOptions(qids, stats) {
163
+ const out = {};
164
+ qids.forEach((qid, i) => {
165
+ const s = stats[i]?.options;
166
+ if (s && s.distinct < s.total)
167
+ out[qid] = { total: s.total, distinct: s.distinct,
168
+ tokens_per_option: s.tokens_per_option };
169
+ });
170
+ return out;
171
+ }
172
+ export function buildSequence(tok, state, q, maxLen = 512, headMaxLen = 192, optionOrder, truncateLeft = false) {
173
+ const stAll = tok.encode(serializeState(state).split(tok.maskToken).join(" "));
174
+ return sequenceWithState(buildQuestionPrefix(tok, q, maxLen, headMaxLen, optionOrder), stAll, tok.sepId, maxLen, truncateLeft);
175
+ }
176
+ export function softmax(z) {
177
+ const m = Math.max(...z);
178
+ const e = z.map((v) => Math.exp(v - m));
179
+ const s = e.reduce((a, b) => a + b, 0);
180
+ return e.map((v) => v / s);
181
+ }
182
+ export function confidenceFromProbs(p) {
183
+ const k = p.length;
184
+ if (k < 2)
185
+ return 1.0;
186
+ const ent = -p.reduce((a, v) => a + v * Math.log(Math.max(v, 1e-12)), 0);
187
+ return Math.min(1, Math.max(0, 1 - ent / Math.log(k)));
188
+ }
189
+ export function answerConfidence(p) {
190
+ // Probability mass on the reported answer: max(p). This is the quantity temperature
191
+ // scaling fits and the one every calibration figure is computed on, so it is stable
192
+ // across option counts and comparable across question types -- unlike
193
+ // confidenceFromProbs, whose entropy scale moves with k.
194
+ if (p.length < 1)
195
+ return 1.0;
196
+ return Math.min(1, Math.max(0, Math.max(...p)));
197
+ }
198
+ function pyRepr(v) {
199
+ if (typeof v === "boolean")
200
+ return v ? "True" : "False";
201
+ if (v === null || v === undefined)
202
+ return "None";
203
+ if (typeof v === "number") {
204
+ if (Number.isNaN(v))
205
+ return "nan";
206
+ if (v === Infinity)
207
+ return "inf";
208
+ if (v === -Infinity)
209
+ return "-inf";
210
+ return String(v);
211
+ }
212
+ if (typeof v === "string")
213
+ return JSON.stringify(v);
214
+ if (Array.isArray(v))
215
+ return `[${v.map(pyRepr).join(", ")}]`;
216
+ if (typeof v === "object") {
217
+ const entries = Object.entries(v).map(([k, val]) => `${pyRepr(k)}: ${pyRepr(val)}`);
218
+ return `{${entries.join(", ")}}`;
219
+ }
220
+ return String(v);
221
+ }
222
+ /** The option types and option-count sizes `optionBucket`/`tempBucket` can produce. The bucket
223
+ * type and the runtime `BUCKET_KEY` check below are both derived from these, so what the type
224
+ * accepts cannot drift from the keys the runtime produces. */
225
+ const BUCKET_TYPES = ["choice", "score", "noul"];
226
+ const BUCKET_SIZES = ["2", "3-5", "6-10", "11+"];
227
+ /** The option-count bucket for a question with `k` options. */
228
+ function optionCountBucketSize(k) {
229
+ return k <= 2 ? BUCKET_SIZES[0] : k <= 5 ? BUCKET_SIZES[1] : k <= 10 ? BUCKET_SIZES[2] : BUCKET_SIZES[3];
230
+ }
231
+ const BUCKET_KEY = new RegExp(`^(${BUCKET_TYPES.join("|")}):(${BUCKET_SIZES.map((size) => size.replace("+", "\\+")).join("|")})$`);
232
+ /**
233
+ * Validate a per-bucket abstention-threshold map (#394).
234
+ *
235
+ * Keys are option-count bucket strings like "choice:2", "choice:3-5", "score:6-10", "noul:2",
236
+ * plus an optional "default". Values are numbers in [0.0, 1.0].
237
+ */
238
+ export function checkMinConfidenceMap(m) {
239
+ if (!m || typeof m !== "object" || Array.isArray(m) || Object.keys(m).length === 0) {
240
+ throw new Error(`a min_confidence map must be a non-empty dict of bucket -> float, got ${pyRepr(m)}`);
241
+ }
242
+ const out = {};
243
+ for (const [key, val] of Object.entries(m)) {
244
+ if (key !== "default" && !BUCKET_KEY.test(key)) {
245
+ throw new Error(`min_confidence map keys must be a bucket like 'choice:3-5' or 'default', got ${pyRepr(key)}`);
246
+ }
247
+ if (typeof val === "boolean" || typeof val !== "number" || !Number.isFinite(val) || val < 0.0 || val > 1.0) {
248
+ throw new Error(`min_confidence must be a float in [0.0, 1.0], got ${pyRepr(val)}`);
249
+ }
250
+ out[key] = val;
251
+ }
252
+ return out;
253
+ }
254
+ /**
255
+ * Validate opt-in abstention threshold `min_confidence` (#361, #394).
256
+ *
257
+ * Either a real number in [0.0, 1.0] or a per-bucket mapping. Booleans are rejected.
258
+ */
259
+ export function checkMinConfidence(v) {
260
+ if (v && typeof v === "object" && !Array.isArray(v)) {
261
+ return checkMinConfidenceMap(v);
262
+ }
263
+ if (typeof v === "boolean" || typeof v !== "number" || !Number.isFinite(v) || v < 0.0 || v > 1.0) {
264
+ throw new Error(`min_confidence must be a float in [0.0, 1.0], got ${pyRepr(v)}`);
265
+ }
266
+ return v;
267
+ }
268
+ export function optionBucket(answer) {
269
+ const qt = answer.type;
270
+ if (qt !== "choice" && qt !== "score" && qt !== "noul")
271
+ return null;
272
+ const probs = answer.probabilities;
273
+ let k;
274
+ if (probs && typeof probs === "object" && !Array.isArray(probs)) {
275
+ k = Object.keys(probs).length;
276
+ }
277
+ else if (qt === "noul") {
278
+ k = 2;
279
+ }
280
+ else {
281
+ return null;
282
+ }
283
+ const size = optionCountBucketSize(k);
284
+ return `${qt}:${size}`;
285
+ }
286
+ export function resolveMinConfidence(answer, thresholds, defaultVal = 0.0) {
287
+ const key = optionBucket(answer);
288
+ if (key !== null) {
289
+ const threshold = thresholds[key];
290
+ if (threshold !== undefined)
291
+ return threshold;
292
+ }
293
+ return thresholds.default ?? defaultVal;
294
+ }
295
+ /**
296
+ * The number the abstention gate compares against the threshold, or null if there is none.
297
+ *
298
+ * Mirrors Python `laya.confidence._gate_confidence` exactly, including the two places it is
299
+ * easy to get wrong:
300
+ *
301
+ * - the fallback is taken whenever `answer_confidence` is not a usable number, not only when
302
+ * it is absent or null. An `answer_confidence` of `NaN` beside a usable `confidence` is
303
+ * gated on the `confidence`, because "unusable" and "missing" are the same case here;
304
+ * - a number outside [0, 1] is still a number. It is compared, not discarded: a negative
305
+ * `answer_confidence` is below every threshold and so is flagged, and one above 1 clears
306
+ * every threshold. Treating out-of-range as "nothing to gate on" would silently clear a
307
+ * marker Python sets.
308
+ *
309
+ * null means no usable number, never an unusable one, which is what lets the caller tell
310
+ * "nothing to gate on" from "a gate ran".
311
+ */
312
+ function gateConfidence(answer) {
313
+ const primary = answer.answer_confidence;
314
+ if (typeof primary === "number" && Number.isFinite(primary))
315
+ return primary;
316
+ const fallback = answer.confidence;
317
+ if (typeof fallback === "number" && Number.isFinite(fallback))
318
+ return fallback;
319
+ return null;
320
+ }
321
+ /**
322
+ * Opt-in abstention marker (#361, #394): flag answers whose confidence falls below `min_confidence`.
323
+ *
324
+ * Reads `answer_confidence` (the calibrated max(p) confidence, invariant to label count k),
325
+ * falling back to `confidence` whenever `answer_confidence` is not a usable number -- see
326
+ * `gateConfidence`, which mirrors Python's `_gate_confidence`.
327
+ * The raw answer and confidence stay intact; `low_confidence: true` is added when the answer
328
+ * falls below the threshold, and removed if a previously-flagged answer now clears it (e.g.
329
+ * when a result dict is reused or re-evaluated with a different threshold).
330
+ *
331
+ * Supports both a scalar number in [0.0, 1.0] and a per-bucket mapping of thresholds.
332
+ *
333
+ * Exactly 0.0 runs this same loop rather than short-circuiting out of it. Nothing falls below
334
+ * it, so it marks no answer -- and the pass is what clears a marker an earlier, stricter threshold
335
+ * left on a reused payload (#910).
336
+ */
337
+ export function flagLowConfidence(results, minConfidence) {
338
+ const isMap = typeof minConfidence === "object" && minConfidence !== null;
339
+ const list = Array.isArray(results) ? results : [results];
340
+ for (const res of list) {
341
+ const answers = res && typeof res === "object" ? res.answers : null;
342
+ if (!answers || typeof answers !== "object")
343
+ continue;
344
+ for (const a of Object.values(answers)) {
345
+ if (!a || typeof a !== "object")
346
+ continue;
347
+ const ansObj = a;
348
+ const conf = gateConfidence(ansObj);
349
+ if (conf === null) {
350
+ delete ansObj.low_confidence;
351
+ continue;
352
+ }
353
+ const thr = isMap ? resolveMinConfidence(ansObj, minConfidence) : minConfidence;
354
+ if (conf < thr) {
355
+ ansObj.low_confidence = true;
356
+ }
357
+ else {
358
+ delete ansObj.low_confidence;
359
+ }
360
+ }
361
+ }
362
+ }
363
+ export const TEMP_MIN = 0.5, TEMP_MAX = 5.0;
364
+ export function clampTemperature(t) {
365
+ if (t === null || t === undefined || t === "" || typeof t === "boolean")
366
+ return 1.0;
367
+ const f = typeof t === "number" ? t : Number(t);
368
+ if (!Number.isFinite(f))
369
+ return 1.0;
370
+ return Math.min(TEMP_MAX, Math.max(TEMP_MIN, f));
371
+ }
372
+ export function tempBucket(qtype, k) {
373
+ return `${BUCKET_TYPES[qtype]}:${optionCountBucketSize(k)}`;
374
+ }
375
+ /**
376
+ * Validate a histogram-binning recalibration map.
377
+ *
378
+ * Keys are option-count bucket strings like "choice:2", "choice:3-5", "score:6-10", "noul:2".
379
+ * Values are objects with an integer `bins >= 1` and a `values` array of length `bins`
380
+ * where each number is in [0.0, 1.0].
381
+ */
382
+ export function checkBinningMap(m) {
383
+ if (!m || typeof m !== "object" || Array.isArray(m)) {
384
+ throw new Error(`binning_map must be an object of bucket -> {bins, values}, got ${pyRepr(m)}`);
385
+ }
386
+ const out = {};
387
+ for (const [name, entry] of Object.entries(m)) {
388
+ if (!BUCKET_KEY.test(name)) {
389
+ throw new Error(`binning_map key ${pyRepr(name)} is not a bucket like "choice:2" or "score:3-5"`);
390
+ }
391
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
392
+ throw new Error(`binning_map[${pyRepr(name)}] must be an object with "bins" and "values", got ${pyRepr(entry)}`);
393
+ }
394
+ const rec = entry;
395
+ const nBins = rec.bins;
396
+ const values = rec.values;
397
+ if (typeof nBins === "boolean" || typeof nBins !== "number" || !Number.isInteger(nBins) || nBins < 1) {
398
+ throw new Error(`binning_map[${pyRepr(name)}] must have an integer "bins" >= 1, got ${pyRepr(nBins)}`);
399
+ }
400
+ if (!Array.isArray(values) || values.length !== nBins) {
401
+ throw new Error(`binning_map[${pyRepr(name)}] must have "values" of length "bins" (${nBins})`);
402
+ }
403
+ const parsedValues = [];
404
+ for (const v of values) {
405
+ if (typeof v === "boolean" || typeof v !== "number" || !Number.isFinite(v) || v < 0.0 || v > 1.0) {
406
+ throw new Error(`binning_map[${pyRepr(name)}] values must be numbers in [0, 1], got ${pyRepr(v)}`);
407
+ }
408
+ parsedValues.push(v);
409
+ }
410
+ out[name] = { bins: nBins, values: parsedValues };
411
+ }
412
+ return out;
413
+ }
414
+ /**
415
+ * Recalibrate one `answer_confidence` for its option-count `bucket` (tempBucket).
416
+ *
417
+ * Returns the confidence unchanged when the map has no entry for the bucket, so a bucket the map
418
+ * was not fit for passes through rather than being forced to a wrong value.
419
+ */
420
+ export function applyBinningMap(confidence, bucket, binningMap) {
421
+ if (!Number.isFinite(confidence))
422
+ return confidence;
423
+ const entry = binningMap?.[bucket];
424
+ if (!entry) {
425
+ return confidence;
426
+ }
427
+ const bins = entry.bins;
428
+ const b = Math.min(bins - 1, Math.max(0, Math.floor(confidence * bins)));
429
+ return entry.values[b];
430
+ }
431
+ /** Max of a length list without spread (Math.max(...arr) throws RangeError past ~100k args). */
432
+ export function maxOf(values, fallback = 0) {
433
+ let m = fallback;
434
+ for (let i = 0; i < values.length; i++)
435
+ if (values[i] > m)
436
+ m = values[i];
437
+ return m;
438
+ }
439
+ /** TS parity of py `collate_items(batch, pad_id)`: batch = list of groups. */
440
+ export function collateItems(batch, padId) {
441
+ const items = (batch ?? []).flat();
442
+ if (items.length === 0)
443
+ return null;
444
+ let L = 0;
445
+ let K = 0;
446
+ for (const it of items) {
447
+ if (it.ids.length > L)
448
+ L = it.ids.length;
449
+ if (it.markers.length > K)
450
+ K = it.markers.length;
451
+ }
452
+ const hasTarget = items.some((it) => "target" in it);
453
+ const inputIds = items.map((it) => [...it.ids, ...Array(L - it.ids.length).fill(padId)]);
454
+ const attentionMask = items.map((it) => [...Array(it.ids.length).fill(1), ...Array(L - it.ids.length).fill(0)]);
455
+ const markerPos = items.map((it) => [...it.markers, ...Array(K - it.markers.length).fill(0)]);
456
+ const markerMask = items.map((it) => [...it.markers.map(() => true), ...Array(K - it.markers.length).fill(false)]);
457
+ const qtype = items.map((it) => it.qtype);
458
+ const label = items.map((it) => (typeof it.label === "number" ? it.label : -1));
459
+ const meta = items.map((it) => {
460
+ const { ids: _ids, markers: _markers, target: _target, ...m } = it;
461
+ return m;
462
+ });
463
+ const out = { inputIds, attentionMask, markerPos, markerMask, qtype, label, meta };
464
+ if (hasTarget) {
465
+ out.target = items.map((it, i) => {
466
+ const t = Array.isArray(it.target) ? it.target : [];
467
+ const k = it.markers.length;
468
+ if (t.length > k) {
469
+ // Same guard as py collate_items: the limit is this item's own marker count, not the
470
+ // batch-wide K — a wider sibling row must not legitimise extra entries (#311).
471
+ throw new Error(`collateItems: item ${i} has ${t.length} target entries but only ${k} marker positions; ` +
472
+ "a target needs one entry per option");
473
+ }
474
+ return [...t, ...Array(K - t.length).fill(0)];
475
+ });
476
+ }
477
+ return out;
478
+ }
@@ -0,0 +1,17 @@
1
+ import type { QuestionDef, SystemAnswer } from "./agent.js";
2
+ /** One-line question factories; output always passes checkQuestion. */
3
+ export declare const q: {
4
+ choice(instructions: string, criteria: Record<string, unknown> | string[]): QuestionDef;
5
+ score(instructions: string, criteria: unknown[]): QuestionDef;
6
+ noul(instructions: string, criteria?: Record<string, unknown>, labels?: {
7
+ false: string;
8
+ true: string;
9
+ }): QuestionDef;
10
+ };
11
+ /** Argmax label: choice string, score key, noul boolean. */
12
+ export declare function best(answer: SystemAnswer): string | boolean;
13
+ /** Top-k probability keys, descending. */
14
+ export declare function topK(probs: Record<string, number>, k: number): string[];
15
+ /** Confidence gate (default 0.8) on answer_confidence (max(p)) alone, so the
16
+ * gate uses one scale across question types instead of mixing in entropy. */
17
+ export declare function isConfident(answer: Pick<SystemAnswer, "answer_confidence">, thresh?: number): boolean;