@vite-hub/choices 0.4.1 → 0.5.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 +27 -2
- package/dist/cli.d.ts +2 -10
- package/dist/cli.js +4 -10
- package/dist/{diagnostics-DTMZy54f.js → diagnostics-D9hxehC1.js} +6 -9
- package/dist/index.d.ts +1 -143
- package/dist/index.js +40 -18
- package/dist/selection-gateway-BB8o3bIT.js +4 -0
- package/dist/testing.d.ts +46 -0
- package/dist/testing.js +125 -0
- package/dist/types-DNHgwMWj.d.ts +146 -0
- package/dist/vue.d.ts +1 -3
- package/dist/vue.js +1 -2
- package/package.json +13 -8
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
|
|
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
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Diagnostic } from "nostics";
|
|
2
|
-
//#region ../internal/src/host-credentials.d.ts
|
|
3
2
|
interface HostCliRunResult {
|
|
4
3
|
exitCode: number | null;
|
|
5
4
|
stdout: string;
|
|
5
|
+
stderr?: string;
|
|
6
6
|
}
|
|
7
7
|
/** Runs a host CLI with an argument array and no shell, and returns its stdout. */
|
|
8
8
|
type HostCliRun = (command: string, args: readonly string[], options: {
|
|
@@ -10,8 +10,6 @@ type HostCliRun = (command: string, args: readonly string[], options: {
|
|
|
10
10
|
env: NodeJS.ProcessEnv;
|
|
11
11
|
signal?: AbortSignal;
|
|
12
12
|
}) => Promise<HostCliRunResult>;
|
|
13
|
-
//#endregion
|
|
14
|
-
//#region ../internal/src/provision.d.ts
|
|
15
13
|
type ProvisionProvider = "cloudflare" | "vercel";
|
|
16
14
|
interface ProvisionLogger {
|
|
17
15
|
log: (message: string) => void;
|
|
@@ -63,8 +61,6 @@ interface ProvisionStep {
|
|
|
63
61
|
/** Describes the Provision State this step records. Runs without network access, also without credentials. */
|
|
64
62
|
recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
|
|
65
63
|
}
|
|
66
|
-
//#endregion
|
|
67
|
-
//#region ../internal/src/cli.d.ts
|
|
68
64
|
interface ViteHubCliStreams {
|
|
69
65
|
stderr: {
|
|
70
66
|
write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
|
|
@@ -125,16 +121,12 @@ interface ViteHubCliCommandNamespace {
|
|
|
125
121
|
name: string;
|
|
126
122
|
}
|
|
127
123
|
type StdoutWriteCallback = (error?: Error | null) => void;
|
|
128
|
-
//#endregion
|
|
129
|
-
//#region src/cli.d.ts
|
|
130
124
|
interface FoundChoices {
|
|
131
125
|
export: string;
|
|
132
126
|
name: string | undefined;
|
|
133
127
|
}
|
|
134
128
|
interface ListedFile {
|
|
135
|
-
/** The exports of the file that `defineChoices()` returned. Empty when the file failed to load. */
|
|
136
129
|
choices: FoundChoices[];
|
|
137
|
-
/** Why the file did not load. */
|
|
138
130
|
error?: string;
|
|
139
131
|
file: string;
|
|
140
132
|
}
|
|
@@ -145,4 +137,4 @@ export declare function listChoices(rootDir: string): Promise<ListedFile[]>;
|
|
|
145
137
|
* `run` calls the gateway of the definition, so it reads the same keys as the app, from the shell or the `.env` files.
|
|
146
138
|
*/
|
|
147
139
|
export declare function createChoicesCliNamespace(): ViteHubCliCommandNamespace;
|
|
148
|
-
|
|
140
|
+
export {};
|
package/dist/cli.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { t as choicesDiagnostics } from "./diagnostics-
|
|
1
|
+
import { t as choicesDiagnostics } from "./diagnostics-D9hxehC1.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";
|
|
5
|
-
|
|
5
|
+
// ../internal/src/cli.ts
|
|
6
6
|
const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
|
|
7
7
|
const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
|
|
8
8
|
const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
|
|
@@ -58,8 +58,7 @@ function getStableStdoutWrite() {
|
|
|
58
58
|
}
|
|
59
59
|
return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
|
|
60
60
|
}
|
|
61
|
-
|
|
62
|
-
//#region ../internal/src/vite-stage.ts
|
|
61
|
+
// ../internal/src/vite-stage.ts
|
|
63
62
|
/**
|
|
64
63
|
* Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
|
|
65
64
|
* logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
|
|
@@ -73,8 +72,7 @@ function loadAllEnv(loadEnv, mode, envDir) {
|
|
|
73
72
|
process.stderr.write = write;
|
|
74
73
|
}
|
|
75
74
|
}
|
|
76
|
-
|
|
77
|
-
//#region src/cli.ts
|
|
75
|
+
// src/cli.ts
|
|
78
76
|
const listUsage = "vitehub choices list [--json]";
|
|
79
77
|
const runUsage = "vitehub choices run <file> <text> [--export <name>] [--context <json>] [--inspect]";
|
|
80
78
|
const sourceExtensions = /\.(?:[cm]?[jt]s)$/;
|
|
@@ -99,7 +97,6 @@ function choicesOf(module) {
|
|
|
99
97
|
name: value.name
|
|
100
98
|
}] : []);
|
|
101
99
|
}
|
|
102
|
-
/** Loads one file the way Vite loads server code, so TypeScript and extensionless imports work. */
|
|
103
100
|
async function loadModule(file, rootDir) {
|
|
104
101
|
const { runnerImport } = await import("vite");
|
|
105
102
|
const { module } = await runnerImport(file, {
|
|
@@ -109,7 +106,6 @@ async function loadModule(file, rootDir) {
|
|
|
109
106
|
});
|
|
110
107
|
return module;
|
|
111
108
|
}
|
|
112
|
-
/** Gateways read their keys from the environment. Add the project `.env` files without replacing set values. */
|
|
113
109
|
async function loadProjectEnv(context) {
|
|
114
110
|
const { loadEnv } = await import("vite");
|
|
115
111
|
const mode = context.env.NODE_ENV === "production" ? "production" : "development";
|
|
@@ -237,7 +233,6 @@ async function runOne(args, context) {
|
|
|
237
233
|
context.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
|
|
238
234
|
return 0;
|
|
239
235
|
}
|
|
240
|
-
/** The fix of a usage error of these commands, or `undefined` for another error. */
|
|
241
236
|
function cliFix(error) {
|
|
242
237
|
return choicesDiagnostics.is(error) && error.code.startsWith("DECISIONS_CLI_") ? error.fix : void 0;
|
|
243
238
|
}
|
|
@@ -278,5 +273,4 @@ function createChoicesCliNamespace() {
|
|
|
278
273
|
name: "choices"
|
|
279
274
|
};
|
|
280
275
|
}
|
|
281
|
-
//#endregion
|
|
282
276
|
export { createChoicesCliNamespace, listChoices };
|
|
@@ -1,35 +1,29 @@
|
|
|
1
1
|
import { defineDiagnostics } from "nostics";
|
|
2
|
-
|
|
2
|
+
// src/diagnostics.ts
|
|
3
3
|
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
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
|
|
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,8 +35,11 @@ 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
|
});
|
|
47
|
-
//#endregion
|
|
48
45
|
export { choicesDiagnostics as t };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,150 +1,9 @@
|
|
|
1
|
-
import {
|
|
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
|
|
140
|
-
//#region src/choices.d.ts
|
|
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-DNHgwMWj.js";
|
|
141
2
|
/**
|
|
142
3
|
* Declares the options that text can choose from, and how to ask a gateway about them.
|
|
143
4
|
* Nothing here knows your UI, your routes, or your store. Call `resolve()` wherever you run server code.
|
|
144
5
|
*/
|
|
145
6
|
export declare function defineChoices<const TGroups extends ChoiceGroups>(definition: ChoicesDefinition<TGroups>): Choices<TGroups>;
|
|
146
|
-
//#endregion
|
|
147
|
-
//#region src/options.d.ts
|
|
148
7
|
interface ToOptionsMap<TItem, TValue extends ChoiceValue> {
|
|
149
8
|
aliases?: (item: TItem) => readonly string[] | undefined;
|
|
150
9
|
description?: (item: TItem) => string | undefined;
|
|
@@ -153,5 +12,4 @@ interface ToOptionsMap<TItem, TValue extends ChoiceValue> {
|
|
|
153
12
|
}
|
|
154
13
|
/** Maps your own items to options. This is the bridge from your data to Choices. */
|
|
155
14
|
export declare function toOptions<TItem, TValue extends ChoiceValue>(items: readonly TItem[], map: ToOptionsMap<TItem, TValue>): ChoiceOption<TValue>[];
|
|
156
|
-
//#endregion
|
|
157
15
|
export type { ChoiceGroup, ChoiceGroups, ChoiceOption, ChoiceValue, Choices, ChoicesArgs, ChoicesDefinition, ChoicesError, ChoicesLimits, ChoicesPlan, ChoicesRequest, ChoicesResult, ChoicesSelection, ChoicesThresholds, GroupValue, GroupsContext, MultipleSelection, SingleSelection, ToOptionsMap };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { t as choicesDiagnostics } from "./diagnostics-
|
|
1
|
+
import { t as choicesDiagnostics } from "./diagnostics-D9hxehC1.js";
|
|
2
|
+
import { t as resolveSelection } from "./selection-gateway-BB8o3bIT.js";
|
|
2
3
|
import { ask, askWithModel } from "@vite-hub/gateways";
|
|
3
4
|
import { getPublicAiGatewayDiagnostic } from "@vite-hub/gateways/internal";
|
|
4
|
-
|
|
5
|
+
// src/choices.ts
|
|
5
6
|
const defaultLimits = {
|
|
6
7
|
groups: 40,
|
|
7
8
|
options: 100,
|
|
@@ -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
|
-
|
|
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
|
-
|
|
226
|
-
|
|
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
|
|
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
|
|
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, {
|
|
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 [
|
|
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];
|
|
@@ -302,8 +326,7 @@ function defineChoices(definition) {
|
|
|
302
326
|
}
|
|
303
327
|
};
|
|
304
328
|
}
|
|
305
|
-
|
|
306
|
-
//#region src/options.ts
|
|
329
|
+
// src/options.ts
|
|
307
330
|
/** Maps your own items to options. This is the bridge from your data to Choices. */
|
|
308
331
|
function toOptions(items, map) {
|
|
309
332
|
return items.map((item) => {
|
|
@@ -317,5 +340,4 @@ function toOptions(items, map) {
|
|
|
317
340
|
};
|
|
318
341
|
});
|
|
319
342
|
}
|
|
320
|
-
//#endregion
|
|
321
343
|
export { defineChoices, toOptions };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { g as GroupsContext, h as GroupValue, i as ChoiceValue, n as ChoiceGroups } from "./types-DNHgwMWj.js";
|
|
2
|
+
import { AiGatewayAsk } from "@vite-hub/gateways";
|
|
3
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
4
|
+
/** Return it from `selectionGateway()` to say that the options cannot express the text. `resolve()` returns `DECISIONS_R0004`. */
|
|
5
|
+
export declare const unsupported: unique symbol;
|
|
6
|
+
type GroupSelection<TValue> = TValue | null | undefined | {
|
|
7
|
+
exclude?: readonly TValue[];
|
|
8
|
+
include?: readonly TValue[];
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The selection that `selectionGateway()` answers, keyed by group: an option value or `null` for a group with `multiple: false`,
|
|
12
|
+
* and `{ include, exclude }` for the other groups. A group that you leave out selects nothing.
|
|
13
|
+
* Pass `typeof groups` as the type argument of `selectionGateway()` to check the keys and values.
|
|
14
|
+
*/
|
|
15
|
+
export type TestSelection<TGroups extends ChoiceGroups = ChoiceGroups> = string extends keyof TGroups ? {
|
|
16
|
+
readonly [group: string]: GroupSelection<ChoiceValue>;
|
|
17
|
+
} : { readonly [K in keyof TGroups]?: TGroups[K] extends {
|
|
18
|
+
multiple: false;
|
|
19
|
+
} ? GroupValue<TGroups[K]> | null : {
|
|
20
|
+
exclude?: readonly GroupValue<TGroups[K]>[];
|
|
21
|
+
include?: readonly GroupValue<TGroups[K]>[];
|
|
22
|
+
}; };
|
|
23
|
+
type TestContext<TGroups extends ChoiceGroups> = string extends keyof TGroups ? unknown : GroupsContext<TGroups>;
|
|
24
|
+
type TestAnswer<TGroups extends ChoiceGroups> = TestSelection<TGroups> | typeof unsupported;
|
|
25
|
+
/**
|
|
26
|
+
* A gateway for unit tests: `resolve()` returns the selection that you give, keyed by your own groups and option values.
|
|
27
|
+
* Pass a function to answer from the text and the `context` of the request. Return `unsupported` for `DECISIONS_R0004`,
|
|
28
|
+
* and throw for `DECISIONS_R0005`. The values are checked against the loaded options without applying model thresholds.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* defineChoices({ gateway: selectionGateway({ supplier: { include: ['nord'] }, chart: 'line' }), groups })
|
|
32
|
+
*/
|
|
33
|
+
export declare function selectionGateway<TGroups extends ChoiceGroups = ChoiceGroups>(selection: TestAnswer<TGroups> | ((text: string, context: TestContext<TGroups>) => MaybePromise<TestAnswer<TGroups>>)): {
|
|
34
|
+
ask: AiGatewayAsk;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* An offline gateway that answers by word match, for get-started and local dev without an API key. It is not a model:
|
|
38
|
+
* an option is included when the text names its label or one of its aliases as whole words, and excluded when "except",
|
|
39
|
+
* "not", or "without" comes before that name. A single group without inference chooses the first named option that is
|
|
40
|
+
* not excluded. An infer group also matches words of five letters or more from the option descriptions. Text with the
|
|
41
|
+
* word "unsupported" fails the supported check, so you can see `DECISIONS_R0004`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function wordGateway(): {
|
|
44
|
+
ask: AiGatewayAsk;
|
|
45
|
+
};
|
|
46
|
+
export {};
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { t as choicesDiagnostics } from "./diagnostics-D9hxehC1.js";
|
|
2
|
+
import { t as resolveSelection } from "./selection-gateway-BB8o3bIT.js";
|
|
3
|
+
import { answers } from "@vite-hub/gateways/testing";
|
|
4
|
+
// 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
|
+
export { selectionGateway, unsupported, wordGateway };
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { AiGatewayAsk, AiGatewayAskOptions, AskModel } from "@vite-hub/gateways";
|
|
2
|
+
import { Diagnostic } from "nostics";
|
|
3
|
+
/** The value that you map back to your data. It must be unique within its group. */
|
|
4
|
+
type ChoiceValue = string | number;
|
|
5
|
+
/** One option of a group. `value` is yours, `label`, `aliases`, and `description` are what the model reads. */
|
|
6
|
+
interface ChoiceOption<TValue extends ChoiceValue = ChoiceValue> {
|
|
7
|
+
/** Other names for the option, such as codes, abbreviations, or translations. */
|
|
8
|
+
aliases?: readonly string[];
|
|
9
|
+
/** What the option is about. An `infer` group needs it to choose an option that the text does not name. */
|
|
10
|
+
description?: string;
|
|
11
|
+
/** What people call the option. */
|
|
12
|
+
label: string;
|
|
13
|
+
/** Your id for the option. It comes back in the selection. */
|
|
14
|
+
value: TValue;
|
|
15
|
+
}
|
|
16
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
17
|
+
/** A set of options that belong to one decision, such as one filter. */
|
|
18
|
+
interface ChoiceGroup<TValue extends ChoiceValue = ChoiceValue> {
|
|
19
|
+
/** Tells the model how to read this group. Keep it short and specific to your data. */
|
|
20
|
+
hints?: string;
|
|
21
|
+
/**
|
|
22
|
+
* `false` (default): choose only an option that the text names. `true`: choose the option that fits the text best,
|
|
23
|
+
* also when the text does not name it, such as a project for a bug report. Needs `multiple: false`.
|
|
24
|
+
* An `infer` group has no "none" answer. Add an option for "anything else" if you need one.
|
|
25
|
+
*/
|
|
26
|
+
infer?: boolean;
|
|
27
|
+
/** What people call the group, such as "Supplier". */
|
|
28
|
+
label: string;
|
|
29
|
+
/** `true` (default): any number of options, each included or excluded. `false`: at most one option. */
|
|
30
|
+
multiple?: boolean;
|
|
31
|
+
/** 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()`. */
|
|
32
|
+
options: readonly ChoiceOption<TValue>[] | ((context: never) => MaybePromise<readonly ChoiceOption<TValue>[]>);
|
|
33
|
+
}
|
|
34
|
+
type ChoiceGroups = Record<string, ChoiceGroup>;
|
|
35
|
+
interface ChoicesLimits {
|
|
36
|
+
/** Most options in one group. Default 100. */
|
|
37
|
+
options: number;
|
|
38
|
+
/** Most groups. Default 40. */
|
|
39
|
+
groups: number;
|
|
40
|
+
/** Longest text in characters. Default 300. */
|
|
41
|
+
text: number;
|
|
42
|
+
/** Most options in all groups together. Default 100. */
|
|
43
|
+
totalOptions: number;
|
|
44
|
+
}
|
|
45
|
+
interface ChoicesThresholds {
|
|
46
|
+
/** The lowest probability that decides one option. Default 0.5. */
|
|
47
|
+
option?: number;
|
|
48
|
+
/** The lowest probability that the options can express the text. Default 0.6. Not asked when every group infers. */
|
|
49
|
+
supported?: number;
|
|
50
|
+
}
|
|
51
|
+
interface ChoicesDefinition<TGroups extends ChoiceGroups> {
|
|
52
|
+
/** Asks TypeSafe Jev, or any object with `ask()`: `typesafe()`, `vercel()`, or `cloudflare()` from `vite-hub/gateways`. Set `gateway` or `model`. */
|
|
53
|
+
gateway?: {
|
|
54
|
+
ask: AiGatewayAsk;
|
|
55
|
+
};
|
|
56
|
+
groups: TGroups;
|
|
57
|
+
/** Tells the model what the options are about. It is added to every question. */
|
|
58
|
+
hints?: string;
|
|
59
|
+
limits?: Partial<ChoicesLimits>;
|
|
60
|
+
/** Asks any AI SDK model instead of Jev, such as `openai("gpt-5.1-mini")`. It needs the `ai` package. Set `gateway` or `model`. */
|
|
61
|
+
model?: AskModel;
|
|
62
|
+
/** A label for logs and the CLI. It never connects anything. */
|
|
63
|
+
name?: string;
|
|
64
|
+
thresholds?: ChoicesThresholds;
|
|
65
|
+
}
|
|
66
|
+
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;
|
|
67
|
+
type GroupValue<TGroup> = TGroup extends {
|
|
68
|
+
options: infer TOptions;
|
|
69
|
+
} ? OptionValue<TOptions> : never;
|
|
70
|
+
/** A group with `multiple` left as `true`: the options the text includes and excludes. */
|
|
71
|
+
interface MultipleSelection<TValue extends ChoiceValue = ChoiceValue> {
|
|
72
|
+
exclude: TValue[];
|
|
73
|
+
include: TValue[];
|
|
74
|
+
}
|
|
75
|
+
/** A group with `multiple: false`: the best option, or `null`, and every option by probability. */
|
|
76
|
+
interface SingleSelection<TValue extends ChoiceValue = ChoiceValue> {
|
|
77
|
+
/** The probability of `value`, from 0 to 1. It is `0` when `value` is `null`. */
|
|
78
|
+
confidence: number;
|
|
79
|
+
/** Every option, from the most to the least likely. */
|
|
80
|
+
ranked: {
|
|
81
|
+
probability: number;
|
|
82
|
+
value: TValue;
|
|
83
|
+
}[];
|
|
84
|
+
/** The best option when it is above `thresholds.option`, else `null`. */
|
|
85
|
+
value: TValue | null;
|
|
86
|
+
}
|
|
87
|
+
/** The result for each group, typed from the options that you declared. */
|
|
88
|
+
type ChoicesSelection<TGroups> = { [K in keyof TGroups]: TGroups[K] extends {
|
|
89
|
+
multiple: false;
|
|
90
|
+
} ? SingleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>> : MultipleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>>; };
|
|
91
|
+
/**
|
|
92
|
+
* Why `resolve()` returned no selection. Check `error.code`. `DECISIONS_R0002`: a group or option is invalid or over a
|
|
93
|
+
* limit. `DECISIONS_R0003`: the text is empty or too long. `DECISIONS_R0004`: the options cannot express the text.
|
|
94
|
+
* `DECISIONS_R0005`: the gateway request failed, with the gateway error in `cause`. `DECISIONS_R0006`: the model left a
|
|
95
|
+
* question without an answer. `defineChoices()` throws `DECISIONS_R0001`, so it never comes back here.
|
|
96
|
+
*/
|
|
97
|
+
type ChoicesError = Diagnostic<unknown, "DECISIONS_R0002"> | Diagnostic<unknown, "DECISIONS_R0003"> | Diagnostic<unknown, "DECISIONS_R0004"> | Diagnostic<unknown, "DECISIONS_R0005"> | Diagnostic<unknown, "DECISIONS_R0006">;
|
|
98
|
+
type ChoicesResult<TData> = readonly [error: ChoicesError, data?: undefined] | readonly [error: undefined, data: TData];
|
|
99
|
+
interface ChoicesRequest<TContext> {
|
|
100
|
+
/** Passed to `options` functions. Put what they need here, such as the tenant. */
|
|
101
|
+
context: TContext;
|
|
102
|
+
/**
|
|
103
|
+
* Receives the model, provider, and token counts when the gateway reports usage.
|
|
104
|
+
* Jev can report usage for multiple batches in one `resolve()`. With `model`, this runs at most once.
|
|
105
|
+
*/
|
|
106
|
+
onUsage?: AiGatewayAskOptions["onUsage"];
|
|
107
|
+
/** Cancels the request to the gateway. */
|
|
108
|
+
signal?: AbortSignal;
|
|
109
|
+
}
|
|
110
|
+
/** What `resolve()` would send, without sending it. */
|
|
111
|
+
interface ChoicesPlan {
|
|
112
|
+
/** The questions for `gateway.ask()`. One per option of a multiple group, one per single group, and `supported` unless every group infers. */
|
|
113
|
+
questions: Record<string, unknown>;
|
|
114
|
+
/** The state for `gateway.ask()`. */
|
|
115
|
+
state: {
|
|
116
|
+
groups: {
|
|
117
|
+
hints?: string;
|
|
118
|
+
infer?: true;
|
|
119
|
+
label: string;
|
|
120
|
+
multiple: boolean;
|
|
121
|
+
options: {
|
|
122
|
+
aliases?: readonly string[];
|
|
123
|
+
label: string;
|
|
124
|
+
value: ChoiceValue;
|
|
125
|
+
}[];
|
|
126
|
+
}[];
|
|
127
|
+
query: string;
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
type UnionToIntersection<TUnion> = (TUnion extends unknown ? (value: TUnion) => void : never) extends ((value: infer TIntersection) => void) ? TIntersection : never;
|
|
131
|
+
type OptionsContext<TGroup> = TGroup extends {
|
|
132
|
+
options: (context: infer TContext) => unknown;
|
|
133
|
+
} ? TContext : never;
|
|
134
|
+
/** The `context` that `resolve()` needs: the parameter types of the `options` functions of the groups. `unknown` when no group needs one. */
|
|
135
|
+
type GroupsContext<TGroups> = UnionToIntersection<{ [K in keyof TGroups]: OptionsContext<TGroups[K]>; }[keyof TGroups]>;
|
|
136
|
+
type ChoicesArgs<TContext> = unknown extends TContext ? [request?: Omit<ChoicesRequest<unknown>, "context">] : [request: ChoicesRequest<TContext> & {
|
|
137
|
+
context: TContext;
|
|
138
|
+
}];
|
|
139
|
+
interface Choices<TGroups extends ChoiceGroups> {
|
|
140
|
+
/** Shows the questions and the state that `resolve()` would send. Nothing leaves your server. */
|
|
141
|
+
inspect: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesPlan>>;
|
|
142
|
+
readonly name: string | undefined;
|
|
143
|
+
/** Asks the gateway which options the text names. It returns `[error, selection]` and never throws. */
|
|
144
|
+
resolve: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesSelection<TGroups>>>;
|
|
145
|
+
}
|
|
146
|
+
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/dist/vue.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Ref } from "vue";
|
|
2
|
-
//#region src/vue.d.ts
|
|
3
2
|
/** Any Choices object. Its `resolve()` parameters do not matter here. */
|
|
4
3
|
export interface ChoicesLike {
|
|
5
4
|
resolve: (text: never, ...args: never[]) => Promise<unknown>;
|
|
@@ -50,5 +49,4 @@ export interface UseChoicesResult<TSelection> {
|
|
|
50
49
|
* `import type`, so no server code reaches the browser.
|
|
51
50
|
*/
|
|
52
51
|
export declare function useChoices<TChoices extends ChoicesLike>(options: UseChoicesOptions<ChoicesSelectionOf<TChoices>>): UseChoicesResult<ChoicesSelectionOf<TChoices>>;
|
|
53
|
-
export declare function useChoices<TSelection>(options: UseChoicesOptions<TSelection>): UseChoicesResult<TSelection>;
|
|
54
|
-
//#endregion
|
|
52
|
+
export declare function useChoices<TSelection>(options: UseChoicesOptions<TSelection>): UseChoicesResult<TSelection>;
|
package/dist/vue.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { onScopeDispose, readonly, ref, watch } from "vue";
|
|
2
|
-
|
|
2
|
+
// src/vue.ts
|
|
3
3
|
function toError(value) {
|
|
4
4
|
return value instanceof Error ? value : new Error(String(value));
|
|
5
5
|
}
|
|
@@ -75,5 +75,4 @@ function useChoices(options) {
|
|
|
75
75
|
text
|
|
76
76
|
};
|
|
77
77
|
}
|
|
78
|
-
//#endregion
|
|
79
78
|
export { useChoices };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vite-hub/choices",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
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,19 +51,19 @@
|
|
|
46
51
|
"./package.json": "./package.json"
|
|
47
52
|
},
|
|
48
53
|
"dependencies": {
|
|
49
|
-
"@vite-hub/gateways": "0.
|
|
54
|
+
"@vite-hub/gateways": "0.5.1",
|
|
50
55
|
"nostics": "1.4.0"
|
|
51
56
|
},
|
|
52
57
|
"devDependencies": {
|
|
53
|
-
"@types/node": "^24.19.
|
|
58
|
+
"@types/node": "^24.19.2",
|
|
54
59
|
"@vite-hub/internal": "0.0.1",
|
|
55
|
-
"ai": "7.0.
|
|
60
|
+
"ai": "7.0.179",
|
|
56
61
|
"publint": "^0.3.25",
|
|
57
62
|
"typescript": "^6.0.3",
|
|
58
|
-
"vite": "^8.
|
|
59
|
-
"vite-plus": "^
|
|
60
|
-
"vitest": "
|
|
61
|
-
"vue": "3.5.
|
|
63
|
+
"vite": "^8.3.8",
|
|
64
|
+
"vite-plus": "^1.7.0",
|
|
65
|
+
"vitest": "5.1.0",
|
|
66
|
+
"vue": "3.5.46"
|
|
62
67
|
},
|
|
63
68
|
"peerDependencies": {
|
|
64
69
|
"vite": ">=8.0.0",
|