@gobing-ai/ts-ai-runner 0.8.9 → 0.9.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.
- package/README.md +29 -106
- package/dist/index.d.ts +0 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -5
- package/package.json +4 -4
- package/src/index.ts +0 -5
- package/dist/decision/decision-maker.d.ts +0 -104
- package/dist/decision/decision-maker.d.ts.map +0 -1
- package/dist/decision/decision-maker.js +0 -156
- package/dist/decision/errors.d.ts +0 -62
- package/dist/decision/errors.d.ts.map +0 -1
- package/dist/decision/errors.js +0 -70
- package/dist/decision/sampled-driver.d.ts +0 -115
- package/dist/decision/sampled-driver.d.ts.map +0 -1
- package/dist/decision/sampled-driver.js +0 -365
- package/dist/decision/types.d.ts +0 -129
- package/dist/decision/types.d.ts.map +0 -1
- package/dist/decision/types.js +0 -34
- package/dist/decision/validation.d.ts +0 -6
- package/dist/decision/validation.d.ts.map +0 -1
- package/dist/decision/validation.js +0 -99
- package/src/decision/decision-maker.ts +0 -296
- package/src/decision/errors.ts +0 -88
- package/src/decision/sampled-driver.ts +0 -454
- package/src/decision/types.ts +0 -136
- package/src/decision/validation.ts +0 -110
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/decision/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,mCAAmC;AACnC,MAAM,MAAM,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,IAAI,EAAE,GAAG;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC;AAErF,mFAAmF;AACnF,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,IAAI,EAAE,GAAG;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,GAAG,IAAI,CAAC;AAE3E,0FAA0F;AAC1F,MAAM,MAA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AM,CAAC,CAAC;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,GAAG,EAAE;QACL,KAAK,EAAE,aAAa,CAAC;QACrB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACpC,KAAK,CAAC,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACpC;;;OAGG;IACH,WAAW,CAAC,CAAC,GAAG,EAAE;QACd,KAAK,EAAE,aAAa,CAAC;QACrB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACpC,KAAK,CAAC,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACjC;;;;OAIG;IACH,OAAO,CAAC,IAAI,IAAI,CAAC;CACpB"}
|
package/dist/decision/types.js
DELETED
|
@@ -1,34 +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
|
-
/**
|
|
9
|
-
* Question builders for the batch path. Namespaced under `q` because
|
|
10
|
-
* `choice` / `score` / `noul` are already `DecisionMaker` method names.
|
|
11
|
-
*/
|
|
12
|
-
export const q = {
|
|
13
|
-
/**
|
|
14
|
-
* Build a choice question. `const` on the type parameter keeps an inline
|
|
15
|
-
* label map from widening to `string` — the caller keeps the union.
|
|
16
|
-
*/
|
|
17
|
-
choice: (prompt, labels) => ({
|
|
18
|
-
kind: 'choice',
|
|
19
|
-
prompt,
|
|
20
|
-
labels,
|
|
21
|
-
}),
|
|
22
|
-
/** Build a score question from a rubric of at least two levels. */
|
|
23
|
-
score: (prompt, rubric) => ({
|
|
24
|
-
kind: 'score',
|
|
25
|
-
prompt,
|
|
26
|
-
rubric,
|
|
27
|
-
}),
|
|
28
|
-
/** Build a yes/no question; outcomes are optional and default undescribed. */
|
|
29
|
-
noul: (prompt, outcomes) => ({
|
|
30
|
-
kind: 'noul',
|
|
31
|
-
prompt,
|
|
32
|
-
...outcomes,
|
|
33
|
-
}),
|
|
34
|
-
};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import type { Question } from './types';
|
|
2
|
-
/** Validate caller data before either a custom driver or the SDK consumes it. */
|
|
3
|
-
export declare function validateQuestions(questions: unknown): asserts questions is Record<string, Question>;
|
|
4
|
-
/** Verify the correspondence that permits the facade's typed answer narrowing. */
|
|
5
|
-
export declare function validateAnswers(questions: Record<string, Question>, answers: unknown): void;
|
|
6
|
-
//# sourceMappingURL=validation.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/decision/validation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAuBxC,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,SAAS,IAAI,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAoCnG;AAUD,kFAAkF;AAClF,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAqC3F"}
|
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import { DecisionBackendError, DecisionRequestError } from './errors.js';
|
|
2
|
-
/** Probability-mass tolerance: |total - 1| at or below this counts as a normalized distribution. */
|
|
3
|
-
const DISTRIBUTION_MASS_TOLERANCE = 1e-6;
|
|
4
|
-
function record(value) {
|
|
5
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
-
}
|
|
7
|
-
function json(value, ancestors = new Set()) {
|
|
8
|
-
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
9
|
-
return true;
|
|
10
|
-
if (typeof value === 'number')
|
|
11
|
-
return Number.isFinite(value);
|
|
12
|
-
if (typeof value !== 'object' || ancestors.has(value))
|
|
13
|
-
return false;
|
|
14
|
-
ancestors.add(value);
|
|
15
|
-
const valid = Object.values(value).every((entry) => json(entry, ancestors));
|
|
16
|
-
ancestors.delete(value);
|
|
17
|
-
return valid;
|
|
18
|
-
}
|
|
19
|
-
function desc(value) {
|
|
20
|
-
return (value === null || typeof value === 'string' || typeof value === 'object') && json(value);
|
|
21
|
-
}
|
|
22
|
-
/** Validate caller data before either a custom driver or the SDK consumes it. */
|
|
23
|
-
export function validateQuestions(questions) {
|
|
24
|
-
const fail = (name) => {
|
|
25
|
-
throw new DecisionRequestError(`Invalid decision question: ${name}`, undefined, undefined);
|
|
26
|
-
};
|
|
27
|
-
if (!record(questions) || Object.keys(questions).length === 0)
|
|
28
|
-
fail('expected a nonempty question map');
|
|
29
|
-
for (const [name, question] of Object.entries(questions)) {
|
|
30
|
-
if (!record(question))
|
|
31
|
-
fail(name);
|
|
32
|
-
if (question.prompt !== undefined && !desc(question.prompt))
|
|
33
|
-
fail(name);
|
|
34
|
-
switch (question.kind) {
|
|
35
|
-
case 'choice':
|
|
36
|
-
if (!record(question.labels) ||
|
|
37
|
-
Object.keys(question.labels).length === 0 ||
|
|
38
|
-
!Object.values(question.labels).every(desc))
|
|
39
|
-
fail(name);
|
|
40
|
-
break;
|
|
41
|
-
case 'score':
|
|
42
|
-
if (!Array.isArray(question.rubric) ||
|
|
43
|
-
question.rubric.length < 2 ||
|
|
44
|
-
!Array.from(question.rubric).every(desc))
|
|
45
|
-
fail(name);
|
|
46
|
-
break;
|
|
47
|
-
case 'noul':
|
|
48
|
-
if ((question.yes !== undefined && !desc(question.yes)) ||
|
|
49
|
-
(question.no !== undefined && !desc(question.no)))
|
|
50
|
-
fail(name);
|
|
51
|
-
break;
|
|
52
|
-
default:
|
|
53
|
-
fail(name);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
function bounded(value, max = 1) {
|
|
58
|
-
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= max;
|
|
59
|
-
}
|
|
60
|
-
function keysMatch(value, keys) {
|
|
61
|
-
return record(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
62
|
-
}
|
|
63
|
-
/** Verify the correspondence that permits the facade's typed answer narrowing. */
|
|
64
|
-
export function validateAnswers(questions, answers) {
|
|
65
|
-
const fail = (name) => {
|
|
66
|
-
throw new DecisionBackendError(`Invalid decision response: ${name}`, undefined);
|
|
67
|
-
};
|
|
68
|
-
if (!keysMatch(answers, Object.keys(questions)))
|
|
69
|
-
fail('answer names do not match questions');
|
|
70
|
-
for (const [name, question] of Object.entries(questions)) {
|
|
71
|
-
const answer = answers[name];
|
|
72
|
-
if (!record(answer) || answer.kind !== question.kind)
|
|
73
|
-
fail(name);
|
|
74
|
-
if (question.kind === 'noul') {
|
|
75
|
-
if (!bounded(answer.probability))
|
|
76
|
-
fail(name);
|
|
77
|
-
continue;
|
|
78
|
-
}
|
|
79
|
-
const keys = question.kind === 'choice' ? Object.keys(question.labels) : Array.from(question.rubric.keys(), String);
|
|
80
|
-
if (!bounded(answer.confidence) ||
|
|
81
|
-
!keysMatch(answer.probabilities, keys) ||
|
|
82
|
-
!Object.values(answer.probabilities).every((p) => bounded(p)))
|
|
83
|
-
fail(name);
|
|
84
|
-
if (question.kind === 'choice') {
|
|
85
|
-
if (typeof answer.label !== 'string' || !Object.hasOwn(question.labels, answer.label))
|
|
86
|
-
fail(name);
|
|
87
|
-
}
|
|
88
|
-
else if (!bounded(answer.score, question.rubric.length - 1) ||
|
|
89
|
-
!keysMatch(answer.legend, keys) ||
|
|
90
|
-
!Object.values(answer.legend).every(desc)) {
|
|
91
|
-
fail(name);
|
|
92
|
-
}
|
|
93
|
-
// Placed after the per-entry checks so their errors keep precedence; every entry is a
|
|
94
|
-
// bounded number here. Inclusive at exactly 1e-6.
|
|
95
|
-
const total = Object.values(answer.probabilities).reduce((sum, p) => sum + p, 0);
|
|
96
|
-
if (Math.abs(total - 1) > DISTRIBUTION_MASS_TOLERANCE)
|
|
97
|
-
fail(name);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
@@ -1,296 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The public decision surface — the only type callers see. `choice`, `score`,
|
|
3
|
-
* and `noul` are implemented once, here, as `ask()` with a single-entry
|
|
4
|
-
* question map; drivers implement `ask` and nothing else, so the sugar can
|
|
5
|
-
* never drift from the batch path. This file imports no SDK (R9).
|
|
6
|
-
*/
|
|
7
|
-
import { getProcessEnv } from '@gobing-ai/ts-runtime';
|
|
8
|
-
import { DecisionConfigError } from './errors';
|
|
9
|
-
import type {
|
|
10
|
-
AnswersFor,
|
|
11
|
-
ChoiceAnswer,
|
|
12
|
-
DecisionDriver,
|
|
13
|
-
DecisionState,
|
|
14
|
-
Desc,
|
|
15
|
-
NoulAnswer,
|
|
16
|
-
Question,
|
|
17
|
-
ScoreAnswer,
|
|
18
|
-
} from './types';
|
|
19
|
-
import { q } from './types';
|
|
20
|
-
import { validateAnswers, validateQuestions } from './validation';
|
|
21
|
-
|
|
22
|
-
/** Public decision surface: batch `ask` plus the three single-question sugar methods. */
|
|
23
|
-
export interface DecisionMaker {
|
|
24
|
-
/** Name of the backing driver (e.g. `"typesafe"`, or a custom driver's name). */
|
|
25
|
-
readonly driver: string;
|
|
26
|
-
/** Evaluate N named questions against one shared state in a single driver request. */
|
|
27
|
-
ask<const Q extends Record<string, Question>>(req: {
|
|
28
|
-
state: DecisionState;
|
|
29
|
-
questions: Q;
|
|
30
|
-
model?: string;
|
|
31
|
-
}): Promise<AnswersFor<Q>>;
|
|
32
|
-
/**
|
|
33
|
-
* `ask` plus the model the backend actually served (P12 R1/R2), or no `servedModel` when the
|
|
34
|
-
* driver cannot report one. Optional: a maker object registered directly need not implement it,
|
|
35
|
-
* and `createDecisionMaker` always does. Validation is identical on both paths.
|
|
36
|
-
*/
|
|
37
|
-
askWithMeta?<const Q extends Record<string, Question>>(req: {
|
|
38
|
-
state: DecisionState;
|
|
39
|
-
questions: Q;
|
|
40
|
-
model?: string;
|
|
41
|
-
}): Promise<{ answers: AnswersFor<Q>; servedModel?: string }>;
|
|
42
|
-
/** Pick one label. Sugar over `ask` with exactly one choice question. */
|
|
43
|
-
choice<const L extends string>(
|
|
44
|
-
state: DecisionState,
|
|
45
|
-
prompt: Desc,
|
|
46
|
-
labels: Record<L, Desc>,
|
|
47
|
-
): Promise<ChoiceAnswer<L>>;
|
|
48
|
-
/** Score against a rubric. Sugar over `ask` with exactly one score question. */
|
|
49
|
-
score(state: DecisionState, prompt: Desc, rubric: readonly [Desc, Desc, ...Desc[]]): Promise<ScoreAnswer>;
|
|
50
|
-
/** Yes/no judgment. Sugar over `ask` with exactly one noul question. */
|
|
51
|
-
noul(state: DecisionState, prompt?: Desc, outcomes?: { yes?: Desc; no?: Desc }): Promise<NoulAnswer>;
|
|
52
|
-
/**
|
|
53
|
-
* Release the driver's own resources (a warm worker process, a socket, a pool), if it owns any.
|
|
54
|
-
* Optional: a driver that owns nothing omits it. Never constructs a driver just to dispose it,
|
|
55
|
-
* is safe to call more than once, and leaves the maker unusable — resolve it again instead.
|
|
56
|
-
*/
|
|
57
|
-
dispose?(): void | Promise<void>;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** Available named decision backends (task 0080, task 0085). */
|
|
61
|
-
export type DecisionBackend = 'typesafe' | 'laya-local' | 'fm-local';
|
|
62
|
-
|
|
63
|
-
/** Factory options: driver selection, credential injection, and transport tuning. */
|
|
64
|
-
export interface DecisionMakerOptions {
|
|
65
|
-
/** Custom driver — when supplied, `backend` is ignored, no default driver is constructed and no key is required. */
|
|
66
|
-
driver?: DecisionDriver;
|
|
67
|
-
/**
|
|
68
|
-
* Named backend selector. Default: `'typesafe'`. Resolution order: `driver` → `backend` → `'typesafe'`.
|
|
69
|
-
*
|
|
70
|
-
* @deprecated `'typesafe'` (including the implicit default) now loads its driver from
|
|
71
|
-
* `@gobing-ai/ts-ai-decision` through a dynamic import, so it requires that package to be
|
|
72
|
-
* installed. Prefer `driver: createTypesafeDriver(...)` imported from `@gobing-ai/ts-ai-decision`;
|
|
73
|
-
* this bridge is removed in the next minor (ADR-039).
|
|
74
|
-
*/
|
|
75
|
-
backend?: DecisionBackend;
|
|
76
|
-
/** Injected env record; defaults to `getProcessEnv()` (doctor-runner convention). */
|
|
77
|
-
env?: Record<string, string | undefined>;
|
|
78
|
-
/** Explicit key — wins over `env.TYPESAFE_API_KEY`. */
|
|
79
|
-
apiKey?: string;
|
|
80
|
-
/** Forwarded to the TypeSafe driver; default is the SDK's model default. */
|
|
81
|
-
model?: string;
|
|
82
|
-
baseURL?: string;
|
|
83
|
-
timeoutMs?: number;
|
|
84
|
-
maxRetries?: number;
|
|
85
|
-
/** Injected fetch for tests. */
|
|
86
|
-
fetch?: typeof fetch;
|
|
87
|
-
[key: string]: unknown;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Resolve the key per R7: `options.apiKey ?? (options.env ?? getProcessEnv()).TYPESAFE_API_KEY`.
|
|
92
|
-
* Throws before any driver construction or request.
|
|
93
|
-
*/
|
|
94
|
-
export function resolveApiKey(options: DecisionMakerOptions): string {
|
|
95
|
-
const env = options.env ?? getProcessEnv();
|
|
96
|
-
const apiKey = options.apiKey ?? env.TYPESAFE_API_KEY;
|
|
97
|
-
if (!apiKey) {
|
|
98
|
-
throw new DecisionConfigError(
|
|
99
|
-
'Missing TYPESAFE_API_KEY — set it in the environment or pass options.apiKey.',
|
|
100
|
-
'TYPESAFE_API_KEY',
|
|
101
|
-
);
|
|
102
|
-
}
|
|
103
|
-
return apiKey;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const LAYA_DRIVER_PACKAGE = '@gobing-ai/ts-laya-mlx';
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* @internal Exported for task 0086 R9 branch tests: `importModule` lets tests
|
|
110
|
-
* simulate package-import failures that cannot occur in-workspace (workspace
|
|
111
|
-
* links always resolve).
|
|
112
|
-
*/
|
|
113
|
-
export async function resolveLayaDriver(
|
|
114
|
-
options: DecisionMakerOptions,
|
|
115
|
-
importModule: (specifier: string) => Promise<unknown> = (specifier) => import(specifier),
|
|
116
|
-
): Promise<DecisionDriver> {
|
|
117
|
-
// Task 0086 R9: only the IMPORT is translated to the install-hint error;
|
|
118
|
-
// construction errors from the factory itself propagate unchanged so the
|
|
119
|
-
// caller sees the real cause instead of a misleading install message.
|
|
120
|
-
let mod: { createLayaDriver?: (opts?: unknown) => DecisionDriver };
|
|
121
|
-
try {
|
|
122
|
-
mod = (await importModule(LAYA_DRIVER_PACKAGE)) as {
|
|
123
|
-
createLayaDriver?: (opts?: unknown) => DecisionDriver;
|
|
124
|
-
};
|
|
125
|
-
} catch (cause) {
|
|
126
|
-
throw new DecisionConfigError(
|
|
127
|
-
`The 'laya-local' backend requires '${LAYA_DRIVER_PACKAGE}' to be installed; install it with 'bun add ${LAYA_DRIVER_PACKAGE}'`,
|
|
128
|
-
'LAYA_BACKEND',
|
|
129
|
-
{ cause },
|
|
130
|
-
);
|
|
131
|
-
}
|
|
132
|
-
if (typeof mod.createLayaDriver !== 'function') {
|
|
133
|
-
throw new DecisionConfigError(
|
|
134
|
-
`Module '${LAYA_DRIVER_PACKAGE}' does not export createLayaDriver`,
|
|
135
|
-
'LAYA_BACKEND',
|
|
136
|
-
);
|
|
137
|
-
}
|
|
138
|
-
return mod.createLayaDriver(options);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
const TYPESAFE_DRIVER_PACKAGE = '@gobing-ai/ts-ai-decision';
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Resolve the `typesafe` driver from `@gobing-ai/ts-ai-decision` (task 0116 R5, ADR-039).
|
|
145
|
-
*
|
|
146
|
-
* The driver moved out of this package, which is now the contract-only surface. The key is
|
|
147
|
-
* resolved FIRST so a missing key keeps its exact pre-move error and no import is attempted.
|
|
148
|
-
*
|
|
149
|
-
* @internal Exported for the branch tests; see {@link resolveLayaDriver}.
|
|
150
|
-
*/
|
|
151
|
-
export async function resolveTypesafeDriver(
|
|
152
|
-
options: DecisionMakerOptions,
|
|
153
|
-
importModule: (specifier: string) => Promise<unknown> = (specifier) => import(specifier),
|
|
154
|
-
): Promise<DecisionDriver> {
|
|
155
|
-
const apiKey = resolveApiKey(options);
|
|
156
|
-
let mod: { createTypesafeDriver?: (opts?: unknown) => DecisionDriver };
|
|
157
|
-
try {
|
|
158
|
-
mod = (await importModule(TYPESAFE_DRIVER_PACKAGE)) as {
|
|
159
|
-
createTypesafeDriver?: (opts?: unknown) => DecisionDriver;
|
|
160
|
-
};
|
|
161
|
-
} catch (cause) {
|
|
162
|
-
throw new DecisionConfigError(
|
|
163
|
-
`The 'typesafe' backend requires '${TYPESAFE_DRIVER_PACKAGE}' to be installed; install it with 'bun add ${TYPESAFE_DRIVER_PACKAGE}'`,
|
|
164
|
-
'TYPESAFE_BACKEND',
|
|
165
|
-
{ cause },
|
|
166
|
-
);
|
|
167
|
-
}
|
|
168
|
-
if (typeof mod.createTypesafeDriver !== 'function') {
|
|
169
|
-
throw new DecisionConfigError(
|
|
170
|
-
`Module '${TYPESAFE_DRIVER_PACKAGE}' does not export createTypesafeDriver`,
|
|
171
|
-
'TYPESAFE_BACKEND',
|
|
172
|
-
);
|
|
173
|
-
}
|
|
174
|
-
return mod.createTypesafeDriver({
|
|
175
|
-
apiKey,
|
|
176
|
-
model: options.model,
|
|
177
|
-
baseURL: options.baseURL,
|
|
178
|
-
timeoutMs: options.timeoutMs,
|
|
179
|
-
maxRetries: options.maxRetries,
|
|
180
|
-
fetch: options.fetch,
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
const FM_DRIVER_PACKAGE = '@gobing-ai/ts-decision-fm';
|
|
185
|
-
|
|
186
|
-
/** @internal Exported for task 0086 R9 branch tests; see {@link resolveLayaDriver}. */
|
|
187
|
-
export async function resolveFmDriver(
|
|
188
|
-
options: DecisionMakerOptions,
|
|
189
|
-
importModule: (specifier: string) => Promise<unknown> = (specifier) => import(specifier),
|
|
190
|
-
): Promise<DecisionDriver> {
|
|
191
|
-
// Task 0086 R9: same import/construction split as laya above.
|
|
192
|
-
let mod: { createFmDriver?: (opts?: unknown) => DecisionDriver };
|
|
193
|
-
try {
|
|
194
|
-
mod = (await importModule(FM_DRIVER_PACKAGE)) as {
|
|
195
|
-
createFmDriver?: (opts?: unknown) => DecisionDriver;
|
|
196
|
-
};
|
|
197
|
-
} catch (cause) {
|
|
198
|
-
throw new DecisionConfigError(
|
|
199
|
-
`The 'fm-local' backend requires '${FM_DRIVER_PACKAGE}' to be installed; install it with 'bun add ${FM_DRIVER_PACKAGE}'`,
|
|
200
|
-
'FM_BACKEND',
|
|
201
|
-
{ cause },
|
|
202
|
-
);
|
|
203
|
-
}
|
|
204
|
-
if (typeof mod.createFmDriver !== 'function') {
|
|
205
|
-
throw new DecisionConfigError(`Module '${FM_DRIVER_PACKAGE}' does not export createFmDriver`, 'FM_BACKEND');
|
|
206
|
-
}
|
|
207
|
-
return mod.createFmDriver(options);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
/**
|
|
211
|
-
* A maker built by {@link createDecisionMaker}: the optional meta seam is always implemented, so a
|
|
212
|
-
* caller that wants the served model calls it without a presence check. A maker object registered
|
|
213
|
-
* directly (a test double, a foreign implementation) keeps the optional shape.
|
|
214
|
-
*/
|
|
215
|
-
export type DecisionMakerWithMeta = DecisionMaker & {
|
|
216
|
-
askWithMeta: NonNullable<DecisionMaker['askWithMeta']>;
|
|
217
|
-
};
|
|
218
|
-
|
|
219
|
-
/**
|
|
220
|
-
* Build a DecisionMaker. `options.driver` wins when supplied; otherwise `options.backend`
|
|
221
|
-
* resolves the driver (default `'typesafe'`). The driver is constructed lazily on first use.
|
|
222
|
-
*/
|
|
223
|
-
export function createDecisionMaker(options: DecisionMakerOptions = {}): DecisionMakerWithMeta {
|
|
224
|
-
let resolvedDriver: DecisionDriver | undefined;
|
|
225
|
-
const getDriver = async (): Promise<DecisionDriver> => {
|
|
226
|
-
if (options.driver) return options.driver;
|
|
227
|
-
if (resolvedDriver) return resolvedDriver;
|
|
228
|
-
const backend = options.backend ?? 'typesafe';
|
|
229
|
-
if (backend === 'typesafe') {
|
|
230
|
-
resolvedDriver = await resolveTypesafeDriver(options);
|
|
231
|
-
return resolvedDriver;
|
|
232
|
-
}
|
|
233
|
-
if (backend === 'laya-local') {
|
|
234
|
-
resolvedDriver = await resolveLayaDriver(options);
|
|
235
|
-
return resolvedDriver;
|
|
236
|
-
}
|
|
237
|
-
if (backend === 'fm-local') {
|
|
238
|
-
resolvedDriver = await resolveFmDriver(options);
|
|
239
|
-
return resolvedDriver;
|
|
240
|
-
}
|
|
241
|
-
throw new DecisionConfigError(`Unknown decision backend '${backend}'`, 'backend');
|
|
242
|
-
};
|
|
243
|
-
|
|
244
|
-
const ask = async <const Q extends Record<string, Question>>(req: {
|
|
245
|
-
state: DecisionState;
|
|
246
|
-
questions: Q;
|
|
247
|
-
model?: string;
|
|
248
|
-
}): Promise<AnswersFor<Q>> => {
|
|
249
|
-
// R3: the questions map reaches the driver untouched — same reference,
|
|
250
|
-
// no reordering, renaming, or dropping.
|
|
251
|
-
const driver = await getDriver();
|
|
252
|
-
validateQuestions(req.questions);
|
|
253
|
-
const answers = await driver.ask(req);
|
|
254
|
-
validateAnswers(req.questions, answers);
|
|
255
|
-
// Runtime validation above establishes each question/answer correspondence.
|
|
256
|
-
return answers as AnswersFor<Q>;
|
|
257
|
-
};
|
|
258
|
-
|
|
259
|
-
const askWithMeta = async <const Q extends Record<string, Question>>(req: {
|
|
260
|
-
state: DecisionState;
|
|
261
|
-
questions: Q;
|
|
262
|
-
model?: string;
|
|
263
|
-
}): Promise<{ answers: AnswersFor<Q>; servedModel?: string }> => {
|
|
264
|
-
const driver = await getDriver();
|
|
265
|
-
validateQuestions(req.questions);
|
|
266
|
-
// R2: prefer the driver's meta seam and fall back to plain `ask` — the answer validation
|
|
267
|
-
// below is shared, so a driver that cannot report a model behaves exactly as it does today.
|
|
268
|
-
const meta = driver.askWithMeta ? await driver.askWithMeta(req) : { answers: await driver.ask(req) };
|
|
269
|
-
validateAnswers(req.questions, meta.answers);
|
|
270
|
-
// Runtime validation above establishes each question/answer correspondence.
|
|
271
|
-
const answers = meta.answers as AnswersFor<Q>;
|
|
272
|
-
// Absent, never an explicit undefined: consumers distinguish "no model reported" by absense.
|
|
273
|
-
return meta.servedModel === undefined ? { answers } : { answers, servedModel: meta.servedModel };
|
|
274
|
-
};
|
|
275
|
-
|
|
276
|
-
return {
|
|
277
|
-
driver: options.driver?.name ?? options.backend ?? 'typesafe',
|
|
278
|
-
// Only an injected or already-resolved driver is a candidate: running the lazy factory
|
|
279
|
-
// here would construct a backend (and, for the local ones, spawn a process) purely to
|
|
280
|
-
// close it.
|
|
281
|
-
dispose: async () => {
|
|
282
|
-
await (options.driver ?? resolvedDriver)?.dispose?.();
|
|
283
|
-
},
|
|
284
|
-
ask,
|
|
285
|
-
askWithMeta,
|
|
286
|
-
// R4/R5: each sugar method is one `ask` with exactly one `q.*` question,
|
|
287
|
-
// unwrapping the single answer — no second driver call, no duplicated
|
|
288
|
-
// request assembly.
|
|
289
|
-
choice: (state, prompt, labels) =>
|
|
290
|
-
ask({ state, questions: { question: q.choice(prompt, labels) } }).then((a) => a.question),
|
|
291
|
-
score: (state, prompt, rubric) =>
|
|
292
|
-
ask({ state, questions: { question: q.score(prompt, rubric) } }).then((a) => a.question),
|
|
293
|
-
noul: (state, prompt, outcomes) =>
|
|
294
|
-
ask({ state, questions: { question: q.noul(prompt, outcomes) } }).then((a) => a.question),
|
|
295
|
-
};
|
|
296
|
-
}
|
package/src/decision/errors.ts
DELETED
|
@@ -1,88 +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
|
-
|
|
7
|
-
/** Base class for every decision-surface error. */
|
|
8
|
-
export class DecisionError extends Error {
|
|
9
|
-
constructor(message: string, options?: { cause?: unknown }) {
|
|
10
|
-
super(message, options);
|
|
11
|
-
this.name = new.target.name;
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/** Missing configuration — e.g. no `TYPESAFE_API_KEY` in the injected env. Carries the variable name. */
|
|
16
|
-
export class DecisionConfigError extends DecisionError {
|
|
17
|
-
constructor(
|
|
18
|
-
message: string,
|
|
19
|
-
readonly variable: string,
|
|
20
|
-
options?: { cause?: unknown },
|
|
21
|
-
) {
|
|
22
|
-
super(message, options);
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/** Authentication or permission failure upstream. Carries the HTTP status. */
|
|
27
|
-
export class DecisionAuthError extends DecisionError {
|
|
28
|
-
constructor(
|
|
29
|
-
message: string,
|
|
30
|
-
readonly status: number | undefined,
|
|
31
|
-
options?: { cause?: unknown },
|
|
32
|
-
) {
|
|
33
|
-
super(message, options);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** Rate limited upstream. Carries the status and the parsed retry-after hint. */
|
|
38
|
-
export class DecisionRateLimitError extends DecisionError {
|
|
39
|
-
constructor(
|
|
40
|
-
message: string,
|
|
41
|
-
readonly status: number | undefined,
|
|
42
|
-
readonly retryAfterMs: number | undefined,
|
|
43
|
-
options?: { cause?: unknown },
|
|
44
|
-
) {
|
|
45
|
-
super(message, options);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** Request timed out. Carries the configured timeout in milliseconds. */
|
|
50
|
-
export class DecisionTimeoutError extends DecisionError {
|
|
51
|
-
constructor(
|
|
52
|
-
message: string,
|
|
53
|
-
readonly timeoutMs: number | undefined,
|
|
54
|
-
options?: { cause?: unknown },
|
|
55
|
-
) {
|
|
56
|
-
super(message, options);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** The backend was unreachable. Carries the underlying cause. */
|
|
61
|
-
export class DecisionConnectionError extends DecisionError {
|
|
62
|
-
constructor(message: string, options?: { cause?: unknown }) {
|
|
63
|
-
super(message, options);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** The request was rejected as malformed (4xx other than auth/rate-limit). Carries status and a body summary. */
|
|
68
|
-
export class DecisionRequestError extends DecisionError {
|
|
69
|
-
constructor(
|
|
70
|
-
message: string,
|
|
71
|
-
readonly status: number | undefined,
|
|
72
|
-
readonly bodySummary: string | undefined,
|
|
73
|
-
options?: { cause?: unknown },
|
|
74
|
-
) {
|
|
75
|
-
super(message, options);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Upstream server failure (5xx). Carries the HTTP status. */
|
|
80
|
-
export class DecisionBackendError extends DecisionError {
|
|
81
|
-
constructor(
|
|
82
|
-
message: string,
|
|
83
|
-
readonly status: number | undefined,
|
|
84
|
-
options?: { cause?: unknown },
|
|
85
|
-
) {
|
|
86
|
-
super(message, options);
|
|
87
|
-
}
|
|
88
|
-
}
|