@gobing-ai/ts-ai-runner 0.8.8 → 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.
package/README.md CHANGED
@@ -33,7 +33,7 @@ bun add @gobing-ai/ts-ai-runner
33
33
  | `AgentEvents` / `AiRunnerProcessEvents` | Typed event maps for agent and process-level observability |
34
34
  | `AGENT_SHIMS` / `TIER1_PRIORITY` / `TIER2_AGENTS` / `DISPLAY_ORDER` | Agent registry constants |
35
35
  | `isAgentName()` | Type guard for supported agent identifiers |
36
- | `createDecisionMaker()` / `q` | Batch `ask` and single-question `choice`/`score`/`noul` decisions with provider-neutral question/answer types and a `DecisionError` taxonomy |
36
+ | agent seam | `AiRunner`, `AgentDetector`, `DoctorRunner` and the `fm` shim; the decision surface itself lives in `@gobing-ai/ts-ai-decision` |
37
37
 
38
38
  Supported agent identifiers: `claude`, `codex`, `gemini` (deprecated), `pi`, `omp`, `opencode`, `antigravity-cli`, `openclaw`, `hermes`, `grok`, `deepseek`, `fm` (text-only). The `antigravity` id is a deprecated alias of `antigravity-cli`. See [Deprecation & Aliases](#deprecation--aliases).
39
39
 
@@ -348,7 +348,7 @@ const { args } = getAgentShim('omp').getPromptCommand({
348
348
  | openclaw | ✗ (CLI `--session-id` unwired) | ✗ | degrade → fresh `agent` | ✗ | ✓ (CLI `--json`; unwired) |
349
349
  | hermes | ✗ (unverified) | ✗ | degrade → fresh `chat` | ✗ | ✗ (unverified) |
350
350
  | deepseek | ✓ (0.2.2-rc.1) | ✗ (ignored; the store is `$DSH_HOME`) | `--session-id <id>` | ✗ | ✓ (`--json`) |
351
- | fm | ✓ | ✓ | `--resume <file>` + `--save-transcript <file>` (file = `<sessionDir>/<sessionId>.json`) | ✗ (`fm chat` is interactive only) | ✗ (`--schema` needs a file; ts-decision-fm surface) |
351
+ | fm | ✓ | ✓ | `--resume <file>` + `--save-transcript <file>` (file = `<sessionDir>/<sessionId>.json`) | ✗ (`fm chat` is interactive only) | ✗ (`--schema` needs a file; the `fm-local` provider surface) |
352
352
 
353
353
  **Claude session discovery:** claude has no session-dir flag and does not accept a caller-chosen
354
354
  session id at open; the headless run's session id is discovered from the process output after the
@@ -734,47 +734,33 @@ If the agent supports an auth-status command, `getAuthCommand()` already returns
734
734
 
735
735
  After these changes, the new agent is automatically available to `AiRunner`, `AgentDetector`, `DoctorRunner`, `TeamOrchestrator`, and all downstream consumers — no further registration needed.
736
736
 
737
- ## Decision Making
737
+ ## Decision Making — moved to `@gobing-ai/ts-ai-decision`
738
738
 
739
- `createDecisionMaker()` exposes a provider-neutral LLM decision surface: ask N questions against one
740
- shared state and get typed, discriminated answers back. Questions are built with the `q` builders;
741
- answers are decoded into neutral `ChoiceAnswer` / `ScoreAnswer` / `NoulAnswer` types — no SDK type
742
- crosses this boundary.
743
-
744
- Named backends are selected with `backend:`: `laya-local` (`@gobing-ai/ts-laya-mlx`), `fm-local`
745
- (`@gobing-ai/ts-decision-fm`) and — deprecated — `typesafe` (`@gobing-ai/ts-ai-decision`). All three
746
- resolve their driver by dynamic import on first use: this package declares no dependency on any
747
- driver package (ADR-028/ADR-039); install the one you select. For typed, non-default driver options,
748
- construct the driver yourself and pass it as `driver:`.
749
-
750
- **TypeSafe moved out (ADR-039, 2026-10-19).** `createTypesafeDriver` and the pinned
751
- `@typesafe-ai/sdk` dependency now live in `@gobing-ai/ts-ai-decision`; this package keeps only the
752
- neutral contract, the validators, the sampled-driver core and `createDecisionMaker`.
739
+ Since ADR-043 this package exports **no** decision symbol. The neutral contract
740
+ (`DecisionProvider`/`DecisionMaker`, `q`, the `Decision*Error` taxonomy, the validators and the
741
+ sampled-driver core) and every provider (`typesafe`, `kev-local`, `llm-agent`, `fm-local`,
742
+ `laya-local`, `clef`, `gemini`, `openai`) live in **`@gobing-ai/ts-ai-decision`**.
753
743
 
754
744
  ```ts
755
- import { createDecisionMaker } from '@gobing-ai/ts-ai-runner';
756
- import { createTypesafeDriver } from '@gobing-ai/ts-ai-decision'; // preferred
745
+ import { createDecisionMaker, createTypesafeProvider } from '@gobing-ai/ts-ai-decision';
757
746
 
758
- const decisions = createDecisionMaker({ driver: createTypesafeDriver({ apiKey }) });
747
+ const decisions = createDecisionMaker({ provider: createTypesafeProvider({ apiKey }) });
759
748
  ```
760
749
 
761
- The `typesafe` backend name — including the implicit default — still works for one release through a
762
- deprecated dynamic import, so it now **requires `@gobing-ai/ts-ai-decision` to be installed**:
763
-
764
- - missing key → `DecisionConfigError` `TYPESAFE_API_KEY` (unchanged, and checked before the import);
765
- - package not installed → `DecisionConfigError` `TYPESAFE_BACKEND` naming the `bun add` command.
766
-
767
- The bridge is removed in the next minor. `resolveApiKey` stays exported here and is what both the
768
- bridge and the `ts-ai-decision` registry use, so `TYPESAFE_API_KEY` precedence is unchanged.
750
+ This package still supplies one thing the decision plane needs: the coding-agent seam. The
751
+ `llm-agent` provider samples any installed agent through `AiRunner`/`AgentDetector`, and
752
+ `AgentDetector` remains the detection source for `rule-engine`. See the
753
+ [ai-decision README](../ai-decision/README.md) for the contract, the eight built-ins, the registry
754
+ and the hub.
769
755
 
770
- ### Batch `ask` — many questions, one request
756
+ ### Batch `ask` — many questions, one request (reference)
771
757
 
772
758
  All questions in one `ask` call share the state and cost a single backend request:
773
759
 
774
760
  ```ts
775
- import { createDecisionMaker, q } from '@gobing-ai/ts-ai-runner';
761
+ import { createDecisionMaker, q } from '@gobing-ai/ts-ai-decision';
776
762
 
777
- const decisions = createDecisionMaker(); // reads TYPESAFE_API_KEY from the environment
763
+ const decisions = createDecisionMaker({ provider: createTypesafeProvider({ apiKey }) });
778
764
  const state = { ticket: 'T-1042', body: 'Users cannot reset their passwords.' };
779
765
 
780
766
  const answers = await decisions.ask({
@@ -795,6 +781,10 @@ answers.urgency.score; // rubric level
795
781
  answers.duplicate.probability; // yes-probability
796
782
  ```
797
783
 
784
+ `decisions.askWithMeta(req)` runs the same request and returns `{ answers, servedModel? }`,
785
+ exposing the model identifier the backend actually served when the underlying driver implements
786
+ `askWithMeta`.
787
+
798
788
  ### Single-question sugar
799
789
 
800
790
  `choice`, `score`, and `noul` are one-question convenience forms over `ask`:
@@ -820,8 +810,7 @@ else from the process environment. A missing key throws `DecisionConfigError` be
820
810
 
821
811
  ```ts
822
812
  const key = 'sk-…'; // from your secret store
823
- const explicit = createDecisionMaker({ apiKey: key }); // explicit key wins
824
- const sandboxed = createDecisionMaker({ env: { TYPESAFE_API_KEY: key } }); // injected record — the host owns the environment
813
+ const sandboxed = new DecisionMakerRegistry({ builtins: { env: { TYPESAFE_API_KEY: key } } }); // injected record — the host owns the environment
825
814
  ```
826
815
 
827
816
  Other options: `model`, `baseURL`, `timeoutMs`, `maxRetries`, and an injected `fetch` for tests. When
@@ -853,80 +842,14 @@ Applications own decision policy and evidence selection. For example, Spur can a
853
842
  `HitlResponder` to use DecisionMaker while retaining its own HITL actions and fallback behavior;
854
843
  the workflow engine itself has no dependency on ai-runner.
855
844
 
856
- ### Shared validators for external drivers
857
-
858
- Out-of-tree drivers reuse the same two validators instead of reimplementing neutral validation.
859
- Both are named exports of the main barrel:
860
-
861
- | Export | Signature | Purpose |
862
- | ------ | --------- | ------- |
863
- | `validateQuestions` | `(questions: unknown) => asserts questions is Record<string, Question>` | Rejects a malformed question map before any transport. |
864
- | `validateAnswers` | `(questions: Record<string, Question>, answers: unknown) => void` | Verifies answer names/kinds, label and level keys, bounded probabilities/confidence, normalized mass (tolerance `1e-6`) and rubric bounds. |
865
-
866
- The facade already runs both around every `ask`, so a driver that also calls them reports matching
867
- errors from its own boundary. Driver-local concerns the neutral validators do not cover (provider
868
- question/option counts, JSON-serializability of `state`, provider response caps) stay in the
869
- driver — see [`@gobing-ai/ts-decision-clef`](../decision-clef/README.md) for a worked example.
870
-
871
- ### Sampled-driver core
872
-
873
- Every backend that answers by drawing k samples from a model shares one
874
- engine-agnostic core in this package (`src/decision/sampled-driver.ts`). It
875
- imports nothing — no SDK, no workspace package, no platform API — so a driver
876
- package outside `ts-ai-runner` can build on it without a cycle. A backend
877
- supplies only the per-ask session hook; rendering, enum enforcement, parsing
878
- and frequency estimation come from the core.
879
-
880
- ```ts
881
- import { createSampledDriver, extractJsonAnswer } from '@gobing-ai/ts-ai-runner';
882
-
883
- const driver = createSampledDriver({
884
- name: 'my-backend',
885
- samples: 5, // k draws per ask; collapsed to 1 when deterministic
886
- concurrency: 1, // max draws in flight
887
- sampleLabel: 'my-backend', // prefix in enum-violation messages
888
- async open({ instructions, prompt, questions }) {
889
- const scratch = await openScratchDir();
890
- return {
891
- sample: async () => extractJsonAnswer(await runModel(instructions, prompt, scratch)),
892
- close: () => removeScratchDir(scratch),
893
- };
894
- },
895
- });
896
- ```
897
-
898
- `ask` validates the map (nonempty, at least two options per question) **before**
899
- calling `open`, draws k samples at most `concurrency` at a time, enum-checks
900
- every sample against `declaredOptions`, and always runs `close` — then reduces
901
- the draws to empirical frequencies (ADR-030). The exported helpers are
902
- `DECISION_INSTRUCTIONS`, `buildPrompt`, `buildEnumSchema`, `declaredOptions`,
903
- `formatDesc`, `requireEnumValue`, `extractJsonAnswer`, `entropyConfidence`,
904
- `estimateChoice`, `estimateScore` and `estimateNoul`.
905
-
906
- ### Adding a backend driver
907
-
908
- Additional backend drivers are the intended extension point. A driver implements only `ask` —
909
- question building, the single-question sugar, and answer typing all come from the facade:
910
-
911
- ```ts
912
- import type { Answer, DecisionDriver } from '@gobing-ai/ts-ai-runner';
913
-
914
- const myDriver: DecisionDriver = {
915
- name: 'my-backend',
916
- async ask() {
917
- const answers: Record<string, Answer> = {};
918
- // Call your backend; return one answer per key in the question map.
919
- return answers;
920
- },
921
- };
922
-
923
- const custom = createDecisionMaker({ driver: myDriver }); // no TYPESAFE_API_KEY required
924
- ```
845
+ ### Validators, the sampled-driver core and custom providers
925
846
 
926
- A driver that owns something outside the JS heap — a warm worker process, a socket, a pool — also
927
- implements the optional `dispose(): void` hook, and `createDecisionMaker` forwards it as
928
- `maker.dispose()`. It is never run against a backend that was not already resolved, and it must be
929
- safe to call more than once; the maker is not usable afterwards.
847
+ They all live in `@gobing-ai/ts-ai-decision` now: `validateQuestions`/`validateAnswers`, the
848
+ sampler core (`createSampledDriver`, `buildEnumSchema`, `extractJsonAnswer`, the estimators) and the
849
+ provider extension point. A custom provider is `DecisionProvider` from
850
+ `@gobing-ai/ts-ai-decision` passed as `createDecisionMaker({ provider })`; the optional
851
+ `askWithMeta`/`dispose` seams are documented in the
852
+ [ai-decision README](../ai-decision/README.md#adding-a-decision-backend).
930
853
 
931
854
  ## Boundary Notes
932
855
 
package/dist/index.d.ts CHANGED
@@ -3,11 +3,6 @@ export * from './agent-spec';
3
3
  export * from './agents/auth-shims';
4
4
  export * from './agents/shims';
5
5
  export * from './ai-runner';
6
- export * from './decision/decision-maker';
7
- export * from './decision/errors';
8
- export * from './decision/sampled-driver';
9
- export * from './decision/types';
10
- export * from './decision/validation';
11
6
  export * from './doctor-runner';
12
7
  export * from './events';
13
8
  export * from './identity';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC;AACpC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,sBAAsB,CAAC;AACrC,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC;AACpC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,sBAAsB,CAAC;AACrC,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -3,11 +3,6 @@ export * from './agent-spec.js';
3
3
  export * from './agents/auth-shims.js';
4
4
  export * from './agents/shims.js';
5
5
  export * from './ai-runner.js';
6
- export * from './decision/decision-maker.js';
7
- export * from './decision/errors.js';
8
- export * from './decision/sampled-driver.js';
9
- export * from './decision/types.js';
10
- export * from './decision/validation.js';
11
6
  export * from './doctor-runner.js';
12
7
  export * from './events.js';
13
8
  export * from './identity.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gobing-ai/ts-ai-runner",
3
- "version": "0.8.8",
3
+ "version": "0.9.0",
4
4
  "description": "@gobing-ai/ts-ai-runner — Coding-agent shims, detection, doctor checks, and prompt execution.",
5
5
  "keywords": [
6
6
  "typescript",
@@ -51,12 +51,12 @@
51
51
  "release": "echo 'Manual publish is disabled. Releases go through GitHub Actions via Trusted Publishing — push a tag: git tag @gobing-ai/ts-ai-runner-v<version> && git push --tags' && exit 1"
52
52
  },
53
53
  "dependencies": {
54
- "@gobing-ai/ts-infra": "^0.8.8",
55
- "@gobing-ai/ts-runtime": "^0.8.8"
54
+ "@gobing-ai/ts-infra": "^0.9.0",
55
+ "@gobing-ai/ts-runtime": "^0.9.0"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@types/bun": "1.4.3",
59
- "@gobing-ai/ts-db": "^0.8.8"
59
+ "@gobing-ai/ts-db": "^0.9.0"
60
60
  },
61
61
  "publishConfig": {
62
62
  "access": "public"
package/src/index.ts CHANGED
@@ -3,11 +3,6 @@ export * from './agent-spec';
3
3
  export * from './agents/auth-shims';
4
4
  export * from './agents/shims';
5
5
  export * from './ai-runner';
6
- export * from './decision/decision-maker';
7
- export * from './decision/errors';
8
- export * from './decision/sampled-driver';
9
- export * from './decision/types';
10
- export * from './decision/validation';
11
6
  export * from './doctor-runner';
12
7
  export * from './events';
13
8
  export * from './identity';
@@ -1,104 +0,0 @@
1
- import type { AnswersFor, ChoiceAnswer, DecisionDriver, DecisionState, Desc, NoulAnswer, Question, ScoreAnswer } from './types';
2
- /** Public decision surface: batch `ask` plus the three single-question sugar methods. */
3
- export interface DecisionMaker {
4
- /** Name of the backing driver (e.g. `"typesafe"`, or a custom driver's name). */
5
- readonly driver: string;
6
- /** Evaluate N named questions against one shared state in a single driver request. */
7
- ask<const Q extends Record<string, Question>>(req: {
8
- state: DecisionState;
9
- questions: Q;
10
- model?: string;
11
- }): Promise<AnswersFor<Q>>;
12
- /**
13
- * `ask` plus the model the backend actually served (P12 R1/R2), or no `servedModel` when the
14
- * driver cannot report one. Optional: a maker object registered directly need not implement it,
15
- * and `createDecisionMaker` always does. Validation is identical on both paths.
16
- */
17
- askWithMeta?<const Q extends Record<string, Question>>(req: {
18
- state: DecisionState;
19
- questions: Q;
20
- model?: string;
21
- }): Promise<{
22
- answers: AnswersFor<Q>;
23
- servedModel?: string;
24
- }>;
25
- /** Pick one label. Sugar over `ask` with exactly one choice question. */
26
- choice<const L extends string>(state: DecisionState, prompt: Desc, labels: Record<L, Desc>): Promise<ChoiceAnswer<L>>;
27
- /** Score against a rubric. Sugar over `ask` with exactly one score question. */
28
- score(state: DecisionState, prompt: Desc, rubric: readonly [Desc, Desc, ...Desc[]]): Promise<ScoreAnswer>;
29
- /** Yes/no judgment. Sugar over `ask` with exactly one noul question. */
30
- noul(state: DecisionState, prompt?: Desc, outcomes?: {
31
- yes?: Desc;
32
- no?: Desc;
33
- }): Promise<NoulAnswer>;
34
- /**
35
- * Release the driver's own resources (a warm worker process, a socket, a pool), if it owns any.
36
- * Optional: a driver that owns nothing omits it. Never constructs a driver just to dispose it,
37
- * is safe to call more than once, and leaves the maker unusable — resolve it again instead.
38
- */
39
- dispose?(): void | Promise<void>;
40
- }
41
- /** Available named decision backends (task 0080, task 0085). */
42
- export type DecisionBackend = 'typesafe' | 'laya-local' | 'fm-local';
43
- /** Factory options: driver selection, credential injection, and transport tuning. */
44
- export interface DecisionMakerOptions {
45
- /** Custom driver — when supplied, `backend` is ignored, no default driver is constructed and no key is required. */
46
- driver?: DecisionDriver;
47
- /**
48
- * Named backend selector. Default: `'typesafe'`. Resolution order: `driver` → `backend` → `'typesafe'`.
49
- *
50
- * @deprecated `'typesafe'` (including the implicit default) now loads its driver from
51
- * `@gobing-ai/ts-ai-decision` through a dynamic import, so it requires that package to be
52
- * installed. Prefer `driver: createTypesafeDriver(...)` imported from `@gobing-ai/ts-ai-decision`;
53
- * this bridge is removed in the next minor (ADR-039).
54
- */
55
- backend?: DecisionBackend;
56
- /** Injected env record; defaults to `getProcessEnv()` (doctor-runner convention). */
57
- env?: Record<string, string | undefined>;
58
- /** Explicit key — wins over `env.TYPESAFE_API_KEY`. */
59
- apiKey?: string;
60
- /** Forwarded to the TypeSafe driver; default is the SDK's model default. */
61
- model?: string;
62
- baseURL?: string;
63
- timeoutMs?: number;
64
- maxRetries?: number;
65
- /** Injected fetch for tests. */
66
- fetch?: typeof fetch;
67
- [key: string]: unknown;
68
- }
69
- /**
70
- * Resolve the key per R7: `options.apiKey ?? (options.env ?? getProcessEnv()).TYPESAFE_API_KEY`.
71
- * Throws before any driver construction or request.
72
- */
73
- export declare function resolveApiKey(options: DecisionMakerOptions): string;
74
- /**
75
- * @internal Exported for task 0086 R9 branch tests: `importModule` lets tests
76
- * simulate package-import failures that cannot occur in-workspace (workspace
77
- * links always resolve).
78
- */
79
- export declare function resolveLayaDriver(options: DecisionMakerOptions, importModule?: (specifier: string) => Promise<unknown>): Promise<DecisionDriver>;
80
- /**
81
- * Resolve the `typesafe` driver from `@gobing-ai/ts-ai-decision` (task 0116 R5, ADR-039).
82
- *
83
- * The driver moved out of this package, which is now the contract-only surface. The key is
84
- * resolved FIRST so a missing key keeps its exact pre-move error and no import is attempted.
85
- *
86
- * @internal Exported for the branch tests; see {@link resolveLayaDriver}.
87
- */
88
- export declare function resolveTypesafeDriver(options: DecisionMakerOptions, importModule?: (specifier: string) => Promise<unknown>): Promise<DecisionDriver>;
89
- /** @internal Exported for task 0086 R9 branch tests; see {@link resolveLayaDriver}. */
90
- export declare function resolveFmDriver(options: DecisionMakerOptions, importModule?: (specifier: string) => Promise<unknown>): Promise<DecisionDriver>;
91
- /**
92
- * A maker built by {@link createDecisionMaker}: the optional meta seam is always implemented, so a
93
- * caller that wants the served model calls it without a presence check. A maker object registered
94
- * directly (a test double, a foreign implementation) keeps the optional shape.
95
- */
96
- export type DecisionMakerWithMeta = DecisionMaker & {
97
- askWithMeta: NonNullable<DecisionMaker['askWithMeta']>;
98
- };
99
- /**
100
- * Build a DecisionMaker. `options.driver` wins when supplied; otherwise `options.backend`
101
- * resolves the driver (default `'typesafe'`). The driver is constructed lazily on first use.
102
- */
103
- export declare function createDecisionMaker(options?: DecisionMakerOptions): DecisionMakerWithMeta;
104
- //# sourceMappingURL=decision-maker.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"decision-maker.d.ts","sourceRoot":"","sources":["../../src/decision/decision-maker.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACR,UAAU,EACV,YAAY,EACZ,cAAc,EACd,aAAa,EACb,IAAI,EACJ,UAAU,EACV,QAAQ,EACR,WAAW,EACd,MAAM,SAAS,CAAC;AAIjB,yFAAyF;AACzF,MAAM,WAAW,aAAa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,uFAAuF;AACvF,wBAAsB,eAAe,CACjC,OAAO,EAAE,oBAAoB,EAC7B,YAAY,GAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAoC,GACzF,OAAO,CAAC,cAAc,CAAC,CAkBzB;AAED;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG,aAAa,GAAG;IAChD,WAAW,EAAE,WAAW,CAAC,aAAa,CAAC,aAAa,CAAC,CAAC,CAAC;CAC1D,CAAC;AAEF;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,oBAAyB,GAAG,qBAAqB,CAyE7F"}
@@ -1,156 +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.js';
9
- import { q } from './types.js';
10
- import { validateAnswers, validateQuestions } from './validation.js';
11
- /**
12
- * Resolve the key per R7: `options.apiKey ?? (options.env ?? getProcessEnv()).TYPESAFE_API_KEY`.
13
- * Throws before any driver construction or request.
14
- */
15
- export function resolveApiKey(options) {
16
- const env = options.env ?? getProcessEnv();
17
- const apiKey = options.apiKey ?? env.TYPESAFE_API_KEY;
18
- if (!apiKey) {
19
- throw new DecisionConfigError('Missing TYPESAFE_API_KEY — set it in the environment or pass options.apiKey.', 'TYPESAFE_API_KEY');
20
- }
21
- return apiKey;
22
- }
23
- const LAYA_DRIVER_PACKAGE = '@gobing-ai/ts-laya-mlx';
24
- /**
25
- * @internal Exported for task 0086 R9 branch tests: `importModule` lets tests
26
- * simulate package-import failures that cannot occur in-workspace (workspace
27
- * links always resolve).
28
- */
29
- export async function resolveLayaDriver(options, importModule = (specifier) => import(specifier)) {
30
- // Task 0086 R9: only the IMPORT is translated to the install-hint error;
31
- // construction errors from the factory itself propagate unchanged so the
32
- // caller sees the real cause instead of a misleading install message.
33
- let mod;
34
- try {
35
- mod = (await importModule(LAYA_DRIVER_PACKAGE));
36
- }
37
- catch (cause) {
38
- throw new DecisionConfigError(`The 'laya-local' backend requires '${LAYA_DRIVER_PACKAGE}' to be installed; install it with 'bun add ${LAYA_DRIVER_PACKAGE}'`, 'LAYA_BACKEND', { cause });
39
- }
40
- if (typeof mod.createLayaDriver !== 'function') {
41
- throw new DecisionConfigError(`Module '${LAYA_DRIVER_PACKAGE}' does not export createLayaDriver`, 'LAYA_BACKEND');
42
- }
43
- return mod.createLayaDriver(options);
44
- }
45
- const TYPESAFE_DRIVER_PACKAGE = '@gobing-ai/ts-ai-decision';
46
- /**
47
- * Resolve the `typesafe` driver from `@gobing-ai/ts-ai-decision` (task 0116 R5, ADR-039).
48
- *
49
- * The driver moved out of this package, which is now the contract-only surface. The key is
50
- * resolved FIRST so a missing key keeps its exact pre-move error and no import is attempted.
51
- *
52
- * @internal Exported for the branch tests; see {@link resolveLayaDriver}.
53
- */
54
- export async function resolveTypesafeDriver(options, importModule = (specifier) => import(specifier)) {
55
- const apiKey = resolveApiKey(options);
56
- let mod;
57
- try {
58
- mod = (await importModule(TYPESAFE_DRIVER_PACKAGE));
59
- }
60
- catch (cause) {
61
- throw new DecisionConfigError(`The 'typesafe' backend requires '${TYPESAFE_DRIVER_PACKAGE}' to be installed; install it with 'bun add ${TYPESAFE_DRIVER_PACKAGE}'`, 'TYPESAFE_BACKEND', { cause });
62
- }
63
- if (typeof mod.createTypesafeDriver !== 'function') {
64
- throw new DecisionConfigError(`Module '${TYPESAFE_DRIVER_PACKAGE}' does not export createTypesafeDriver`, 'TYPESAFE_BACKEND');
65
- }
66
- return mod.createTypesafeDriver({
67
- apiKey,
68
- model: options.model,
69
- baseURL: options.baseURL,
70
- timeoutMs: options.timeoutMs,
71
- maxRetries: options.maxRetries,
72
- fetch: options.fetch,
73
- });
74
- }
75
- const FM_DRIVER_PACKAGE = '@gobing-ai/ts-decision-fm';
76
- /** @internal Exported for task 0086 R9 branch tests; see {@link resolveLayaDriver}. */
77
- export async function resolveFmDriver(options, importModule = (specifier) => import(specifier)) {
78
- // Task 0086 R9: same import/construction split as laya above.
79
- let mod;
80
- try {
81
- mod = (await importModule(FM_DRIVER_PACKAGE));
82
- }
83
- catch (cause) {
84
- throw new DecisionConfigError(`The 'fm-local' backend requires '${FM_DRIVER_PACKAGE}' to be installed; install it with 'bun add ${FM_DRIVER_PACKAGE}'`, 'FM_BACKEND', { cause });
85
- }
86
- if (typeof mod.createFmDriver !== 'function') {
87
- throw new DecisionConfigError(`Module '${FM_DRIVER_PACKAGE}' does not export createFmDriver`, 'FM_BACKEND');
88
- }
89
- return mod.createFmDriver(options);
90
- }
91
- /**
92
- * Build a DecisionMaker. `options.driver` wins when supplied; otherwise `options.backend`
93
- * resolves the driver (default `'typesafe'`). The driver is constructed lazily on first use.
94
- */
95
- export function createDecisionMaker(options = {}) {
96
- let resolvedDriver;
97
- const getDriver = async () => {
98
- if (options.driver)
99
- return options.driver;
100
- if (resolvedDriver)
101
- return resolvedDriver;
102
- const backend = options.backend ?? 'typesafe';
103
- if (backend === 'typesafe') {
104
- resolvedDriver = await resolveTypesafeDriver(options);
105
- return resolvedDriver;
106
- }
107
- if (backend === 'laya-local') {
108
- resolvedDriver = await resolveLayaDriver(options);
109
- return resolvedDriver;
110
- }
111
- if (backend === 'fm-local') {
112
- resolvedDriver = await resolveFmDriver(options);
113
- return resolvedDriver;
114
- }
115
- throw new DecisionConfigError(`Unknown decision backend '${backend}'`, 'backend');
116
- };
117
- const ask = async (req) => {
118
- // R3: the questions map reaches the driver untouched — same reference,
119
- // no reordering, renaming, or dropping.
120
- const driver = await getDriver();
121
- validateQuestions(req.questions);
122
- const answers = await driver.ask(req);
123
- validateAnswers(req.questions, answers);
124
- // Runtime validation above establishes each question/answer correspondence.
125
- return answers;
126
- };
127
- const askWithMeta = async (req) => {
128
- const driver = await getDriver();
129
- validateQuestions(req.questions);
130
- // R2: prefer the driver's meta seam and fall back to plain `ask` — the answer validation
131
- // below is shared, so a driver that cannot report a model behaves exactly as it does today.
132
- const meta = driver.askWithMeta ? await driver.askWithMeta(req) : { answers: await driver.ask(req) };
133
- validateAnswers(req.questions, meta.answers);
134
- // Runtime validation above establishes each question/answer correspondence.
135
- const answers = meta.answers;
136
- // Absent, never an explicit undefined: consumers distinguish "no model reported" by absense.
137
- return meta.servedModel === undefined ? { answers } : { answers, servedModel: meta.servedModel };
138
- };
139
- return {
140
- driver: options.driver?.name ?? options.backend ?? 'typesafe',
141
- // Only an injected or already-resolved driver is a candidate: running the lazy factory
142
- // here would construct a backend (and, for the local ones, spawn a process) purely to
143
- // close it.
144
- dispose: async () => {
145
- await (options.driver ?? resolvedDriver)?.dispose?.();
146
- },
147
- ask,
148
- askWithMeta,
149
- // R4/R5: each sugar method is one `ask` with exactly one `q.*` question,
150
- // unwrapping the single answer — no second driver call, no duplicated
151
- // request assembly.
152
- choice: (state, prompt, labels) => ask({ state, questions: { question: q.choice(prompt, labels) } }).then((a) => a.question),
153
- score: (state, prompt, rubric) => ask({ state, questions: { question: q.score(prompt, rubric) } }).then((a) => a.question),
154
- noul: (state, prompt, outcomes) => ask({ state, questions: { question: q.noul(prompt, outcomes) } }).then((a) => a.question),
155
- };
156
- }
@@ -1,62 +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 declare class DecisionError extends Error {
8
- constructor(message: string, options?: {
9
- cause?: unknown;
10
- });
11
- }
12
- /** Missing configuration — e.g. no `TYPESAFE_API_KEY` in the injected env. Carries the variable name. */
13
- export declare class DecisionConfigError extends DecisionError {
14
- readonly variable: string;
15
- constructor(message: string, variable: string, options?: {
16
- cause?: unknown;
17
- });
18
- }
19
- /** Authentication or permission failure upstream. Carries the HTTP status. */
20
- export declare class DecisionAuthError extends DecisionError {
21
- readonly status: number | undefined;
22
- constructor(message: string, status: number | undefined, options?: {
23
- cause?: unknown;
24
- });
25
- }
26
- /** Rate limited upstream. Carries the status and the parsed retry-after hint. */
27
- export declare class DecisionRateLimitError extends DecisionError {
28
- readonly status: number | undefined;
29
- readonly retryAfterMs: number | undefined;
30
- constructor(message: string, status: number | undefined, retryAfterMs: number | undefined, options?: {
31
- cause?: unknown;
32
- });
33
- }
34
- /** Request timed out. Carries the configured timeout in milliseconds. */
35
- export declare class DecisionTimeoutError extends DecisionError {
36
- readonly timeoutMs: number | undefined;
37
- constructor(message: string, timeoutMs: number | undefined, options?: {
38
- cause?: unknown;
39
- });
40
- }
41
- /** The backend was unreachable. Carries the underlying cause. */
42
- export declare class DecisionConnectionError extends DecisionError {
43
- constructor(message: string, options?: {
44
- cause?: unknown;
45
- });
46
- }
47
- /** The request was rejected as malformed (4xx other than auth/rate-limit). Carries status and a body summary. */
48
- export declare class DecisionRequestError extends DecisionError {
49
- readonly status: number | undefined;
50
- readonly bodySummary: string | undefined;
51
- constructor(message: string, status: number | undefined, bodySummary: string | undefined, options?: {
52
- cause?: unknown;
53
- });
54
- }
55
- /** Upstream server failure (5xx). Carries the HTTP status. */
56
- export declare class DecisionBackendError extends DecisionError {
57
- readonly status: number | undefined;
58
- constructor(message: string, status: number | undefined, options?: {
59
- cause?: unknown;
60
- });
61
- }
62
- //# sourceMappingURL=errors.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/decision/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,mDAAmD;AACnD,qBAAa,aAAc,SAAQ,KAAK;gBACxB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE;CAI7D;AAED,yGAAyG;AACzG,qBAAa,mBAAoB,SAAQ,aAAa;IAG9C,QAAQ,CAAC,QAAQ,EAAE,MAA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