@try-works/extension-laya 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/pure.d.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * is testable in isolation, and so a reviewer can see that the reported
9
9
  * confidence is EXACTLY the runtime's uncalibrated probability mass (DEC-08).
10
10
  */
11
+ import type { DecisionScope } from './scope.js';
11
12
  /** The option-count bounds the vendored runtime enforces (structured.js). */
12
13
  export declare const MAX_OPTIONS = 32;
13
14
  export declare const MAX_SCORE_LEVELS = 10;
@@ -15,6 +16,180 @@ export declare const MAX_SCORE_LEVELS = 10;
15
16
  export declare function softmax(z: readonly number[]): number[];
16
17
  /** Probability mass on the reported answer — the vendored answerConfidence. */
17
18
  export declare function answerConfidence(p: readonly number[]): number;
19
+ /** R18/DEC-06: the only probability kind the LOCAL decision payloads advertise. */
20
+ export declare const LOCAL_DECISION_PROBABILITY_KIND: "model_probability";
21
+ /** R18 default scope; R20's detector replaces it with a computed boundary. */
22
+ export declare const LOCAL_DECISION_SCOPE: "in-scope";
23
+ /** R22: per-item reliability derived from the margin against a REVIEWED trust margin. */
24
+ export type DecisionReliability = 'confident' | 'tentative';
25
+ /**
26
+ * Reliability for one margin (R22): a margin at or above the reviewed trustMargin is
27
+ * 'confident'; strictly below is 'tentative'. No default threshold is invented.
28
+ * @param margin - the top-two probability gap.
29
+ * @param trustMargin - the REVIEWED trustMargin in [0,1].
30
+ * @returns the per-item reliability.
31
+ */
32
+ export declare function reliabilityOf(margin: number, trustMargin: number): DecisionReliability;
33
+ /** Which local decision contract a payload belongs to. */
34
+ export type LocalDecisionKind = 'test' | 'choose' | 'score';
35
+ /**
36
+ * The v2 local decision envelope: the answer, the raw model probabilities and the
37
+ * evidence a caller can audit. It deliberately has NO `confidence` (DEC-04): Laya's
38
+ * mass is near-uniform even when wrong, so a single confidence field would mislabel it.
39
+ */
40
+ export interface LocalDecisionPayload {
41
+ readonly decision?: string | null;
42
+ readonly chosen?: string | null;
43
+ readonly score?: string | null;
44
+ readonly probabilities: Readonly<Record<string, number>>;
45
+ readonly probabilityKind: typeof LOCAL_DECISION_PROBABILITY_KIND;
46
+ readonly margin: number;
47
+ readonly scope: DecisionScope;
48
+ readonly abstained: boolean;
49
+ /** R19: the reviewed abstainMargin echoed for audit, or null while the gate is BLOCKED. */
50
+ readonly abstainMargin: number | null;
51
+ /** R22: the reviewed trustMargin echoed for audit, or null while no reviewed config exists. */
52
+ readonly marginThreshold: number | null;
53
+ /** R22: per-item reliability, or null when no reviewed trustMargin exists (never guessed). */
54
+ readonly reliability: DecisionReliability | null;
55
+ }
56
+ /** Inputs for {@link buildLocalDecisionPayload}. */
57
+ export interface LocalDecisionPayloadInput {
58
+ readonly kind: LocalDecisionKind;
59
+ /** The already-mapped answer label (or null when the runtime abstained). */
60
+ readonly answer: string | null;
61
+ readonly probabilities: Readonly<Record<string, number>>;
62
+ readonly abstained: boolean;
63
+ readonly scope?: DecisionScope;
64
+ /** R19: the REVIEWED abstain margin; absent while the gate is BLOCKED (no default). */
65
+ readonly abstainMargin?: number | undefined;
66
+ /** R22: the REVIEWED trust margin; absent while the gate is BLOCKED (no reliability claim). */
67
+ readonly trustMargin?: number | undefined;
68
+ }
69
+ /**
70
+ * The top-two probability gap (margin). The two highest finite probabilities are
71
+ * compared; fewer than two values has no gap and reports 0.
72
+ * @param probabilities - label/index → probability.
73
+ * @returns the non-negative gap between the best and second-best probability.
74
+ */
75
+ export declare function topTwoMargin(probabilities: Readonly<Record<string, number>>): number;
76
+ /**
77
+ * Build the v2 local decision payload (R18).
78
+ *
79
+ * Fields are the contract: the mapped answer, raw probabilities, the pinned
80
+ * `model_probability` kind, the top-two margin, the scope and `abstained`. NO
81
+ * confidence/calibrated/answer_confidence field is emitted.
82
+ * @param input - kind, answer label, probabilities, abstention and optional scope.
83
+ * @returns the schema-shaped payload (before the optional act-gate field).
84
+ */
85
+ export declare function buildLocalDecisionPayload(input: LocalDecisionPayloadInput): LocalDecisionPayload;
86
+ /** One margin-gate decision, with the threshold echoed for audit (R19). */
87
+ export interface MarginGateDecision {
88
+ /** True when the top-two gap is BELOW the threshold. */
89
+ readonly abstain: boolean;
90
+ /** The top-two probability gap actually observed. */
91
+ readonly margin: number;
92
+ /** The reviewed threshold the decision used (echoed, never hidden). */
93
+ readonly threshold: number;
94
+ }
95
+ /**
96
+ * Apply the reviewed abstain margin to a probability map (R19).
97
+ * A margin STRICTLY below the threshold abstains; equal or above answers.
98
+ * @param probabilities - label/index → probability.
99
+ * @param threshold - the REVIEWED abstainMargin in [0,1]; never a default.
100
+ * @returns the decision plus the observed margin and the threshold used.
101
+ */
102
+ export declare function marginGate(probabilities: Readonly<Record<string, number>>, threshold: number): MarginGateDecision;
103
+ /**
104
+ * Withhold a local decision payload whose margin is below the reviewed threshold (R19).
105
+ * The probabilities, margin, scope and probabilityKind are preserved; the answer becomes
106
+ * null and abstained becomes true. A clearing margin returns the payload unchanged.
107
+ * @param payload - the v2 local payload.
108
+ * @param threshold - the reviewed abstainMargin.
109
+ * @returns the gated payload.
110
+ */
111
+ export declare function applyMarginGate(payload: LocalDecisionPayload, threshold: number): LocalDecisionPayload;
112
+ /** One labelled row for the R19 coverage-budget replay. */
113
+ export interface CoverageRow {
114
+ readonly correct: boolean;
115
+ readonly probabilities: Readonly<Record<string, number>>;
116
+ }
117
+ /** Coverage stayed within the reviewed budget. */
118
+ export interface CoverageWithinBudget {
119
+ readonly ok: true;
120
+ readonly lostCorrect: number;
121
+ /** The reviewed coverageBudget that was checked (echoed for audit). */
122
+ readonly budget: number;
123
+ }
124
+ /** Coverage lost more correct rows than the reviewed budget allows. */
125
+ export interface CoverageBudgetExceeded {
126
+ readonly ok: false;
127
+ readonly code: 'COVERAGE_BUDGET_EXCEEDED';
128
+ readonly lostCorrect: number;
129
+ readonly budget: number;
130
+ readonly message: string;
131
+ }
132
+ /** The coverage-budget outcome. */
133
+ export type CoverageBudgetOutcome = CoverageWithinBudget | CoverageBudgetExceeded;
134
+ /**
135
+ * Replay the gate over CORRECT labelled rows and fail when it loses more than the reviewed
136
+ * coverage budget (R19). This is a replay check, not a new measurement.
137
+ * @param rows - correct-labelled rows with their probabilities.
138
+ * @param threshold - the reviewed abstainMargin.
139
+ * @param budget - the reviewed coverageBudget (non-negative integer).
140
+ * @returns ok with the lost count, or a named coverage failure.
141
+ */
142
+ export declare function coverageBudgetFailure(rows: readonly CoverageRow[], threshold: number, budget: number): CoverageBudgetOutcome;
143
+ /** One row of an R22 labelled decision fixture. */
144
+ export interface R22ReplayRow {
145
+ readonly kind?: string;
146
+ /** The human-verified label. */
147
+ readonly label?: string;
148
+ /** Captured model probabilities per option/level (required to replay a margin). */
149
+ readonly probabilities?: Readonly<Record<string, number>>;
150
+ }
151
+ /** One R22 fixture document (dev or held-out half). */
152
+ export interface R22ReplayDocument {
153
+ readonly set?: string;
154
+ readonly reviewStatus?: string;
155
+ readonly reviewedAt?: string;
156
+ /** Plan R22: the labeler wrote the labels BEFORE opening model outputs. */
157
+ readonly blind?: boolean;
158
+ /** Plan R22: the reviewer who signed the blind protocol. */
159
+ readonly reviewer?: string;
160
+ readonly rows?: readonly R22ReplayRow[];
161
+ }
162
+ /** The replay is BLOCKED: a named reason, never a pass claim. */
163
+ export interface R22ReplayBlocked {
164
+ readonly status: 'BLOCKED';
165
+ readonly code: 'R22_FIXTURES_NOT_REVIEWED' | 'R22_NO_CAPTURED_VECTORS';
166
+ readonly reason: string;
167
+ }
168
+ /** The replay ran against operator-reviewed fixtures with captured vectors. */
169
+ export interface R22ReplayCompleted {
170
+ readonly status: 'REPLAYED';
171
+ readonly tentativeContainsMustRecheck: boolean;
172
+ readonly toleranceExceeded: boolean;
173
+ readonly mustRecheckRows: number;
174
+ readonly trustRows: number;
175
+ readonly tentativeTrustRows: number;
176
+ readonly allowedTrustInTentative: number;
177
+ readonly confidentRows: number;
178
+ }
179
+ /** The R22 replay outcome. */
180
+ export type R22ReplayOutcome = R22ReplayBlocked | R22ReplayCompleted;
181
+ /**
182
+ * Replay the R22 held-out containment/tolerance rule (R22), or return BLOCKED with a named
183
+ * reason. The committed fixtures are draft-unreviewed, so this returns BLOCKED today and
184
+ * claims no pass. A dev-fitted reviewed trustMargin is supplied by the caller, never refit
185
+ * here.
186
+ * @param dev - the development fixture document (must be reviewed, used for provenance only).
187
+ * @param heldout - the held-out fixture document (acceptance only).
188
+ * @param trustMargin - the REVIEWED trust margin fitted on dev.
189
+ * @param tolerance - the pre-registered maximum fraction of trust rows allowed in tentative.
190
+ * @returns REPLAYED results or a named BLOCKED reason.
191
+ */
192
+ export declare function evaluateR22Replay(dev: R22ReplayDocument, heldout: R22ReplayDocument, trustMargin: number, tolerance: number): R22ReplayOutcome;
18
193
  /** One boundary decision: logits → label + confidence. */
