@gobing-ai/ts-ai-runner 0.8.9 → 0.9.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.
@@ -1,70 +0,0 @@
1
- /**
2
- * `DecisionError` taxonomy. Both the facade and the driver throw from this set;
3
- * no raw SDK error class escapes the package. Keeping every class in one file
4
- * makes that invariant checkable by reading a single file.
5
- */
6
- /** Base class for every decision-surface error. */
7
- export class DecisionError extends Error {
8
- constructor(message, options) {
9
- super(message, options);
10
- this.name = new.target.name;
11
- }
12
- }
13
- /** Missing configuration — e.g. no `TYPESAFE_API_KEY` in the injected env. Carries the variable name. */
14
- export class DecisionConfigError extends DecisionError {
15
- variable;
16
- constructor(message, variable, options) {
17
- super(message, options);
18
- this.variable = variable;
19
- }
20
- }
21
- /** Authentication or permission failure upstream. Carries the HTTP status. */
22
- export class DecisionAuthError extends DecisionError {
23
- status;
24
- constructor(message, status, options) {
25
- super(message, options);
26
- this.status = status;
27
- }
28
- }
29
- /** Rate limited upstream. Carries the status and the parsed retry-after hint. */
30
- export class DecisionRateLimitError extends DecisionError {
31
- status;
32
- retryAfterMs;
33
- constructor(message, status, retryAfterMs, options) {
34
- super(message, options);
35
- this.status = status;
36
- this.retryAfterMs = retryAfterMs;
37
- }
38
- }
39
- /** Request timed out. Carries the configured timeout in milliseconds. */
40
- export class DecisionTimeoutError extends DecisionError {
41
- timeoutMs;
42
- constructor(message, timeoutMs, options) {
43
- super(message, options);
44
- this.timeoutMs = timeoutMs;
45
- }
46
- }
47
- /** The backend was unreachable. Carries the underlying cause. */
48
- export class DecisionConnectionError extends DecisionError {
49
- constructor(message, options) {
50
- super(message, options);
51
- }
52
- }
53
- /** The request was rejected as malformed (4xx other than auth/rate-limit). Carries status and a body summary. */
54
- export class DecisionRequestError extends DecisionError {
55
- status;
56
- bodySummary;
57
- constructor(message, status, bodySummary, options) {
58
- super(message, options);
59
- this.status = status;
60
- this.bodySummary = bodySummary;
61
- }
62
- }
63
- /** Upstream server failure (5xx). Carries the HTTP status. */
64
- export class DecisionBackendError extends DecisionError {
65
- status;
66
- constructor(message, status, options) {
67
- super(message, options);
68
- this.status = status;
69
- }
70
- }
@@ -1,115 +0,0 @@
1
- /**
2
- * The engine-agnostic sampled-driver core (task 0114 R1, ADR-038): prompt
3
- * rendering, per-question enum options, answer parsing and frequency
4
- * estimation, shared by every backend that answers by drawing k samples from a
5
- * model. A backend supplies only the per-ask session hook.
6
- *
7
- * Pure by contract (R2): imports only the sibling `types` and `errors` modules —
8
- * no SDK, no workspace package, no platform API. That is what lets a driver
9
- * package outside `ts-ai-runner` build on it without a cycle.
10
- */
11
- import type { ChoiceAnswer, DecisionDriver, DecisionState, Desc, NoulAnswer, Question, ScoreAnswer } from './types';
12
- /**
13
- * Fixed instructions text. It never asks for confidence, certainty or a
14
- * probability — self-reported confidence would be fabricated calibration, which
15
- * the decision contract forbids (ADR-030).
16
- */
17
- export declare const DECISION_INSTRUCTIONS: string;
18
- /** The constrained-output schema over the whole question map (fm passes it to `fm respond --schema`). */
19
- export interface EnumSchema {
20
- type: 'object';
21
- title: string;
22
- 'x-order': string[];
23
- required: string[];
24
- additionalProperties: false;
25
- properties: Record<string, {
26
- type: 'string';
27
- enum: string[];
28
- }>;
29
- }
30
- /** One ask's sampling session; opened once per ask and closed in `finally`. */
31
- export interface SampleSession {
32
- /** Return one sample as a key → option-string record (parsed, not yet enum-checked). */
33
- sample(): Promise<Record<string, string>>;
34
- /** Release per-ask resources (temp schema file, scratch dir). Called on success and failure. */
35
- close?(): void | Promise<void>;
36
- }
37
- /** Configuration for {@link createSampledDriver}. */
38
- export interface SampledDriverOptions {
39
- /** Driver name reported through `DecisionDriver.name`. */
40
- readonly name: string;
41
- /** Samples per ask. Default: 5. Ignored when `deterministic`. Positive integer. */
42
- readonly samples?: number;
43
- /** One sample; the sampler is expected to decode greedily. Default: false. */
44
- readonly deterministic?: boolean;
45
- /** Max samples in flight. Default: 1 (sequential). Positive integer. */
46
- readonly concurrency?: number;
47
- /** Prefix used in enum-violation messages. Default: `name` (fm passes `'fm'`). */
48
- readonly sampleLabel?: string;
49
- /** Open the per-ask session. Receives the rendered texts and the validated request. */
50
- open(ctx: {
51
- instructions: string;
52
- prompt: string;
53
- questions: Record<string, Question>;
54
- state: DecisionState;
55
- model?: string;
56
- }): Promise<SampleSession>;
57
- /** Override the default {@link DECISION_INSTRUCTIONS} text. */
58
- readonly instructions?: string;
59
- }
60
- /** A {@link DecisionDriver} built on sample frequencies, with the estimator it declares (ADR-030). */
61
- export interface SampledDecisionDriver extends DecisionDriver {
62
- readonly estimator: {
63
- readonly kind: 'sample-frequency';
64
- readonly samples: number;
65
- readonly greedy: boolean;
66
- };
67
- }
68
- /** Build the enum schema over the whole question map: one call answers every key. */
69
- export declare function buildEnumSchema(questions: Record<string, Question>): EnumSchema;
70
- /** Format a {@link Desc} into prompt text: strings verbatim, structured values JSON, absence empty. */
71
- export declare function formatDesc(desc: Desc | undefined): string;
72
- /** The declared option values of a question, in declaration order (estimation + validation share this). */
73
- export declare function declaredOptions(question: Question): string[];
74
- /**
75
- * Render the positional prompt: the state as text (JSON when structured), then
76
- * one block per question key with the prompt `Desc` and its options with
77
- * descriptions — choice label keys, score level indices with the rubric text,
78
- * noul `yes`/`no` with any outcome descriptions.
79
- */
80
- export declare function buildPrompt(state: DecisionState, questions: Record<string, Question>): string;
81
- /**
82
- * Laya reference `confidence_from_probs` on the empirical distribution:
83
- * `1 − H(p) / ln(n)` over the n declared options. One-hot ⇒ 1, uniform ⇒ 0.
84
- */
85
- export declare function entropyConfidence(probabilities: number[]): number;
86
- /**
87
- * Choice frequencies over every supplied label (unsampled ⇒ 0). The answer
88
- * label is the most frequent with ties broken by label declaration order.
89
- */
90
- export declare function estimateChoice(labels: readonly string[], samples: readonly string[]): ChoiceAnswer<string>;
91
- /**
92
- * Score frequencies over the level indices `0…n-1`. The answer score is the
93
- * most frequent level with ties going to the lower level; the legend maps each
94
- * index back to its rubric description.
95
- */
96
- export declare function estimateScore(rubric: readonly Desc[], samples: readonly string[]): ScoreAnswer;
97
- /** Noul is a bare yes-probability — no `confidence` key, by contract. */
98
- export declare function estimateNoul(samples: readonly string[]): NoulAnswer;
99
- /** A parsed value outside the declared enum is a schema violation, never an answer. */
100
- export declare function requireEnumValue(parsed: Record<string, string>, key: string, allowed: readonly string[], label?: string): string;
101
- /**
102
- * Lenient answer parser for models without constrained decoding (task 0114 R6).
103
- * Tries the whole text, then the first fenced block, then the first balanced
104
- * object in prose. The result must be a flat object of string values.
105
- */
106
- export declare function extractJsonAnswer(text: string): Record<string, string>;
107
- /**
108
- * Build a sampled driver: k draws through one per-ask {@link SampleSession},
109
- * enum-checked against the declared options and reduced to sample frequencies.
110
- *
111
- * The order inside `ask` is the contract (R5): validate → render → open →
112
- * sample → enum-check → estimate, with `close` in `finally` either way.
113
- */
114
- export declare function createSampledDriver(options: SampledDriverOptions): SampledDecisionDriver;
115
- //# sourceMappingURL=sampled-driver.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sampled-driver.d.ts","sourceRoot":"","sources":["../../src/decision/sampled-driver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,KAAK,EAER,YAAY,EACZ,cAAc,EACd,aAAa,EACb,IAAI,EACJ,UAAU,EACV,QAAQ,EACR,WAAW,EACd,MAAM,SAAS,CAAC;AAEjB;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,QAGmB,CAAC;AAEtD,yGAAyG;AACzG,MAAM,WAAW,UAAU;IACvB,IAAI,EAAE,QAAQ,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,oBAAoB,EAAE,KAAK,CAAC;IAC5B,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,QAAQ,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE,CA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nostic sampled-driver core (task 0114 R1, ADR-038): prompt
3
- * rendering, per-question enum options, answer parsing and frequency
4
- * estimation, shared by every backend that answers by drawing k samples from a
5
- * model. A backend supplies only the per-ask session hook.
6
- *
7
- * Pure by contract (R2): imports only the sibling `types` and `errors` modules —
8
- * no SDK, no workspace package, no platform API. That is what lets a driver
9
- * package outside `ts-ai-runner` build on it without a cycle.
10
- */
11
- import { DecisionBackendError, DecisionRequestError } from './errors.js';
12
- /**
13
- * Fixed instructions text. It never asks for confidence, certainty or a
14
- * probability — self-reported confidence would be fabricated calibration, which
15
- * the decision contract forbids (ADR-030).
16
- */
17
- export const DECISION_INSTRUCTIONS = 'You are a decision engine. Answer every question below using only the supplied state. ' +
18
- 'For each question choose exactly one of the listed options. ' +
19
- 'Reply with the JSON object the schema requires.';
20
- /** Build the enum schema over the whole question map: one call answers every key. */
21
- export function buildEnumSchema(questions) {
22
- const properties = {};
23
- for (const [key, question] of Object.entries(questions)) {
24
- switch (question.kind) {
25
- case 'choice':
26
- properties[key] = { type: 'string', enum: Object.keys(question.labels) };
27
- break;
28
- case 'score':
29
- properties[key] = { type: 'string', enum: question.rubric.map((_, level) => String(level)) };
30
- break;
31
- case 'noul':
32
- properties[key] = { type: 'string', enum: ['yes', 'no'] };
33
- break;
34
- }
35
- }
36
- const keys = Object.keys(questions);
37
- return {
38
- type: 'object',
39
- title: 'Decision',
40
- 'x-order': keys,
41
- required: keys,
42
- additionalProperties: false,
43
- properties,
44
- };
45
- }
46
- /** Format a {@link Desc} into prompt text: strings verbatim, structured values JSON, absence empty. */
47
- export function formatDesc(desc) {
48
- if (typeof desc === 'string')
49
- return desc;
50
- if (desc === null || desc === undefined)
51
- return '';
52
- return JSON.stringify(desc);
53
- }
54
- /** The declared option values of a question, in declaration order (estimation + validation share this). */
55
- export function declaredOptions(question) {
56
- switch (question.kind) {
57
- case 'choice':
58
- return Object.keys(question.labels);
59
- case 'score':
60
- return question.rubric.map((_, level) => String(level));
61
- case 'noul':
62
- return ['yes', 'no'];
63
- }
64
- }
65
- /**
66
- * Render the positional prompt: the state as text (JSON when structured), then
67
- * one block per question key with the prompt `Desc` and its options with
68
- * descriptions — choice label keys, score level indices with the rubric text,
69
- * noul `yes`/`no` with any outcome descriptions.
70
- */
71
- export function buildPrompt(state, questions) {
72
- const parts = [];
73
- const stateText = typeof state === 'string' ? state : state === null || state === undefined ? '' : JSON.stringify(state);
74
- if (stateText.length > 0)
75
- parts.push(stateText);
76
- for (const [key, question] of Object.entries(questions)) {
77
- const lines = [];
78
- const prompt = formatDesc(question.prompt);
79
- lines.push(`Question "${key}":${prompt.length > 0 ? ` ${prompt}` : ''}`);
80
- lines.push('Options:');
81
- switch (question.kind) {
82
- case 'choice':
83
- for (const [label, desc] of Object.entries(question.labels)) {
84
- const d = formatDesc(desc);
85
- lines.push(d.length > 0 ? `- ${label}: ${d}` : `- ${label}`);
86
- }
87
- break;
88
- case 'score':
89
- question.rubric.forEach((desc, level) => {
90
- const d = formatDesc(desc);
91
- lines.push(d.length > 0 ? `- ${level}: ${d}` : `- ${level}`);
92
- });
93
- break;
94
- case 'noul': {
95
- for (const outcome of ['yes', 'no']) {
96
- const d = formatDesc(question[outcome]);
97
- lines.push(d.length > 0 ? `- ${outcome}: ${d}` : `- ${outcome}`);
98
- }
99
- break;
100
- }
101
- }
102
- parts.push(lines.join('\n'));
103
- }
104
- return parts.join('\n\n');
105
- }
106
- /**
107
- * Laya reference `confidence_from_probs` on the empirical distribution:
108
- * `1 − H(p) / ln(n)` over the n declared options. One-hot ⇒ 1, uniform ⇒ 0.
109
- */
110
- export function entropyConfidence(probabilities) {
111
- const n = probabilities.length;
112
- if (n <= 1)
113
- return 1;
114
- let entropy = 0;
115
- for (const p of probabilities) {
116
- if (p > 0)
117
- entropy -= p * Math.log(p);
118
- }
119
- return 1 - entropy / Math.log(n);
120
- }
121
- /**
122
- * Choice frequencies over every supplied label (unsampled ⇒ 0). The answer
123
- * label is the most frequent with ties broken by label declaration order.
124
- */
125
- export function estimateChoice(labels, samples) {
126
- const counts = new Map(labels.map((label) => [label, 0]));
127
- for (const sample of samples)
128
- counts.set(sample, (counts.get(sample) ?? 0) + 1);
129
- const k = samples.length;
130
- const probabilities = {};
131
- const distribution = [];
132
- let bestLabel = labels[0] ?? '';
133
- let bestCount = -1;
134
- for (const label of labels) {
135
- const count = counts.get(label) ?? 0;
136
- const probability = count / k;
137
- distribution.push(probability);
138
- probabilities[label] = probability;
139
- // Declaration order wins ties: strict `>` keeps the earlier label.
140
- if (count > bestCount) {
141
- bestCount = count;
142
- bestLabel = label;
143
- }
144
- }
145
- return {
146
- kind: 'choice',
147
- label: bestLabel,
148
- confidence: entropyConfidence(distribution),
149
- probabilities,
150
- };
151
- }
152
- /**
153
- * Score frequencies over the level indices `0…n-1`. The answer score is the
154
- * most frequent level with ties going to the lower level; the legend maps each
155
- * index back to its rubric description.
156
- */
157
- export function estimateScore(rubric, samples) {
158
- const k = samples.length;
159
- const counts = [];
160
- for (const sample of samples) {
161
- const level = Number.parseInt(sample, 10);
162
- counts[level] = (counts[level] ?? 0) + 1;
163
- }
164
- const probabilities = {};
165
- const distribution = [];
166
- let bestLevel = 0;
167
- let bestCount = -1;
168
- for (let level = 0; level < rubric.length; level++) {
169
- const count = counts[level] ?? 0;
170
- const probability = count / k;
171
- distribution.push(probability);
172
- probabilities[level] = probability;
173
- // Lower level wins ties: strict `>` keeps the smaller index.
174
- if (count > bestCount) {
175
- bestCount = count;
176
- bestLevel = level;
177
- }
178
- }
179
- const legend = {};
180
- rubric.forEach((desc, level) => {
181
- legend[level] = desc;
182
- });
183
- return {
184
- kind: 'score',
185
- score: bestLevel,
186
- confidence: entropyConfidence(distribution),
187
- legend,
188
- probabilities,
189
- };
190
- }
191
- /** Noul is a bare yes-probability — no `confidence` key, by contract. */
192
- export function estimateNoul(samples) {
193
- const yes = samples.filter((sample) => sample === 'yes').length;
194
- return { kind: 'noul', probability: yes / samples.length };
195
- }
196
- /** A parsed value outside the declared enum is a schema violation, never an answer. */
197
- export function requireEnumValue(parsed, key, allowed, label = 'sample') {
198
- const value = parsed[key];
199
- if (value === undefined || !allowed.includes(value)) {
200
- throw new DecisionBackendError(`${label} sample for '${key}' violates the schema enum: ${value === undefined ? '(missing)' : `'${value}'`}`, undefined);
201
- }
202
- return value;
203
- }
204
- /** Parse text as JSON, reporting failure instead of throwing. */
205
- function tryParse(text) {
206
- try {
207
- return { ok: true, value: JSON.parse(text) };
208
- }
209
- catch {
210
- return { ok: false };
211
- }
212
- }
213
- /**
214
- * The first balanced `{…}` substring, scanned with a string/escape-aware brace
215
- * counter so braces inside string values do not close the object early.
216
- */
217
- function firstBalancedObject(text) {
218
- for (let start = text.indexOf('{'); start !== -1; start = text.indexOf('{', start + 1)) {
219
- let depth = 0;
220
- let inString = false;
221
- let escaped = false;
222
- for (let i = start; i < text.length; i++) {
223
- const ch = text[i];
224
- if (inString) {
225
- if (escaped)
226
- escaped = false;
227
- else if (ch === '\\')
228
- escaped = true;
229
- else if (ch === '"')
230
- inString = false;
231
- continue;
232
- }
233
- if (ch === '"') {
234
- inString = true;
235
- }
236
- else if (ch === '{') {
237
- depth += 1;
238
- }
239
- else if (ch === '}') {
240
- depth -= 1;
241
- if (depth === 0) {
242
- const parsed = tryParse(text.slice(start, i + 1));
243
- if (parsed.ok)
244
- return parsed.value;
245
- break;
246
- }
247
- }
248
- }
249
- }
250
- return undefined;
251
- }
252
- /**
253
- * Lenient answer parser for models without constrained decoding (task 0114 R6).
254
- * Tries the whole text, then the first fenced block, then the first balanced
255
- * object in prose. The result must be a flat object of string values.
256
- */
257
- export function extractJsonAnswer(text) {
258
- const direct = tryParse(text.trim());
259
- let value = direct.ok ? direct.value : undefined;
260
- if (value === undefined) {
261
- const fence = /```(?:json)?\s*([\s\S]*?)```/i.exec(text);
262
- if (fence !== null) {
263
- const fenced = tryParse((fence[1] ?? '').trim());
264
- if (fenced.ok)
265
- value = fenced.value;
266
- }
267
- }
268
- if (value === undefined)
269
- value = firstBalancedObject(text);
270
- if (value === undefined) {
271
- throw new DecisionBackendError('no JSON object in sample output', undefined);
272
- }
273
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
274
- throw new DecisionBackendError(`sample output is not a JSON object: ${JSON.stringify(value)}`, undefined);
275
- }
276
- const record = {};
277
- for (const [key, entry] of Object.entries(value)) {
278
- if (typeof entry !== 'string') {
279
- throw new DecisionBackendError(`sample output has a non-string value for '${key}'`, undefined);
280
- }
281
- record[key] = entry;
282
- }
283
- return record;
284
- }
285
- /**
286
- * Build a sampled driver: k draws through one per-ask {@link SampleSession},
287
- * enum-checked against the declared options and reduced to sample frequencies.
288
- *
289
- * The order inside `ask` is the contract (R5): validate → render → open →
290
- * sample → enum-check → estimate, with `close` in `finally` either way.
291
- */
292
- export function createSampledDriver(options) {
293
- const { name, deterministic = false, sampleLabel } = options;
294
- const samples = options.samples ?? 5;
295
- const concurrency = options.concurrency ?? 1;
296
- if (!Number.isInteger(samples) || samples < 1) {
297
- throw new DecisionRequestError(`samples must be a positive integer; got ${samples}`, undefined, undefined);
298
- }
299
- if (!Number.isInteger(concurrency) || concurrency < 1) {
300
- throw new DecisionRequestError(`concurrency must be a positive integer; got ${concurrency}`, undefined, undefined);
301
- }
302
- const k = deterministic ? 1 : samples;
303
- const label = sampleLabel ?? name;
304
- return {
305
- name,
306
- estimator: { kind: 'sample-frequency', samples: k, greedy: deterministic },
307
- async ask({ state, questions, model, }) {
308
- const entries = Object.entries(questions);
309
- if (entries.length === 0) {
310
- throw new DecisionRequestError('expected a nonempty question map', undefined, undefined);
311
- }
312
- for (const [key, question] of entries) {
313
- const optionCount = declaredOptions(question).length;
314
- if (optionCount < 2) {
315
- throw new DecisionRequestError(`question '${key}' has fewer than two options (${optionCount})`, undefined, undefined);
316
- }
317
- }
318
- const instructions = options.instructions ?? DECISION_INSTRUCTIONS;
319
- const prompt = buildPrompt(state, questions);
320
- const session = await options.open({ instructions, prompt, questions, state, model });
321
- try {
322
- const draws = [];
323
- for (let start = 0; start < k; start += concurrency) {
324
- const size = Math.min(concurrency, k - start);
325
- const batch = Array.from({ length: size }, () => session.sample());
326
- // allSettled awaits the whole batch before close; the first
327
- // rejection in draw order wins, so no partial estimate escapes.
328
- const settled = await Promise.allSettled(batch);
329
- const failure = settled.find((result) => result.status === 'rejected');
330
- if (failure !== undefined)
331
- throw failure.reason;
332
- for (const result of settled) {
333
- draws.push(result.value);
334
- }
335
- }
336
- const allowed = new Map(entries.map(([key, question]) => [key, declaredOptions(question)]));
337
- const samplesByKey = new Map(entries.map(([key]) => [key, []]));
338
- for (const draw of draws) {
339
- for (const [key] of entries) {
340
- samplesByKey.get(key)?.push(requireEnumValue(draw, key, allowed.get(key) ?? [], label));
341
- }
342
- }
343
- const answers = {};
344
- for (const [key, question] of entries) {
345
- const values = samplesByKey.get(key) ?? [];
346
- switch (question.kind) {
347
- case 'choice':
348
- answers[key] = estimateChoice(Object.keys(question.labels), values);
349
- break;
350
- case 'score':
351
- answers[key] = estimateScore(question.rubric, values);
352
- break;
353
- case 'noul':
354
- answers[key] = estimateNoul(values);
355
- break;
356
- }
357
- }
358
- return answers;
359
- }
360
- finally {
361
- await session.close?.();
362
- }
363
- },
364
- };
365
- }
@@ -1,129 +0,0 @@
1
- /**
2
- * Provider-neutral decision vocabulary — deliberately not re-exported from
3
- * `@typesafe-ai/sdk`. Re-exporting the SDK's response types would bind every
4
- * caller to the vendor; the neutral names here (`kind`, `labels`, `rubric`,
5
- * `probability`) keep vendor mapping explicit and confined to the driver.
6
- * This file imports nothing — no SDK, no workspace package (boundary rule).
7
- */
8
- /** Any JSON-serializable value. */
9
- export type Json = string | number | boolean | null | Json[] | {
10
- [k: string]: Json;
11
- };
12
- /** Caller-supplied decision context: free text, a structured object, or a list. */
13
- export type DecisionState = string | Json[] | {
14
- [k: string]: Json;
15
- } | null;
16
- /** A description; `null` means "left undescribed" (e.g. a label needing no rationale). */
17
- export type Desc = string | Json[] | {
18
- [k: string]: Json;
19
- } | null;
20
- /** Pick one label from a fixed set. Labels are the answer's type parameter. */
21
- export type ChoiceQuestion<L extends string> = {
22
- kind: 'choice';
23
- prompt?: Desc;
24
- labels: Record<L, Desc>;
25
- };
26
- /** Score against a rubric; at least two levels, enforced at compile time. */
27
- export type ScoreQuestion = {
28
- kind: 'score';
29
- prompt?: Desc;
30
- rubric: readonly [Desc, Desc, ...Desc[]];
31
- };
32
- /** Binary yes/no judgment with optional per-outcome descriptions. */
33
- export type NoulQuestion = {
34
- kind: 'noul';
35
- prompt?: Desc;
36
- yes?: Desc;
37
- no?: Desc;
38
- };
39
- /** Any question the decision surface accepts. */
40
- export type Question = ChoiceQuestion<string> | ScoreQuestion | NoulQuestion;
41
- /** Selected label, calibration confidence, and a probability per label. */
42
- export type ChoiceAnswer<L extends string> = {
43
- kind: 'choice';
44
- label: L;
45
- confidence: number;
46
- probabilities: Record<L, number>;
47
- };
48
- /** Rubric score, confidence, per-level legend, and a probability per level. */
49
- export type ScoreAnswer = {
50
- kind: 'score';
51
- score: number;
52
- confidence: number;
53
- legend: Record<number, Desc>;
54
- probabilities: Record<number, number>;
55
- };
56
- /**
57
- * Bare yes-probability — no `confidence`, on purpose. The wire response
58
- * returns only a probability; synthesizing a confidence would fabricate
59
- * calibration data. The asymmetry is load-bearing: later code cannot paper
60
- * over it.
61
- */
62
- export type NoulAnswer = {
63
- kind: 'noul';
64
- probability: number;
65
- };
66
- /** Any answer the decision surface returns — discriminate on `kind`. */
67
- export type Answer = ChoiceAnswer<string> | ScoreAnswer | NoulAnswer;
68
- /** The answer type a question of shape `Q` decodes to. */
69
- export type AnswerFor<Q> = Q extends ChoiceQuestion<infer L> ? ChoiceAnswer<L> : Q extends ScoreQuestion ? ScoreAnswer : Q extends NoulQuestion ? NoulAnswer : never;
70
- /** Conditional answer record for a keyed question map. */
71
- export type AnswersFor<Q extends Record<string, Question>> = {
72
- readonly [K in keyof Q]: AnswerFor<Q[K]>;
73
- };
74
- /**
75
- * Question builders for the batch path. Namespaced under `q` because
76
- * `choice` / `score` / `noul` are already `DecisionMaker` method names.
77
- */
78
- export declare const q: {
79
- /**
80
- * Build a choice question. `const` on the type parameter keeps an inline
81
- * label map from widening to `string` — the caller keeps the union.
82
- */
83
- choice: <const L extends string>(prompt: Desc, labels: Record<L, Desc>) => ChoiceQuestion<L>;
84
- /** Build a score question from a rubric of at least two levels. */
85
- score: (prompt: Desc, rubric: readonly [Desc, Desc, ...Desc[]]) => ScoreQuestion;
86
- /** Build a yes/no question; outcomes are optional and default undescribed. */
87
- noul: (prompt?: Desc, outcomes?: {
88
- yes?: Desc;
89
- no?: Desc;
90
- }) => NoulQuestion;
91
- };
92
- /**
93
- * Answers plus the model that actually served them (P12 R3): `servedModel` is what the backend
94
- * reports it used, which can differ from the requested model under routing. Absent whenever the
95
- * driver reports none — a fallback, a local process, or an agent CLI with no model identity.
96
- */
97
- export interface DecisionAnswersMeta {
98
- answers: Record<string, Answer>;
99
- servedModel?: string;
100
- }
101
- /**
102
- * The one-method internal seam every backend driver implements. The loose
103
- * `Record<string, Answer>` return is narrowed to `AnswersFor<Q>` by a single
104
- * documented cast at the facade boundary — drivers stay trivial to write.
105
- */
106
- export interface DecisionDriver {
107
- readonly name: string;
108
- ask(req: {
109
- state: DecisionState;
110
- questions: Record<string, Question>;
111
- model?: string;
112
- }): Promise<Record<string, Answer>>;
113
- /**
114
- * `ask` plus the served model (P12 R1). Optional and additive: a driver that cannot report a
115
- * model omits it, and every caller keeps working through `ask` alone.
116
- */
117
- askWithMeta?(req: {
118
- state: DecisionState;
119
- questions: Record<string, Question>;
120
- model?: string;
121
- }): Promise<DecisionAnswersMeta>;
122
- /**
123
- * Release whatever the driver owns outside the JS heap — a warm worker process, a socket, a
124
- * pool. Optional: a driver that owns no such resource omits it. Must be safe to call more than
125
- * once, and the driver is not expected to answer after it runs.
126
- */
127
- dispose?(): void;
128
- }
129
- //# sourceMappingURL=types.d.ts.map