@vite-hub/choices 0.0.0 → 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/dist/index.js ADDED
@@ -0,0 +1,345 @@
1
+ import { t as choicesDiagnostics } from "./diagnostics-BubnKF2J.js";
2
+ import { t as resolveSelection } from "./selection-gateway-D2jci9t-.js";
3
+ import { ask, askWithModel } from "@vite-hub/gateways";
4
+ import { getPublicAiGatewayDiagnostic } from "@vite-hub/gateways/internal";
5
+ //#region src/choices.ts
6
+ const defaultLimits = {
7
+ groups: 40,
8
+ options: 100,
9
+ text: 300,
10
+ totalOptions: 100
11
+ };
12
+ const defaultThresholds = {
13
+ option: .5,
14
+ supported: .6
15
+ };
16
+ const noneLabel = "(none)";
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
+ 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.";
19
+ const noneCriteria = "Choose none when the text does not mention this option. Do not infer options from context or from other options. Unspecified options stay none even when another option is included or excluded.";
20
+ const supportedTrue = "Every constraint in the text can be expressed with the listed options, including several options in one group, constraints across groups, exclusions, and a prefix or suffix that matches several options. Accept fragments, omitted group names, shorthand, and typos when a real option matches.";
21
+ const supportedFalse = "The text needs a value or a capability that the options do not have, such as a numeric comparison, an unknown name, or OR between different groups. Also false when the text names no option at all. Do not reject a recognizable option because of shorthand or a minor typo.";
22
+ function define(message) {
23
+ throw choicesDiagnostics.DECISIONS_R0001({ message: `[vitehub] ${message}` });
24
+ }
25
+ function fail(code, message) {
26
+ return choicesDiagnostics[code]({ message: `[vitehub] ${message}` });
27
+ }
28
+ function unsupportedText() {
29
+ return fail("DECISIONS_R0004", "The options cannot express that text. Try another name, or use the options directly.");
30
+ }
31
+ function gatewayFailed(cause) {
32
+ const diagnostic = getPublicAiGatewayDiagnostic(cause);
33
+ return choicesDiagnostics.DECISIONS_R0005({
34
+ cause,
35
+ fix: diagnostic?.fix,
36
+ reason: diagnostic?.message.replace(/^\[vitehub\]\s*/, "")
37
+ });
38
+ }
39
+ function probability(value) {
40
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;
41
+ }
42
+ function checkDefinition(definition, limits, thresholds) {
43
+ const { gateway, model } = definition;
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.");
45
+ if (model === void 0 && typeof gateway?.ask !== "function") define("defineChoices() needs a gateway with ask(), such as typesafe() or vercel() from vite-hub/gateways.");
46
+ const entries = Object.entries(definition.groups ?? {});
47
+ if (!entries.length) define("defineChoices() needs at least one group.");
48
+ if (entries.length > limits.groups) define(`defineChoices() has ${entries.length} groups. The limit is ${limits.groups}.`);
49
+ for (const [key, group] of entries) {
50
+ if (typeof group?.label !== "string" || !group.label.trim()) define(`Group "${key}" needs a label.`);
51
+ if (!Array.isArray(group.options) && typeof group.options !== "function") define(`Group "${key}" options must be a list or a function.`);
52
+ if (group.multiple !== void 0 && typeof group.multiple !== "boolean") define(`Group "${key}" multiple must be true or false.`);
53
+ if (group.infer !== void 0 && typeof group.infer !== "boolean") define(`Group "${key}" infer must be true or false.`);
54
+ if (group.infer && group.multiple !== false) define(`Group "${key}" infers one option, so it needs multiple: false.`);
55
+ }
56
+ for (const [name, value] of Object.entries(thresholds)) if (!Number.isFinite(value) || value < 0 || value > 1) define(`thresholds.${name} must be a number from 0 to 1.`);
57
+ for (const [name, value] of Object.entries(limits)) if (!Number.isInteger(value) || value < 1) define(`limits.${name} must be a positive integer.`);
58
+ return model === void 0 ? gateway : askWithModel(model);
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
+ }
65
+ async function loadGroups(definition, limits, context) {
66
+ const keys = Object.keys(definition.groups);
67
+ const loaded = [];
68
+ let total = 0;
69
+ for (const key of keys) {
70
+ const group = definition.groups[key];
71
+ let options;
72
+ try {
73
+ options = typeof group.options === "function" ? await group.options(context) : group.options;
74
+ } catch (cause) {
75
+ return { error: choicesDiagnostics.DECISIONS_R0002({
76
+ message: `[vitehub] The options of group "${key}" failed to load.`,
77
+ cause
78
+ }) };
79
+ }
80
+ if (!Array.isArray(options)) return { error: fail("DECISIONS_R0002", `The options of group "${key}" must be a list.`) };
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.`) };
82
+ const multiple = group.multiple !== false;
83
+ const values = /* @__PURE__ */ new Set();
84
+ const labels = /* @__PURE__ */ new Set();
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.`) };
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.`) };
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.`) };
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.`) };
92
+ values.add(option.value);
93
+ if (!multiple) {
94
+ if (option.label === noneLabel || labels.has(option.label)) return { error: fail("DECISIONS_R0002", `Group "${key}" is single-select, so labels must be unique and cannot be "${noneLabel}". Found "${option.label}".`) };
95
+ labels.add(option.label);
96
+ }
97
+ }
98
+ total += options.length;
99
+ loaded.push({
100
+ group,
101
+ infer: group.infer === true,
102
+ key,
103
+ multiple,
104
+ options
105
+ });
106
+ }
107
+ if (total === 0) return { error: fail("DECISIONS_R0002", "No group has options. Nothing can be asked.") };
108
+ if (total > limits.totalOptions) return { error: fail("DECISIONS_R0002", `The groups have ${total} options. The limit is ${limits.totalOptions}. Narrow the options before you ask.`) };
109
+ return { groups: loaded };
110
+ }
111
+ function describe(option) {
112
+ return option.aliases?.length ? `${option.label} (also ${option.aliases.map((alias) => JSON.stringify(alias)).join(", ")})` : option.label;
113
+ }
114
+ function optionCriteria(option) {
115
+ const parts = [option.description?.trim(), option.aliases?.length ? `Also called ${option.aliases.join(", ")}.` : void 0].filter(Boolean);
116
+ return parts.length ? parts.join(" ") : null;
117
+ }
118
+ function optionInstructions(group, option, hints) {
119
+ return [
120
+ `For the ${JSON.stringify(group.group.label)} group, does the text directly request or directly negate the option ${JSON.stringify(describe(option))} (value ${JSON.stringify(option.value)})?`,
121
+ option.description?.trim() && `The option means: ${option.description.trim()}`,
122
+ "Evaluate this option separately from all others. A requested prefix or suffix applies to every matching option. If the text names a different group for a phrase, do not reuse that phrase to select this option.",
123
+ group.group.hints,
124
+ hints
125
+ ].filter(Boolean).join(" ");
126
+ }
127
+ function singleInstructions(group, hints) {
128
+ if (group.infer) return [
129
+ `For the ${JSON.stringify(group.group.label)} group, which one option fits the text best?`,
130
+ "The text does not have to name the option. Infer it from what the text is about, every fact in the text, and the option descriptions. Prefer the most specific option that fits.",
131
+ group.group.hints,
132
+ hints
133
+ ].filter(Boolean).join(" ");
134
+ return [
135
+ `For the ${JSON.stringify(group.group.label)} group, which one option does the text choose?`,
136
+ `Choose ${JSON.stringify(noneLabel)} when the text does not name an option of this group. Do not infer an option from context or from other groups.`,
137
+ group.group.hints,
138
+ hints
139
+ ].filter(Boolean).join(" ");
140
+ }
141
+ function needsSupported(groups) {
142
+ return groups.some((group) => !group.infer && group.options.length);
143
+ }
144
+ function supportedQuestion(groups, hints) {
145
+ const checked = groups.filter((group) => !group.infer).map((group) => JSON.stringify(group.group.label));
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(" "), {
147
+ false: supportedFalse,
148
+ true: supportedTrue
149
+ });
150
+ return ask.chance([
151
+ `Judge only the ${checked.join(", ")} ${checked.length === 1 ? "group" : "groups"}. Ignore every group with infer: true.`,
152
+ "Can every constraint that the text sets for these groups be expressed with their options? Be permissive about ordinary phrasing, shorthand, prefixes, and typos, but require a real match to supplied options.",
153
+ hints
154
+ ].filter(Boolean).join(" "), {
155
+ false: "The text needs a value or a capability that the options of these groups do not have, such as a numeric comparison, an unknown name, or OR between different groups. Do not reject a recognizable option because of shorthand or a minor typo.",
156
+ true: `${supportedTrue} Also true when the text sets no constraint for these groups.`
157
+ });
158
+ }
159
+ function buildPlan(text, groups, hints) {
160
+ const questions = {};
161
+ if (needsSupported(groups)) questions.supported = supportedQuestion(groups, hints);
162
+ groups.forEach((group, groupIndex) => {
163
+ if (!group.options.length) return;
164
+ if (group.infer && group.options.length === 1) return;
165
+ if (group.multiple) {
166
+ group.options.forEach((option, optionIndex) => {
167
+ questions[`g${groupIndex}_o${optionIndex}`] = ask.choice(optionInstructions(group, option, hints), {
168
+ exclude: excludeCriteria,
169
+ include: includeCriteria,
170
+ none: noneCriteria
171
+ });
172
+ });
173
+ return;
174
+ }
175
+ const criteria = Object.fromEntries(group.options.map((option) => [option.label, optionCriteria(option)]));
176
+ questions[`g${groupIndex}`] = ask.choice(singleInstructions(group, hints), group.infer ? criteria : {
177
+ ...criteria,
178
+ [noneLabel]: "The text does not name an option of this group."
179
+ });
180
+ });
181
+ return {
182
+ questions,
183
+ state: {
184
+ groups: groups.map((group) => ({
185
+ ...group.group.hints ? { hints: group.group.hints } : {},
186
+ ...group.infer ? { infer: true } : {},
187
+ label: group.group.label,
188
+ multiple: group.multiple,
189
+ options: group.options.map((option) => ({
190
+ ...option.aliases?.length ? { aliases: option.aliases } : {},
191
+ label: option.label,
192
+ value: option.value
193
+ }))
194
+ })),
195
+ query: text
196
+ }
197
+ };
198
+ }
199
+ function readSelection(answers, groups, threshold) {
200
+ const selection = {};
201
+ for (const [groupIndex, group] of groups.entries()) {
202
+ if (!group.multiple) {
203
+ const answer = answers[`g${groupIndex}`];
204
+ if (!group.options.length) {
205
+ selection[group.key] = {
206
+ confidence: 0,
207
+ ranked: [],
208
+ value: null
209
+ };
210
+ continue;
211
+ }
212
+ const [only] = group.options;
213
+ if (group.infer && only && group.options.length === 1) {
214
+ selection[group.key] = {
215
+ confidence: 1,
216
+ ranked: [{
217
+ probability: 1,
218
+ value: only.value
219
+ }],
220
+ value: only.value
221
+ };
222
+ continue;
223
+ }
224
+ if (typeof answer !== "object" || answer.type !== "choice") return [fail("DECISIONS_R0006", `The model did not answer the group "${group.key}".`)];
225
+ const byLabel = new Map(group.options.map((option) => [option.label, option.value]));
226
+ const ranked = [...byLabel].map(([label, value]) => ({
227
+ probability: probability(Reflect.get(answer.probabilities, label)),
228
+ value
229
+ })).sort((a, b) => b.probability - a.probability);
230
+ const chosen = answer.choice === noneLabel ? void 0 : byLabel.get(answer.choice);
231
+ const chance = probability(Reflect.get(answer.probabilities, answer.choice));
232
+ selection[group.key] = chosen !== void 0 && chance >= threshold ? {
233
+ confidence: chance,
234
+ ranked,
235
+ value: chosen
236
+ } : {
237
+ confidence: 0,
238
+ ranked,
239
+ value: null
240
+ };
241
+ continue;
242
+ }
243
+ const include = [];
244
+ const exclude = [];
245
+ for (const [optionIndex, option] of group.options.entries()) {
246
+ const answer = answers[`g${groupIndex}_o${optionIndex}`];
247
+ if (typeof answer !== "object" || answer.type !== "choice") return [fail("DECISIONS_R0006", `The model did not answer the option "${option.label}" of group "${group.key}".`)];
248
+ if (answer.choice === "none" || probability(Reflect.get(answer.probabilities, answer.choice)) < threshold) continue;
249
+ if (answer.choice === "include") include.push(option.value);
250
+ else exclude.push(option.value);
251
+ }
252
+ selection[group.key] = {
253
+ exclude,
254
+ include
255
+ };
256
+ }
257
+ return [void 0, selection];
258
+ }
259
+ /**
260
+ * Declares the options that text can choose from, and how to ask a gateway about them.
261
+ * Nothing here knows your UI, your routes, or your store. Call `resolve()` wherever you run server code.
262
+ */
263
+ function defineChoices(definition) {
264
+ const limits = {
265
+ ...defaultLimits,
266
+ ...definition.limits
267
+ };
268
+ const thresholds = {
269
+ ...defaultThresholds,
270
+ ...definition.thresholds
271
+ };
272
+ const base = definition;
273
+ const asker = checkDefinition(base, limits, thresholds);
274
+ const hints = definition.hints?.trim() ?? "";
275
+ async function prepare(text, request) {
276
+ const trimmed = typeof text === "string" ? text.trim() : "";
277
+ if (!trimmed) return [fail("DECISIONS_R0003", "The text is empty. Nothing was asked.")];
278
+ if (trimmed.length > limits.text) return [fail("DECISIONS_R0003", `The text has ${trimmed.length} characters. The limit is ${limits.text}.`)];
279
+ const loaded = await loadGroups(base, limits, request?.context);
280
+ if ("error" in loaded) return [loaded.error];
281
+ const plan = buildPlan(trimmed, loaded.groups, hints);
282
+ return [void 0, {
283
+ groups: loaded.groups,
284
+ plan,
285
+ text: trimmed
286
+ }];
287
+ }
288
+ return {
289
+ async inspect(text, ...args) {
290
+ const [error, prepared] = await prepare(text, args[0]);
291
+ return error ? [error] : [void 0, prepared.plan];
292
+ },
293
+ name: definition.name,
294
+ async resolve(text, ...args) {
295
+ const request = args[0];
296
+ const [error, prepared] = await prepare(text, request);
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
+ }
307
+ let answers = {};
308
+ if (Object.keys(prepared.plan.questions).length) try {
309
+ const [askError, asked] = await asker.ask(prepared.plan.state, prepared.plan.questions, {
310
+ signal: request?.signal,
311
+ ...request?.onUsage && { onUsage: request.onUsage }
312
+ });
313
+ if (askError) return [gatewayFailed(askError)];
314
+ answers = asked;
315
+ } catch (cause) {
316
+ return [gatewayFailed(cause)];
317
+ }
318
+ if (needsSupported(prepared.groups)) {
319
+ const supported = answers.supported;
320
+ if (typeof supported !== "object" || supported.type !== "chance") return [fail("DECISIONS_R0006", "The model did not answer the supported check.")];
321
+ if (probability(supported.chance) < thresholds.supported) return [unsupportedText()];
322
+ }
323
+ const [readError, selection] = readSelection(answers, prepared.groups, thresholds.option);
324
+ if (readError) return [readError];
325
+ return [void 0, selection];
326
+ }
327
+ };
328
+ }
329
+ //#endregion
330
+ //#region src/options.ts
331
+ /** Maps your own items to options. This is the bridge from your data to Choices. */
332
+ function toOptions(items, map) {
333
+ return items.map((item) => {
334
+ const aliases = map.aliases?.(item);
335
+ const description = map.description?.(item)?.trim();
336
+ return {
337
+ label: map.label(item),
338
+ value: map.value(item),
339
+ ...aliases?.length ? { aliases } : {},
340
+ ...description ? { description } : {}
341
+ };
342
+ });
343
+ }
344
+ //#endregion
345
+ export { defineChoices, toOptions };
@@ -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 };