19
194
  export interface BoundaryDecision {
20
195
  readonly index: number;
@@ -33,3 +208,165 @@ export declare function decideFromLogits(labels: readonly string[], logits: read
33
208
  * schema enforces, re-asserted here so the runtime refusal is precise.
34
209
  */
35
210
  export declare function validateOptions(options: readonly string[], max: number): string[];
211
+ /** The native input rejection codes DEC-05 requires. */
212
+ export type DecisionInputErrorCode = 'INPUT_TRUNCATED' | 'INDISTINGUISHABLE_OPTIONS';
213
+ /** A refused decision input, carrying the code the caller/UI must surface (DEC-05). */
214
+ export declare class DecisionInputError extends Error {
215
+ readonly name = "DecisionInputError";
216
+ /** The stable rejection code. */
217
+ readonly code: DecisionInputErrorCode;
218
+ constructor(code: DecisionInputErrorCode, message: string);
219
+ }
220
+ /** The runtime's per-answer usage report, as far as DEC-05 needs it. */
221
+ export interface DecisionUsageReport {
222
+ readonly truncated?: boolean;
223
+ readonly state_tokens_dropped?: number;
224
+ readonly truncated_questions?: readonly string[];
225
+ readonly options?: Readonly<Record<string, number>>;
226
+ }
227
+ /**
228
+ * Reject a decision whose input the model did not fully receive (DEC-05).
229
+ *
230
+ * The native runtime reports both dropped state tokens (`truncated`, a token-budget
231
+ * fact) and options that collapsed to the same head representation (`options`).
232
+ * Returning a confident answer over either would hide the loss.
233
+ * @param usage - the runtime's usage report.
234
+ * @throws DecisionInputError with `INPUT_TRUNCATED` or `INDISTINGUISHABLE_OPTIONS`.
235
+ */
236
+ export declare function assertDecisionInputSafe(usage: DecisionUsageReport | undefined): void;
237
+ /**
238
+ * Validate a probability distribution the runtime reported (DEC-04).
239
+ *
240
+ * The native API returns probabilities as an object; a malformed vector is not a
241
+ * weaker answer, it is an answer the extension must not report as probabilities.
242
+ * Length must match the declared options/levels, every value must be finite and in
243
+ * [0,1], and the total must be 1 within a small floating-point tolerance.
244
+ * @param probabilities - the runtime's index/label → probability map.
245
+ * @param expectedEntries - how many options/levels the answer covers.
246
+ * @returns the same map, when valid.
247
+ * @throws Error naming the violated property.
248
+ */
249
+ export declare function validateProbabilityDistribution(probabilities: Readonly<Record<string, number>>, expectedEntries: number): Readonly<Record<string, number>>;
250
+ /** A stable, reversible mapping between caller option IDs and native criteria keys. */
251
+ export interface ProviderKeyMapping {
252
+ /** The native choice criteria: provider key → null description, input order. */
253
+ readonly criteria: Record<string, null>;
254
+ /** Provider keys in caller order. */
255
+ readonly originalToProvider: readonly string[];
256
+ /** Map a provider key back to the caller's original ID. */
257
+ toOriginal(providerKey: string): string;
258
+ /** Map a native probability object back to the caller's original IDs. */
259
+ toOriginalProbabilities(probabilities: Readonly<Record<string, number>>): Record<string, number>;
260
+ }
261
+ /**
262
+ * Build a stable reversible provider-key mapping for choice options (DEC-03).
263
+ *
264
+ * The native API uses each criterion key as both the option text and the answer
265
+ * key. Ordinary labels are therefore passed through unchanged. The reserved object
266
+ * keys (`__proto__`, `constructor`, `prototype`) are unsafe as object keys and get a
267
+ * deterministic `__option_<index>` surrogate instead; every answer is mapped back to
268
+ * the caller's original ID before it is returned. Surrogates never collide with a
269
+ * caller label in the same question.
270
+ * @param options - the caller's validated option labels, in input order.
271
+ * @returns the native criteria plus the reverse mapping.
272
+ */
273
+ export declare function mapProviderOptionKeys(options: readonly string[]): ProviderKeyMapping;
274
+ /**
275
+ * Map a SCORE answer onto the caller's level label.
276
+ *
277
+ * The runtime answers a score question with BOTH an expected value
278
+ * (`score: Σ i·p_i`, a float) and per-index probabilities plus a legend. The
279
+ * declared output schema requires a LABEL (`score: string|null`), so the label is
280
+ * the argmax of those probabilities — exactly what the vendored runtime's own
281
+ * `best()` returns — mapped through the levels the caller supplied. The expected
282
+ * value is deliberately NOT reported as the score: it is a mean, not a level.
283
+ * @param probabilities - the answer's index→probability map.
284
+ * @param levels - the caller's levels, lowest first.
285
+ * @returns the level label, or null when no index maps to a level.
286
+ */
287
+ /** The standard `decision.choose` payload. */
288
+ export interface StandardDecisionChoice {
289
+ readonly chosen: number;
290
+ readonly confidence: 'confident' | 'likely' | 'tentative';
291
+ readonly reason: string;
292
+ }
293
+ /**
294
+ * Map a native choice onto the STANDARD `decision.choose` contract.
295
+ *
296
+ * The runtime's own chosen label is revalidated against the caller's FULL option
297
+ * set before it is used; an unknown label refuses instead of being rendered. When
298
+ * the runtime abstained (null choice), the argmax over the caller's options is
299
+ * used so the standard payload always names an option.
300
+ * @param options - the caller's complete options, in order.
301
+ * @param chosenLabel - the runtime's choice, or null when it abstained.
302
+ * @param probabilities - per-option probabilities, keyed by option label.
303
+ * @param confidence - the runtime's uncalibrated confidence mass.
304
+ * @returns the standard contract payload, never with a label outside `options`.
305
+ */
306
+ export declare function standardChooseFromNative(options: readonly string[], chosenLabel: string | null, probabilities: Readonly<Record<string, number>>, confidence: number): StandardDecisionChoice;
307
+ /**
308
+ * Map a SCORE answer onto the caller's level label.
309
+ *
310
+ * The runtime answers a score question with BOTH an expected value
311
+ * (`score: Σ i·p_i`, a float) and per-index probabilities plus a legend. The
312
+ * declared output schema requires a LABEL (`score: string|null`), so the label is
313
+ * the argmax of those probabilities — exactly what the vendored runtime's own
314
+ * `best()` returns — mapped through the levels the caller supplied. The expected
315
+ * value is deliberately NOT reported as the score: it is a mean, not a level.
316
+ * @param probabilities - the answer's index→probability map.
317
+ * @param levels - the caller's levels, lowest first.
318
+ * @returns the level label, or null when no index maps to a level.
319
+ */
320
+ export declare function scoreLevelFromProbabilities(probabilities: Readonly<Record<string, number>>, levels: readonly string[]): string | null;
321
+ /** One captured R19 replay row: a model probability map and whether the answer is correct. */
322
+ export interface R19ReplayRow {
323
+ readonly id?: string;
324
+ /** Captured model probabilities per label/index. */
325
+ readonly probabilities?: Readonly<Record<string, number>>;
326
+ /** Human-verified correctness of the answered route. */
327
+ readonly correct?: boolean;
328
+ }
329
+ /** One R19 fixture document (task-shape dev or held-out half). */
330
+ export interface R19ReplayDocument {
331
+ readonly set?: string;
332
+ readonly reviewStatus?: string;
333
+ readonly reviewedAt?: string;
334
+ readonly blind?: boolean;
335
+ readonly reviewer?: string;
336
+ readonly rows?: readonly R19ReplayRow[];
337
+ }
338
+ /** The R19 replay is BLOCKED: named reason, never a pass claim. */
339
+ export interface R19ReplayBlocked {
340
+ readonly status: 'BLOCKED';
341
+ readonly code: 'R19_FIXTURES_NOT_REVIEWED' | 'R19_NO_CAPTURED_VECTORS';
342
+ readonly reason: string;
343
+ }
344
+ /** The R19 replay ran against reviewed, blind fixtures with captured vectors. */
345
+ export interface R19ReplayCompleted {
346
+ readonly status: 'REPLAYED';
347
+ /** Rows whose top-two margin is below the reviewed abstainMargin. */
348
+ readonly abstentions: number;
349
+ /** Correct rows the gate would abstain on (the coverage loss). */
350
+ readonly lostCorrect: number;
351
+ /** Incorrect rows the gate would ANSWER, i.e. wrong routes it fails to abstain on. */
352
+ readonly wrongRoutes: number;
353
+ /** The reviewed coverageBudget verdict. */
354
+ readonly coverage: CoverageBudgetOutcome;
355
+ }
356
+ /** The R19 replay outcome. */
357
+ export type R19ReplayOutcome = R19ReplayBlocked | R19ReplayCompleted;
358
+ /**
359
+ * Replay the reviewed margin gate over the held-out task-shape fixtures (R19), wiring the
360
+ * reviewed coverageBudget into the verdict.
361
+ *
362
+ * The replay is BLOCKED with a named reason unless BOTH halves carry operator provenance
363
+ * (reviewStatus 'reviewed', a parseable reviewedAt, blind:true, a non-empty reviewer) AND
364
+ * every held-out row carries a captured probability map and a correctness label. A
365
+ * dev-fitted abstainMargin is supplied by the caller, never refit on held-out data.
366
+ * @param dev - the development fixture document (provenance only).
367
+ * @param heldout - the held-out fixture document (acceptance only).
368
+ * @param abstainMargin - the REVIEWED abstain margin.
369
+ * @param coverageBudget - the REVIEWED maximum correct rows the gate may lose.
370
+ * @returns REPLAYED results with the coverage verdict, or a named BLOCKED reason.
371
+ */
372
+ export declare function evaluateR19Replay(dev: R19ReplayDocument, heldout: R19ReplayDocument, abstainMargin: number, coverageBudget: number): R19ReplayOutcome;