@vite-hub/choices 0.4.1 → 0.5.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
@@ -39,11 +39,23 @@ const [error, selection] = await forecast.resolve('nord parts except vak supply'
39
39
  if (error) return handle(error)
40
40
 
41
41
  selection.supplier // { include: ['S2'], exclude: ['S1'] }
42
- selection.chart // { value: null, confidence: 0.9, ranked: [{ value: 'line', probability: 0.5 }, ...] }
42
+ selection.chart // { value: null, confidence: 0, ranked: [{ value: 'line', probability: 0.1 }, ...] }
43
43
  ```
44
44
 
45
45
  `resolve()` returns `[error, data]` and never throws. Definition errors throw when you define the choices.
46
46
 
47
+ `resolve(text, { context?, signal?, onUsage? })` takes these request options:
48
+
49
+ | Option | Meaning |
50
+ | --- | --- |
51
+ | `context` | Passed to `options` functions. |
52
+ | `signal` | Cancels the gateway request. |
53
+ | `onUsage` | Receives the model, provider, and token counts the gateway reports. Jev sends at most 60 KB of questions per request, so it can run more than once in one `resolve()`. It does not run when no question is sent or the gateway reports no usage. |
54
+
55
+ No callback does not mean that no request was sent or no tokens were used.
56
+
57
+ Each multi-select option is one question, and each non-empty single-select group is one question, except that an `infer` group with one option sends none. The `supported` check adds one question if at least one non-empty group does not infer. With one group and 100 options, multi-select sends 101 questions and single-select sends 2, or 1 with `infer: true`.
58
+
47
59
  ## The bridges
48
60
 
49
61
  | You write | We do |
@@ -64,7 +76,7 @@ options: async ({ tenantId }: { tenantId: string }) => toOptions(await loadSites
64
76
  | Option | Meaning |
65
77
  | --- | --- |
66
78
  | `multiple: true` (default) | Any number of options. The selection is `{ include, exclude }`. |
67
- | `multiple: false` | At most one option. The selection is `{ value, confidence, ranked }`. `value` is `null` below `thresholds.option`. |
79
+ | `multiple: false` | At most one option. The selection is `{ value, confidence, ranked }`. `confidence` is the probability of `value`. `value` is `null` and `confidence` is `0` below `thresholds.option`. |
68
80
  | `hints` | A short note for the model about this group. |
69
81
 
70
82
  The top-level `hints` apply to every question. Put your domain words there, such as "mtop means Make to order".
@@ -121,6 +133,19 @@ A newer request cancels the older one through `signal`, and the older result nev
121
133
 
122
134
  `thresholds.option` (0.5) decides one option. `thresholds.supported` (0.6) decides whether the text can be expressed at all. A decision model answers from the options you gave it. It cannot compare numbers or invent a value.
123
135
 
136
+ ## Test
137
+
138
+ `@vite-hub/choices/testing` has two gateways that need no key. `selectionGateway(selection)` returns the selection that you give, by group key and option value. It validates the values against the loaded groups without applying model thresholds. Leave a group out to select nothing, even when it has `infer: true`:
139
+
140
+ ```ts fragment
141
+ import { selectionGateway, unsupported } from '@vite-hub/choices/testing'
142
+
143
+ const choices = defineChoices({ gateway: selectionGateway<typeof groups>({ supplier: { include: ['S2'] }, chart: 'bar' }), groups })
144
+ await choices.resolve('anything') // [undefined, { supplier: { include: ['S2'], exclude: [] }, chart: { value: 'bar', ... } }]
145
+ ```
146
+
147
+ Pass a function, `(text, context) => selection`, to answer from the request. Return `unsupported` for `DECISIONS_R0004`, and throw for `DECISIONS_R0005`. `wordGateway()` answers by word match, for examples and local dev without a key. For a failing provider, pass `scriptedAsk()` from `@vite-hub/gateways/testing`.
148
+
124
149
  ## Inspect
125
150
 
126
151
  `choices.inspect(text)` returns the state and the questions that `resolve()` would send. Nothing leaves your server.
package/dist/cli.d.ts CHANGED
@@ -3,6 +3,7 @@ import { Diagnostic } from "nostics";
3
3
  interface HostCliRunResult {
4
4
  exitCode: number | null;
5
5
  stdout: string;
6
+ stderr?: string;
6
7
  }
7
8
  /** Runs a host CLI with an argument array and no shell, and returns its stdout. */
8
9
  type HostCliRun = (command: string, args: readonly string[], options: {
@@ -132,9 +133,7 @@ interface FoundChoices {
132
133
  name: string | undefined;
133
134
  }
134
135
  interface ListedFile {
135
- /** The exports of the file that `defineChoices()` returned. Empty when the file failed to load. */
136
136
  choices: FoundChoices[];
137
- /** Why the file did not load. */
138
137
  error?: string;
139
138
  file: string;
140
139
  }
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as choicesDiagnostics } from "./diagnostics-DTMZy54f.js";
1
+ import { t as choicesDiagnostics } from "./diagnostics-BubnKF2J.js";
2
2
  import { readFile, readdir, stat } from "node:fs/promises";
3
3
  import { relative, resolve } from "node:path";
4
4
  import { parseArgs } from "node:util";
@@ -99,7 +99,6 @@ function choicesOf(module) {
99
99
  name: value.name
100
100
  }] : []);
101
101
  }
102
- /** Loads one file the way Vite loads server code, so TypeScript and extensionless imports work. */
103
102
  async function loadModule(file, rootDir) {
104
103
  const { runnerImport } = await import("vite");
105
104
  const { module } = await runnerImport(file, {
@@ -109,7 +108,6 @@ async function loadModule(file, rootDir) {
109
108
  });
110
109
  return module;
111
110
  }
112
- /** Gateways read their keys from the environment. Add the project `.env` files without replacing set values. */
113
111
  async function loadProjectEnv(context) {
114
112
  const { loadEnv } = await import("vite");
115
113
  const mode = context.env.NODE_ENV === "production" ? "production" : "development";
@@ -237,7 +235,6 @@ async function runOne(args, context) {
237
235
  context.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
238
236
  return 0;
239
237
  }
240
- /** The fix of a usage error of these commands, or `undefined` for another error. */
241
238
  function cliFix(error) {
242
239
  return choicesDiagnostics.is(error) && error.code.startsWith("DECISIONS_CLI_") ? error.fix : void 0;
243
240
  }
@@ -4,32 +4,26 @@ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(me
4
4
  const choicesDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
5
  docsBase: "https://vitehub.dev/docs/choices/diagnostics",
6
6
  codes: {
7
- /** A `defineChoices()` definition is invalid. It throws when you define it. */
8
7
  DECISIONS_R0001: {
9
8
  ...dynamicError,
10
9
  fix: "Change the `defineChoices()` option that the message names: one of `gateway` with `ask()` or `model`, at least one group, a label on each group, and thresholds from 0 to 1."
11
10
  },
12
- /** The groups or options are over a limit, or an option is invalid. Nothing was asked. */
13
11
  DECISIONS_R0002: {
14
12
  ...dynamicError,
15
- fix: "Use fewer options, a unique value and a label on each option, and an `options` function that does not throw. `error.cause` holds the error of a failed `options` function."
13
+ fix: "Use fewer options, a list of option objects with a label and a unique text or finite number value, aliases as a list of text, and an `options` function that does not throw. `error.cause` holds the error of a failed `options` function."
16
14
  },
17
- /** The text is empty or longer than `limits.text`. Nothing was asked. */
18
15
  DECISIONS_R0003: {
19
16
  ...dynamicError,
20
17
  fix: "Pass `resolve()` a nonempty text no longer than `limits.text`."
21
18
  },
22
- /** The model says the options cannot express the text. The `supported` check is below its threshold. */
23
19
  DECISIONS_R0004: {
24
20
  ...dynamicError,
25
21
  fix: "Show a message and let the person use your normal controls, or ask with a text that the options can express."
26
22
  },
27
- /** The gateway request failed. Only trusted gateway diagnostics supply a public reason and fix. */
28
23
  DECISIONS_R0005: {
29
24
  why: ({ reason }) => reason ? `[vitehub] The gateway request failed: ${reason}` : "[vitehub] The gateway request failed.",
30
25
  fix: ({ fix }) => fix ?? "Read error.cause for the gateway error."
31
26
  },
32
- /** The model answer misses a question that was asked. */
33
27
  DECISIONS_R0006: {
34
28
  ...dynamicError,
35
29
  fix: "Call `resolve()` again, because the model left a question without an answer. A retry often helps."
@@ -41,6 +35,10 @@ const choicesDiagnostics = /*#__PURE__*/ defineDiagnostics({
41
35
  DECISIONS_CLI_CHOICES_NOT_FOUND: {
42
36
  why: ({ problem }) => problem,
43
37
  fix: "Run `vitehub choices list` to find the files and exports that call `defineChoices()`, and pass one of them to `vitehub choices run`."
38
+ },
39
+ DECISIONS_TESTING_SELECTION_INVALID: {
40
+ why: ({ problem }) => `[vitehub] ${problem}`,
41
+ fix: "Pass `selectionGateway()` as the `gateway` of `defineChoices()`. Name only its groups: an option value or `null` for a group with `multiple: false`, and `{ include, exclude }` with option values for the other groups."
44
42
  }
45
43
  }
46
44
  });
package/dist/index.d.ts CHANGED
@@ -1,142 +1,4 @@
1
- import { AiGatewayAsk, AskModel } from "@vite-hub/gateways";
2
- import { Diagnostic } from "nostics";
3
- //#region src/types.d.ts
4
- /** The value that you map back to your data. It must be unique within its group. */
5
- type ChoiceValue = string | number;
6
- /** One option of a group. `value` is yours, `label`, `aliases`, and `description` are what the model reads. */
7
- interface ChoiceOption<TValue extends ChoiceValue = ChoiceValue> {
8
- /** Other names for the option, such as codes, abbreviations, or translations. */
9
- aliases?: readonly string[];
10
- /** What the option is about. An `infer` group needs it to choose an option that the text does not name. */
11
- description?: string;
12
- /** What people call the option. */
13
- label: string;
14
- /** Your id for the option. It comes back in the selection. */
15
- value: TValue;
16
- }
17
- type MaybePromise<T> = T | Promise<T>;
18
- /** A set of options that belong to one decision, such as one filter. */
19
- interface ChoiceGroup<TValue extends ChoiceValue = ChoiceValue> {
20
- /** Tells the model how to read this group. Keep it short and specific to your data. */
21
- hints?: string;
22
- /**
23
- * `false` (default): choose only an option that the text names. `true`: choose the option that fits the text best,
24
- * also when the text does not name it, such as a project for a bug report. Needs `multiple: false`.
25
- * An `infer` group has no "none" answer. Add an option for "anything else" if you need one.
26
- */
27
- infer?: boolean;
28
- /** What people call the group, such as "Supplier". */
29
- label: string;
30
- /** `true` (default): any number of options, each included or excluded. `false`: at most one option. */
31
- multiple?: boolean;
32
- /** A list, or a function that loads the list for one request. Annotate the parameter of the function: its type is the `context` of `resolve()`. */
33
- options: readonly ChoiceOption<TValue>[] | ((context: never) => MaybePromise<readonly ChoiceOption<TValue>[]>);
34
- }
35
- type ChoiceGroups = Record<string, ChoiceGroup>;
36
- interface ChoicesLimits {
37
- /** Most options in one group. Default 100. */
38
- options: number;
39
- /** Most groups. Default 40. */
40
- groups: number;
41
- /** Longest text in characters. Default 300. */
42
- text: number;
43
- /** Most options in all groups together. Default 100. */
44
- totalOptions: number;
45
- }
46
- interface ChoicesThresholds {
47
- /** The lowest probability that decides one option. Default 0.5. */
48
- option?: number;
49
- /** The lowest probability that the options can express the text. Default 0.6. Not asked when every group infers. */
50
- supported?: number;
51
- }
52
- interface ChoicesDefinition<TGroups extends ChoiceGroups> {
53
- /** Asks TypeSafe Jev, or any object with `ask()`: `typesafe()`, `vercel()`, or `cloudflare()` from `vite-hub/gateways`. Set `gateway` or `model`. */
54
- gateway?: {
55
- ask: AiGatewayAsk;
56
- };
57
- groups: TGroups;
58
- /** Tells the model what the options are about. It is added to every question. */
59
- hints?: string;
60
- limits?: Partial<ChoicesLimits>;
61
- /** Asks any AI SDK model instead of Jev, such as `openai("gpt-5.1-mini")`. It needs the `ai` package. Set `gateway` or `model`. */
62
- model?: AskModel;
63
- /** A label for logs and the CLI. It never connects anything. */
64
- name?: string;
65
- thresholds?: ChoicesThresholds;
66
- }
67
- type OptionValue<TOptions> = TOptions extends readonly ChoiceOption<infer TValue>[] ? TValue : TOptions extends ((context: never) => infer TResult) ? Awaited<TResult> extends readonly ChoiceOption<infer TValue>[] ? TValue : never : never;
68
- type GroupValue<TGroup> = TGroup extends {
69
- options: infer TOptions;
70
- } ? OptionValue<TOptions> : never;
71
- /** A group with `multiple` left as `true`: the options the text includes and excludes. */
72
- interface MultipleSelection<TValue extends ChoiceValue = ChoiceValue> {
73
- exclude: TValue[];
74
- include: TValue[];
75
- }
76
- /** A group with `multiple: false`: the best option, or `null`, and every option by probability. */
77
- interface SingleSelection<TValue extends ChoiceValue = ChoiceValue> {
78
- /** How much the best option stands out, from 0 to 1. */
79
- confidence: number;
80
- /** Every option, from the most to the least likely. */
81
- ranked: {
82
- probability: number;
83
- value: TValue;
84
- }[];
85
- /** The best option when it is above `thresholds.option`, else `null`. */
86
- value: TValue | null;
87
- }
88
- /** The result for each group, typed from the options that you declared. */
89
- type ChoicesSelection<TGroups> = { [K in keyof TGroups]: TGroups[K] extends {
90
- multiple: false;
91
- } ? SingleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>> : MultipleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>>; };
92
- /** A nostics error. Its `code` is one of `DECISIONS_R0001` to `DECISIONS_R0006`. */
93
- type ChoicesError = Diagnostic;
94
- type ChoicesResult<TData> = readonly [error: ChoicesError, data?: undefined] | readonly [error: undefined, data: TData];
95
- interface ChoicesRequest<TContext> {
96
- /** Passed to `options` functions. Put what they need here, such as the tenant. */
97
- context: TContext;
98
- /** Cancels the request to the gateway. */
99
- signal?: AbortSignal;
100
- }
101
- /** What `resolve()` would send, without sending it. */
102
- interface ChoicesPlan {
103
- /** The questions for `gateway.ask()`. One per option of a multiple group, one per single group, and `supported` unless every group infers. */
104
- questions: Record<string, unknown>;
105
- /** The state for `gateway.ask()`. */
106
- state: {
107
- groups: {
108
- hints?: string;
109
- infer?: true;
110
- label: string;
111
- multiple: boolean;
112
- options: {
113
- aliases?: readonly string[];
114
- label: string;
115
- value: ChoiceValue;
116
- }[];
117
- }[];
118
- query: string;
119
- };
120
- }
121
- type UnionToIntersection<TUnion> = (TUnion extends unknown ? (value: TUnion) => void : never) extends ((value: infer TIntersection) => void) ? TIntersection : never;
122
- type OptionsContext<TGroup> = TGroup extends {
123
- options: (context: infer TContext) => unknown;
124
- } ? TContext : never;
125
- /** The `context` that `resolve()` needs: the parameter types of the `options` functions of the groups. `unknown` when no group needs one. */
126
- type GroupsContext<TGroups> = UnionToIntersection<{ [K in keyof TGroups]: OptionsContext<TGroups[K]>; }[keyof TGroups]>;
127
- type ChoicesArgs<TContext> = unknown extends TContext ? [request?: {
128
- signal?: AbortSignal;
129
- }] : [request: ChoicesRequest<TContext> & {
130
- context: TContext;
131
- }];
132
- interface Choices<TGroups extends ChoiceGroups> {
133
- /** Shows the questions and the state that `resolve()` would send. Nothing leaves your server. */
134
- inspect: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesPlan>>;
135
- readonly name: string | undefined;
136
- /** Asks the gateway which options the text names. It returns `[error, selection]` and never throws. */
137
- resolve: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesSelection<TGroups>>>;
138
- }
139
- //#endregion
1
+ import { _ as MultipleSelection, a as Choices, c as ChoicesError, d as ChoicesRequest, f as ChoicesResult, g as GroupsContext, h as GroupValue, i as ChoiceValue, l as ChoicesLimits, m as ChoicesThresholds, n as ChoiceGroups, o as ChoicesArgs, p as ChoicesSelection, r as ChoiceOption, s as ChoicesDefinition, t as ChoiceGroup, u as ChoicesPlan, v as SingleSelection } from "./types-slPoBTpx.js";
140
2
  //#region src/choices.d.ts
141
3
  /**
142
4
  * Declares the options that text can choose from, and how to ask a gateway about them.
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { t as choicesDiagnostics } from "./diagnostics-DTMZy54f.js";
1
+ import { t as choicesDiagnostics } from "./diagnostics-BubnKF2J.js";
2
+ import { t as resolveSelection } from "./selection-gateway-D2jci9t-.js";
2
3
  import { ask, askWithModel } from "@vite-hub/gateways";
3
4
  import { getPublicAiGatewayDiagnostic } from "@vite-hub/gateways/internal";
4
5
  //#region src/choices.ts
@@ -12,7 +13,6 @@ const defaultThresholds = {
12
13
  option: .5,
13
14
  supported: .6
14
15
  };
15
- /** The label of "no option" in a single group. Option labels cannot use it. */
16
16
  const noneLabel = "(none)";
17
17
  const includeCriteria = "Choose include when the text names this option or clearly refers to it by a common abbreviation, code, partial name, spelling error, synonym, prefix, or suffix. Match the closest specific option. Partial text alone is not permission to include neighboring options. Match each requested option independently.";
18
18
  const excludeCriteria = "Choose exclude only when the text directly says to omit this option, for example with except, without, not, or exclude. A negated family, prefix, or suffix excludes every matching option.";
@@ -25,7 +25,9 @@ function define(message) {
25
25
  function fail(code, message) {
26
26
  return choicesDiagnostics[code]({ message: `[vitehub] ${message}` });
27
27
  }
28
- /** Exposes trusted gateway diagnostics while keeping unknown failures in `cause`. */
28
+ function unsupportedText() {
29
+ return fail("DECISIONS_R0004", "The options cannot express that text. Try another name, or use the options directly.");
30
+ }
29
31
  function gatewayFailed(cause) {
30
32
  const diagnostic = getPublicAiGatewayDiagnostic(cause);
31
33
  return choicesDiagnostics.DECISIONS_R0005({
@@ -37,7 +39,6 @@ function gatewayFailed(cause) {
37
39
  function probability(value) {
38
40
  return typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;
39
41
  }
40
- /** Checks the definition and returns what answers the questions: the gateway, or the model through `askWithModel()`. */
41
42
  function checkDefinition(definition, limits, thresholds) {
42
43
  const { gateway, model } = definition;
43
44
  if (gateway === void 0 === (model === void 0)) define("defineChoices() needs one of gateway or model: a gateway with ask(), such as vercel() from vite-hub/gateways, or an AI SDK model.");
@@ -56,6 +57,11 @@ function checkDefinition(definition, limits, thresholds) {
56
57
  for (const [name, value] of Object.entries(limits)) if (!Number.isInteger(value) || value < 1) define(`limits.${name} must be a positive integer.`);
57
58
  return model === void 0 ? gateway : askWithModel(model);
58
59
  }
60
+ function isAliasList(value) {
61
+ if (!Array.isArray(value)) return false;
62
+ for (const alias of value) if (typeof alias !== "string") return false;
63
+ return true;
64
+ }
59
65
  async function loadGroups(definition, limits, context) {
60
66
  const keys = Object.keys(definition.groups);
61
67
  const loaded = [];
@@ -71,12 +77,16 @@ async function loadGroups(definition, limits, context) {
71
77
  cause
72
78
  }) };
73
79
  }
80
+ if (!Array.isArray(options)) return { error: fail("DECISIONS_R0002", `The options of group "${key}" must be a list.`) };
74
81
  if (options.length > limits.options) return { error: fail("DECISIONS_R0002", `Group "${key}" has ${options.length} options. The limit is ${limits.options}. Narrow the options before you ask.`) };
75
82
  const multiple = group.multiple !== false;
76
83
  const values = /* @__PURE__ */ new Set();
77
84
  const labels = /* @__PURE__ */ new Set();
78
85
  for (const option of options) {
86
+ if (typeof option !== "object" || option === null) return { error: fail("DECISIONS_R0002", `An option of group "${key}" is not an object.`) };
79
87
  if (typeof option.label !== "string" || !option.label.trim()) return { error: fail("DECISIONS_R0002", `An option of group "${key}" has no label.`) };
88
+ if (typeof option.value !== "string" && !(typeof option.value === "number" && Number.isFinite(option.value))) return { error: fail("DECISIONS_R0002", `The option "${option.label}" of group "${key}" needs a value that is text or a finite number.`) };
89
+ if (option.aliases !== void 0 && !isAliasList(option.aliases)) return { error: fail("DECISIONS_R0002", `The option "${option.label}" of group "${key}" has aliases that are not a list of text.`) };
80
90
  if (option.description !== void 0 && typeof option.description !== "string") return { error: fail("DECISIONS_R0002", `The option "${option.label}" of group "${key}" has a description that is not text.`) };
81
91
  if (values.has(option.value)) return { error: fail("DECISIONS_R0002", `Group "${key}" has the value ${JSON.stringify(option.value)} twice. Values must be unique within a group.`) };
82
92
  values.add(option.value);
@@ -101,7 +111,6 @@ async function loadGroups(definition, limits, context) {
101
111
  function describe(option) {
102
112
  return option.aliases?.length ? `${option.label} (also ${option.aliases.map((alias) => JSON.stringify(alias)).join(", ")})` : option.label;
103
113
  }
104
- /** What the model reads about one option of a single group: its description and its aliases. */
105
114
  function optionCriteria(option) {
106
115
  const parts = [option.description?.trim(), option.aliases?.length ? `Also called ${option.aliases.join(", ")}.` : void 0].filter(Boolean);
107
116
  return parts.length ? parts.join(" ") : null;
@@ -129,11 +138,9 @@ function singleInstructions(group, hints) {
129
138
  hints
130
139
  ].filter(Boolean).join(" ");
131
140
  }
132
- /** The supported check covers the groups that do not infer. It is not asked when every group infers. */
133
141
  function needsSupported(groups) {
134
142
  return groups.some((group) => !group.infer && group.options.length);
135
143
  }
136
- /** Asks if the options can express the text. With `infer` groups, it judges only the other groups, and text that sets none of them is supported. */
137
144
  function supportedQuestion(groups, hints) {
138
145
  const checked = groups.filter((group) => !group.infer).map((group) => JSON.stringify(group.group.label));
139
146
  if (checked.length === groups.length) return ask.chance(["Can all intended constraints in the text be expressed with the supplied options? Be permissive about ordinary phrasing, shorthand, prefixes, and typos, but require a real match to supplied options.", hints].filter(Boolean).join(" "), {
@@ -220,12 +227,16 @@ function readSelection(answers, groups, threshold) {
220
227
  probability: probability(Reflect.get(answer.probabilities, label)),
221
228
  value
222
229
  })).sort((a, b) => b.probability - a.probability);
223
- const best = ranked[0];
224
230
  const chosen = answer.choice === noneLabel ? void 0 : byLabel.get(answer.choice);
225
- selection[group.key] = {
226
- confidence: probability(answer.confidence),
231
+ const chance = probability(Reflect.get(answer.probabilities, answer.choice));
232
+ selection[group.key] = chosen !== void 0 && chance >= threshold ? {
233
+ confidence: chance,
227
234
  ranked,
228
- value: chosen !== void 0 && best && probability(Reflect.get(answer.probabilities, answer.choice)) >= threshold ? chosen : null
235
+ value: chosen
236
+ } : {
237
+ confidence: 0,
238
+ ranked,
239
+ value: null
229
240
  };
230
241
  continue;
231
242
  }
@@ -267,9 +278,10 @@ function defineChoices(definition) {
267
278
  if (trimmed.length > limits.text) return [fail("DECISIONS_R0003", `The text has ${trimmed.length} characters. The limit is ${limits.text}.`)];
268
279
  const loaded = await loadGroups(base, limits, request?.context);
269
280
  if ("error" in loaded) return [loaded.error];
281
+ const plan = buildPlan(trimmed, loaded.groups, hints);
270
282
  return [void 0, {
271
283
  groups: loaded.groups,
272
- plan: buildPlan(trimmed, loaded.groups, hints),
284
+ plan,
273
285
  text: trimmed
274
286
  }];
275
287
  }
@@ -283,9 +295,21 @@ function defineChoices(definition) {
283
295
  const request = args[0];
284
296
  const [error, prepared] = await prepare(text, request);
285
297
  if (error) return [error];
298
+ const scripted = asker[resolveSelection];
299
+ if (scripted) try {
300
+ request?.signal?.throwIfAborted();
301
+ const context = request && "context" in request ? request.context : void 0;
302
+ const selection = await scripted(prepared.plan.state, prepared.groups.map((group) => group.key), context);
303
+ return selection ? [void 0, selection] : [unsupportedText()];
304
+ } catch (cause) {
305
+ return [gatewayFailed(cause)];
306
+ }
286
307
  let answers = {};
287
308
  if (Object.keys(prepared.plan.questions).length) try {
288
- const [askError, asked] = await asker.ask(prepared.plan.state, prepared.plan.questions, { signal: request?.signal });
309
+ const [askError, asked] = await asker.ask(prepared.plan.state, prepared.plan.questions, {
310
+ signal: request?.signal,
311
+ ...request?.onUsage && { onUsage: request.onUsage }
312
+ });
289
313
  if (askError) return [gatewayFailed(askError)];
290
314
  answers = asked;
291
315
  } catch (cause) {
@@ -294,7 +318,7 @@ function defineChoices(definition) {
294
318
  if (needsSupported(prepared.groups)) {
295
319
  const supported = answers.supported;
296
320
  if (typeof supported !== "object" || supported.type !== "chance") return [fail("DECISIONS_R0006", "The model did not answer the supported check.")];
297
- if (probability(supported.chance) < thresholds.supported) return [fail("DECISIONS_R0004", "The options cannot express that text. Try another name, or use the options directly.")];
321
+ if (probability(supported.chance) < thresholds.supported) return [unsupportedText()];
298
322
  }
299
323
  const [readError, selection] = readSelection(answers, prepared.groups, thresholds.option);
300
324
  if (readError) return [readError];
@@ -0,0 +1,5 @@
1
+ //#region src/selection-gateway.ts
2
+ /** Internal protocol shared by the production and testing entries, even across package copies. */
3
+ const resolveSelection = Symbol.for("vitehub.choices.resolveSelection");
4
+ //#endregion
5
+ export { resolveSelection as t };
@@ -0,0 +1,47 @@
1
+ import { g as GroupsContext, h as GroupValue, i as ChoiceValue, n as ChoiceGroups } from "./types-slPoBTpx.js";
2
+ import { AiGatewayAsk } from "@vite-hub/gateways";
3
+ //#region src/testing.d.ts
4
+ type MaybePromise<T> = T | Promise<T>;
5
+ /** Return it from `selectionGateway()` to say that the options cannot express the text. `resolve()` returns `DECISIONS_R0004`. */
6
+ export declare const unsupported: unique symbol;
7
+ type GroupSelection<TValue> = TValue | null | undefined | {
8
+ exclude?: readonly TValue[];
9
+ include?: readonly TValue[];
10
+ };
11
+ /**
12
+ * The selection that `selectionGateway()` answers, keyed by group: an option value or `null` for a group with `multiple: false`,
13
+ * and `{ include, exclude }` for the other groups. A group that you leave out selects nothing.
14
+ * Pass `typeof groups` as the type argument of `selectionGateway()` to check the keys and values.
15
+ */
16
+ export type TestSelection<TGroups extends ChoiceGroups = ChoiceGroups> = string extends keyof TGroups ? {
17
+ readonly [group: string]: GroupSelection<ChoiceValue>;
18
+ } : { readonly [K in keyof TGroups]?: TGroups[K] extends {
19
+ multiple: false;
20
+ } ? GroupValue<TGroups[K]> | null : {
21
+ exclude?: readonly GroupValue<TGroups[K]>[];
22
+ include?: readonly GroupValue<TGroups[K]>[];
23
+ }; };
24
+ type TestContext<TGroups extends ChoiceGroups> = string extends keyof TGroups ? unknown : GroupsContext<TGroups>;
25
+ type TestAnswer<TGroups extends ChoiceGroups> = TestSelection<TGroups> | typeof unsupported;
26
+ /**
27
+ * A gateway for unit tests: `resolve()` returns the selection that you give, keyed by your own groups and option values.
28
+ * Pass a function to answer from the text and the `context` of the request. Return `unsupported` for `DECISIONS_R0004`,
29
+ * and throw for `DECISIONS_R0005`. The values are checked against the loaded options without applying model thresholds.
30
+ *
31
+ * @example
32
+ * defineChoices({ gateway: selectionGateway({ supplier: { include: ['nord'] }, chart: 'line' }), groups })
33
+ */
34
+ export declare function selectionGateway<TGroups extends ChoiceGroups = ChoiceGroups>(selection: TestAnswer<TGroups> | ((text: string, context: TestContext<TGroups>) => MaybePromise<TestAnswer<TGroups>>)): {
35
+ ask: AiGatewayAsk;
36
+ };
37
+ /**
38
+ * An offline gateway that answers by word match, for get-started and local dev without an API key. It is not a model:
39
+ * an option is included when the text names its label or one of its aliases as whole words, and excluded when "except",
40
+ * "not", or "without" comes before that name. A single group without inference chooses the first named option that is
41
+ * not excluded. An infer group also matches words of five letters or more from the option descriptions. Text with the
42
+ * word "unsupported" fails the supported check, so you can see `DECISIONS_R0004`.
43
+ */
44
+ export declare function wordGateway(): {
45
+ ask: AiGatewayAsk;
46
+ };
47
+ //#endregion
@@ -0,0 +1,126 @@
1
+ import { t as choicesDiagnostics } from "./diagnostics-BubnKF2J.js";
2
+ import { t as resolveSelection } from "./selection-gateway-D2jci9t-.js";
3
+ import { answers } from "@vite-hub/gateways/testing";
4
+ //#region src/testing.ts
5
+ /** Return it from `selectionGateway()` to say that the options cannot express the text. `resolve()` returns `DECISIONS_R0004`. */
6
+ const unsupported = Symbol("unsupported");
7
+ function invalid(problem) {
8
+ return choicesDiagnostics.DECISIONS_TESTING_SELECTION_INVALID({ problem });
9
+ }
10
+ /**
11
+ * A gateway for unit tests: `resolve()` returns the selection that you give, keyed by your own groups and option values.
12
+ * Pass a function to answer from the text and the `context` of the request. Return `unsupported` for `DECISIONS_R0004`,
13
+ * and throw for `DECISIONS_R0005`. The values are checked against the loaded options without applying model thresholds.
14
+ *
15
+ * @example
16
+ * defineChoices({ gateway: selectionGateway({ supplier: { include: ['nord'] }, chart: 'line' }), groups })
17
+ */
18
+ function selectionGateway(selection) {
19
+ return {
20
+ async ask() {
21
+ throw invalid("selectionGateway() only works as the gateway of defineChoices().");
22
+ },
23
+ async [resolveSelection](plan, keys, context) {
24
+ const selected = typeof selection === "function" ? await selection(plan.query, context) : selection;
25
+ if (selected === unsupported) return void 0;
26
+ const values = selected;
27
+ const unknown = Object.keys(values).filter((key) => !keys.includes(key));
28
+ if (unknown.length) throw invalid(`The selection names ${unknown.map((key) => JSON.stringify(key)).join(", ")}, but the groups are ${keys.map((key) => JSON.stringify(key)).join(", ")}.`);
29
+ return Object.fromEntries(plan.groups.map((group, index) => {
30
+ const key = keys[index];
31
+ const value = Object.hasOwn(values, key) ? values[key] : void 0;
32
+ const optionValues = group.options.map((option) => option.value);
33
+ const checkValue = (item) => {
34
+ if (!optionValues.includes(item)) throw invalid(`Group "${key}" has no option with the value ${JSON.stringify(item)}.`);
35
+ };
36
+ if (!group.multiple) {
37
+ if (typeof value === "object" && value !== null) throw invalid(`Group "${key}" has multiple: false. Select one option value or null, not { include, exclude }.`);
38
+ const chosen = value ?? null;
39
+ if (chosen !== null) checkValue(chosen);
40
+ const ranked = optionValues.map((item) => ({
41
+ probability: item === chosen ? 1 : 0,
42
+ value: item
43
+ })).sort((left, right) => right.probability - left.probability);
44
+ return [key, {
45
+ confidence: chosen === null ? 0 : 1,
46
+ ranked,
47
+ value: chosen
48
+ }];
49
+ }
50
+ if (value !== void 0 && (typeof value !== "object" || value === null || Array.isArray(value))) throw invalid(`Group "${key}" takes any number of options. Select { include, exclude }, not one value.`);
51
+ const include = value?.include ?? [];
52
+ const exclude = value?.exclude ?? [];
53
+ if (!Array.isArray(include) || !Array.isArray(exclude)) throw invalid(`Group "${key}" needs arrays of option values for include and exclude.`);
54
+ for (const item of [...include, ...exclude]) checkValue(item);
55
+ const both = include.find((item) => exclude.includes(item));
56
+ if (both !== void 0) throw invalid(`Group "${key}" includes and excludes ${JSON.stringify(both)}. Put each option value in one list.`);
57
+ return [key, {
58
+ exclude: optionValues.filter((item) => exclude.includes(item)),
59
+ include: optionValues.filter((item) => include.includes(item))
60
+ }];
61
+ }));
62
+ }
63
+ };
64
+ }
65
+ function escapeRegExp(text) {
66
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
67
+ }
68
+ const edge = String.raw`[\p{L}\p{M}\p{N}_]`;
69
+ function wordPattern(pattern) {
70
+ return new RegExp(`(?<!${edge})${pattern}(?!${edge})`, "u");
71
+ }
72
+ function matchOption(text, option) {
73
+ let named = false;
74
+ for (const name of [option.label, ...option.aliases ?? []]) {
75
+ if (!name.trim()) continue;
76
+ const pattern = escapeRegExp(name.toLowerCase());
77
+ if (!wordPattern(pattern).test(text)) continue;
78
+ if (wordPattern(String.raw`(?:except|not|without)\s+(?:${edge}+\s+)?${pattern}`).test(text)) return "exclude";
79
+ named = true;
80
+ }
81
+ return named ? "include" : "none";
82
+ }
83
+ /**
84
+ * An offline gateway that answers by word match, for get-started and local dev without an API key. It is not a model:
85
+ * an option is included when the text names its label or one of its aliases as whole words, and excluded when "except",
86
+ * "not", or "without" comes before that name. A single group without inference chooses the first named option that is
87
+ * not excluded. An infer group also matches words of five letters or more from the option descriptions. Text with the
88
+ * word "unsupported" fails the supported check, so you can see `DECISIONS_R0004`.
89
+ */
90
+ function wordGateway() {
91
+ const ask = async (state, questions, options) => {
92
+ options?.signal?.throwIfAborted();
93
+ const { groups, query } = state;
94
+ const text = query.toLowerCase();
95
+ const answer = (key, question) => {
96
+ if (key === "supported") return answers.chance(wordPattern("unsupported").test(text) ? .1 : .95);
97
+ const [, groupIndex, optionIndex] = /^g(\d+)(?:_o(\d+))?$/.exec(key) ?? [];
98
+ const group = groups[Number(groupIndex)];
99
+ if (!group || question.type !== "choice") return answers.first(question);
100
+ if (optionIndex !== void 0) return answers.choice(question, matchOption(text, group.options[Number(optionIndex)]), .9);
101
+ if (group.infer) {
102
+ const words = (label) => {
103
+ const criteria = question.criteria[label];
104
+ return typeof criteria === "string" ? criteria.toLowerCase().match(/\w{5,}/g) ?? [] : [];
105
+ };
106
+ const fit = group.options.find((option) => matchOption(text, option) !== "none" || words(option.label).some((word) => text.includes(word)));
107
+ return answers.choice(question, (fit ?? group.options[0]).label, fit ? .8 : Math.max(.4, 1 / group.options.length));
108
+ }
109
+ const best = group.options.find((option) => matchOption(text, option) === "include");
110
+ return answers.choice(question, best?.label ?? "(none)", best ? .8 : .9);
111
+ };
112
+ const entries = Object.entries(questions).map(([key, question]) => [key, answer(key, question)]);
113
+ options?.onUsage?.({
114
+ provider: "scripted",
115
+ usage: {
116
+ inputTokens: 0,
117
+ outputTokens: 0,
118
+ totalTokens: 0
119
+ }
120
+ });
121
+ return [void 0, Object.fromEntries(entries)];
122
+ };
123
+ return { ask };
124
+ }
125
+ //#endregion
126
+ export { selectionGateway, unsupported, wordGateway };
@@ -0,0 +1,148 @@
1
+ import { AiGatewayAsk, AiGatewayAskOptions, AskModel } from "@vite-hub/gateways";
2
+ import { Diagnostic } from "nostics";
3
+ //#region src/types.d.ts
4
+ /** The value that you map back to your data. It must be unique within its group. */
5
+ type ChoiceValue = string | number;
6
+ /** One option of a group. `value` is yours, `label`, `aliases`, and `description` are what the model reads. */
7
+ interface ChoiceOption<TValue extends ChoiceValue = ChoiceValue> {
8
+ /** Other names for the option, such as codes, abbreviations, or translations. */
9
+ aliases?: readonly string[];
10
+ /** What the option is about. An `infer` group needs it to choose an option that the text does not name. */
11
+ description?: string;
12
+ /** What people call the option. */
13
+ label: string;
14
+ /** Your id for the option. It comes back in the selection. */
15
+ value: TValue;
16
+ }
17
+ type MaybePromise<T> = T | Promise<T>;
18
+ /** A set of options that belong to one decision, such as one filter. */
19
+ interface ChoiceGroup<TValue extends ChoiceValue = ChoiceValue> {
20
+ /** Tells the model how to read this group. Keep it short and specific to your data. */
21
+ hints?: string;
22
+ /**
23
+ * `false` (default): choose only an option that the text names. `true`: choose the option that fits the text best,
24
+ * also when the text does not name it, such as a project for a bug report. Needs `multiple: false`.
25
+ * An `infer` group has no "none" answer. Add an option for "anything else" if you need one.
26
+ */
27
+ infer?: boolean;
28
+ /** What people call the group, such as "Supplier". */
29
+ label: string;
30
+ /** `true` (default): any number of options, each included or excluded. `false`: at most one option. */
31
+ multiple?: boolean;
32
+ /** A list, or a function that loads the list for one request. Annotate the parameter of the function: its type is the `context` of `resolve()`. */
33
+ options: readonly ChoiceOption<TValue>[] | ((context: never) => MaybePromise<readonly ChoiceOption<TValue>[]>);
34
+ }
35
+ type ChoiceGroups = Record<string, ChoiceGroup>;
36
+ interface ChoicesLimits {
37
+ /** Most options in one group. Default 100. */
38
+ options: number;
39
+ /** Most groups. Default 40. */
40
+ groups: number;
41
+ /** Longest text in characters. Default 300. */
42
+ text: number;
43
+ /** Most options in all groups together. Default 100. */
44
+ totalOptions: number;
45
+ }
46
+ interface ChoicesThresholds {
47
+ /** The lowest probability that decides one option. Default 0.5. */
48
+ option?: number;
49
+ /** The lowest probability that the options can express the text. Default 0.6. Not asked when every group infers. */
50
+ supported?: number;
51
+ }
52
+ interface ChoicesDefinition<TGroups extends ChoiceGroups> {
53
+ /** Asks TypeSafe Jev, or any object with `ask()`: `typesafe()`, `vercel()`, or `cloudflare()` from `vite-hub/gateways`. Set `gateway` or `model`. */
54
+ gateway?: {
55
+ ask: AiGatewayAsk;
56
+ };
57
+ groups: TGroups;
58
+ /** Tells the model what the options are about. It is added to every question. */
59
+ hints?: string;
60
+ limits?: Partial<ChoicesLimits>;
61
+ /** Asks any AI SDK model instead of Jev, such as `openai("gpt-5.1-mini")`. It needs the `ai` package. Set `gateway` or `model`. */
62
+ model?: AskModel;
63
+ /** A label for logs and the CLI. It never connects anything. */
64
+ name?: string;
65
+ thresholds?: ChoicesThresholds;
66
+ }
67
+ type OptionValue<TOptions> = TOptions extends readonly ChoiceOption<infer TValue>[] ? TValue : TOptions extends ((context: never) => infer TResult) ? Awaited<TResult> extends readonly ChoiceOption<infer TValue>[] ? TValue : never : never;
68
+ type GroupValue<TGroup> = TGroup extends {
69
+ options: infer TOptions;
70
+ } ? OptionValue<TOptions> : never;
71
+ /** A group with `multiple` left as `true`: the options the text includes and excludes. */
72
+ interface MultipleSelection<TValue extends ChoiceValue = ChoiceValue> {
73
+ exclude: TValue[];
74
+ include: TValue[];
75
+ }
76
+ /** A group with `multiple: false`: the best option, or `null`, and every option by probability. */
77
+ interface SingleSelection<TValue extends ChoiceValue = ChoiceValue> {
78
+ /** The probability of `value`, from 0 to 1. It is `0` when `value` is `null`. */
79
+ confidence: number;
80
+ /** Every option, from the most to the least likely. */
81
+ ranked: {
82
+ probability: number;
83
+ value: TValue;
84
+ }[];
85
+ /** The best option when it is above `thresholds.option`, else `null`. */
86
+ value: TValue | null;
87
+ }
88
+ /** The result for each group, typed from the options that you declared. */
89
+ type ChoicesSelection<TGroups> = { [K in keyof TGroups]: TGroups[K] extends {
90
+ multiple: false;
91
+ } ? SingleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>> : MultipleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>>; };
92
+ /**
93
+ * Why `resolve()` returned no selection. Check `error.code`. `DECISIONS_R0002`: a group or option is invalid or over a
94
+ * limit. `DECISIONS_R0003`: the text is empty or too long. `DECISIONS_R0004`: the options cannot express the text.
95
+ * `DECISIONS_R0005`: the gateway request failed, with the gateway error in `cause`. `DECISIONS_R0006`: the model left a
96
+ * question without an answer. `defineChoices()` throws `DECISIONS_R0001`, so it never comes back here.
97
+ */
98
+ type ChoicesError = Diagnostic<unknown, "DECISIONS_R0002"> | Diagnostic<unknown, "DECISIONS_R0003"> | Diagnostic<unknown, "DECISIONS_R0004"> | Diagnostic<unknown, "DECISIONS_R0005"> | Diagnostic<unknown, "DECISIONS_R0006">;
99
+ type ChoicesResult<TData> = readonly [error: ChoicesError, data?: undefined] | readonly [error: undefined, data: TData];
100
+ interface ChoicesRequest<TContext> {
101
+ /** Passed to `options` functions. Put what they need here, such as the tenant. */
102
+ context: TContext;
103
+ /**
104
+ * Receives the model, provider, and token counts when the gateway reports usage.
105
+ * Jev can report usage for multiple batches in one `resolve()`. With `model`, this runs at most once.
106
+ */
107
+ onUsage?: AiGatewayAskOptions["onUsage"];
108
+ /** Cancels the request to the gateway. */
109
+ signal?: AbortSignal;
110
+ }
111
+ /** What `resolve()` would send, without sending it. */
112
+ interface ChoicesPlan {
113
+ /** The questions for `gateway.ask()`. One per option of a multiple group, one per single group, and `supported` unless every group infers. */
114
+ questions: Record<string, unknown>;
115
+ /** The state for `gateway.ask()`. */
116
+ state: {
117
+ groups: {
118
+ hints?: string;
119
+ infer?: true;
120
+ label: string;
121
+ multiple: boolean;
122
+ options: {
123
+ aliases?: readonly string[];
124
+ label: string;
125
+ value: ChoiceValue;
126
+ }[];
127
+ }[];
128
+ query: string;
129
+ };
130
+ }
131
+ type UnionToIntersection<TUnion> = (TUnion extends unknown ? (value: TUnion) => void : never) extends ((value: infer TIntersection) => void) ? TIntersection : never;
132
+ type OptionsContext<TGroup> = TGroup extends {
133
+ options: (context: infer TContext) => unknown;
134
+ } ? TContext : never;
135
+ /** The `context` that `resolve()` needs: the parameter types of the `options` functions of the groups. `unknown` when no group needs one. */
136
+ type GroupsContext<TGroups> = UnionToIntersection<{ [K in keyof TGroups]: OptionsContext<TGroups[K]>; }[keyof TGroups]>;
137
+ type ChoicesArgs<TContext> = unknown extends TContext ? [request?: Omit<ChoicesRequest<unknown>, "context">] : [request: ChoicesRequest<TContext> & {
138
+ context: TContext;
139
+ }];
140
+ interface Choices<TGroups extends ChoiceGroups> {
141
+ /** Shows the questions and the state that `resolve()` would send. Nothing leaves your server. */
142
+ inspect: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesPlan>>;
143
+ readonly name: string | undefined;
144
+ /** Asks the gateway which options the text names. It returns `[error, selection]` and never throws. */
145
+ resolve: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesSelection<TGroups>>>;
146
+ }
147
+ //#endregion
148
+ export { MultipleSelection as _, Choices as a, ChoicesError as c, ChoicesRequest as d, ChoicesResult as f, GroupsContext as g, GroupValue as h, ChoiceValue as i, ChoicesLimits as l, ChoicesThresholds as m, ChoiceGroups as n, ChoicesArgs as o, ChoicesSelection as p, ChoiceOption as r, ChoicesDefinition as s, ChoiceGroup as t, ChoicesPlan as u, SingleSelection as v };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/choices",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Turn text into choices over options that you declare: filters, search facets, command palettes, and builders on a TypeSafe Jev decision model.",
5
5
  "keywords": [
6
6
  "ai",
@@ -38,6 +38,11 @@
38
38
  "import": "./dist/cli.js",
39
39
  "default": "./dist/cli.js"
40
40
  },
41
+ "./testing": {
42
+ "types": "./dist/testing.d.ts",
43
+ "import": "./dist/testing.js",
44
+ "default": "./dist/testing.js"
45
+ },
41
46
  "./vue": {
42
47
  "types": "./dist/vue.d.ts",
43
48
  "import": "./dist/vue.js",
@@ -46,7 +51,7 @@
46
51
  "./package.json": "./package.json"
47
52
  },
48
53
  "dependencies": {
49
- "@vite-hub/gateways": "0.4.1",
54
+ "@vite-hub/gateways": "0.5.0",
50
55
  "nostics": "1.4.0"
51
56
  },
52
57
  "devDependencies": {