@vite-hub/choices 0.6.1 → 0.7.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
@@ -12,6 +12,8 @@ pnpm add @vite-hub/choices @vite-hub/gateways advocaat
12
12
 
13
13
  The model call goes through an AI gateway that has `ask()`, such as `typesafe()` or `vercel()` from `@vite-hub/gateways`, to TypeSafe Jev. The gateway reads its key from the environment. The key stays on your server. To use another model, pass any AI SDK model as `model` instead of `gateway`, and install `ai`.
14
14
 
15
+ Without the key, a gateway preset still answers in dev and tests, by word match, and prints the warning `DECISIONS_KEYLESS_WORD_MATCH` one time. In production, a missing key returns `DECISIONS_R0005`. A Nitro production build counts as production, and so does `NODE_ENV=production`. Word match finds only option labels and aliases, so set the key before you judge the results.
16
+
15
17
  ## Use
16
18
 
17
19
  ```ts fragment
@@ -130,6 +132,7 @@ A newer request cancels the older one through `signal`, and the older result nev
130
132
  | `DECISIONS_R0004` | The model says the options cannot express the text. |
131
133
  | `DECISIONS_R0005` | The gateway request failed. `message` and `fix` show known, client-safe gateway diagnostics. Other failures use a generic message. `cause` has the original error for server-side inspection. |
132
134
  | `DECISIONS_R0006` | The model answer misses a question. |
135
+ | `DECISIONS_KEYLESS_WORD_MATCH` | A warning, not an error: the gateway has no API key outside production, so `resolve()` answered by word match. |
133
136
 
134
137
  `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.
135
138
 
@@ -144,7 +147,7 @@ const choices = defineChoices({ gateway: selectionGateway<typeof groups>({ suppl
144
147
  await choices.resolve('anything') // [undefined, { supplier: { include: ['S2'], exclude: [] }, chart: { value: 'bar', ... } }]
145
148
  ```
146
149
 
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`.
150
+ 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. A gateway preset without its key uses it outside production. For a failing provider, pass `scriptedAsk()` from `@vite-hub/gateways/testing`.
148
151
 
149
152
  ## Inspect
150
153
 
package/dist/cli.d.ts CHANGED
@@ -58,6 +58,7 @@ interface ProvisionStep {
58
58
  id: string;
59
59
  provider: ProvisionProvider;
60
60
  plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
61
+ hasResources?: (context: Pick<ProvisionContext, "env">) => boolean;
61
62
  /** Describes the Provision State this step records. Runs without network access, also without credentials. */
62
63
  recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
63
64
  }
@@ -74,10 +75,13 @@ interface ViteHubCliSpawnResult {
74
75
  signal?: NodeJS.Signals | null;
75
76
  /** The output of the child when `stdout` is `pipe`. */
76
77
  stdout?: string;
78
+ /** The error output of the child when `stderr` is `pipe`. */
79
+ stderr?: string;
77
80
  }
78
81
  interface ViteHubCliSpawnOptions {
79
82
  cwd?: string;
80
83
  env?: NodeJS.ProcessEnv;
84
+ onOutput?: (text: string, stream: "stdout" | "stderr") => void;
81
85
  stderr?: "inherit" | "pipe";
82
86
  /** `ignore` gives the child no terminal input, so a tool that asks questions on a terminal does not ask. */
83
87
  stdin?: "ignore" | "inherit";
@@ -85,7 +89,17 @@ interface ViteHubCliSpawnOptions {
85
89
  stdout?: "inherit" | "pipe" | "stderr";
86
90
  }
87
91
  type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
92
+ /** Where a call to an app goes through the Console: the operation endpoint of the app's Console project, and the token of `vitehub login`. */
93
+ interface ViteHubCliConsoleRoute {
94
+ authorization: string;
95
+ target: string;
96
+ }
88
97
  interface ViteHubCliContext extends ViteHubCliStreams {
98
+ /**
99
+ * Finds the app at `url` in the Console of `vitehub login` and returns the route that lets the Console sign the call.
100
+ * Returns nothing when the command must call the app directly, such as when a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` is set.
101
+ */
102
+ consoleRoute?: (url: string, signal: AbortSignal) => Promise<ViteHubCliConsoleRoute | undefined>;
89
103
  cwd: string;
90
104
  env: NodeJS.ProcessEnv;
91
105
  /** Replaces `fetch` for commands that call a running app, so tests need no server. */
@@ -104,6 +118,7 @@ interface ViteHubCliContext extends ViteHubCliStreams {
104
118
  spawn: ViteHubCliSpawn;
105
119
  }
106
120
  interface ViteHubCliProvision {
121
+ env?: NodeJS.ProcessEnv;
107
122
  rootDir: string;
108
123
  steps: readonly ProvisionStep[];
109
124
  }
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as choicesDiagnostics } from "./diagnostics-D9hxehC1.js";
1
+ import { t as choicesDiagnostics } from "./diagnostics-Canya8Hh.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";
@@ -36,6 +36,10 @@ const choicesDiagnostics = /*#__PURE__*/ defineDiagnostics({
36
36
  why: ({ problem }) => problem,
37
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
38
  },
39
+ DECISIONS_KEYLESS_WORD_MATCH: {
40
+ why: ({ reason }) => `[vitehub] ${reason} This is not a production build, so Choices answers by word match until the key is set. Word match is not a model: it finds only exact option labels and aliases. In production, the missing key returns DECISIONS_R0005.`,
41
+ fix: "Set the API key that the message names, in the Server Env, to ask the model. To answer by word match on purpose, pass `wordGateway()` from `vite-hub/choices/testing` as the gateway."
42
+ },
39
43
  DECISIONS_TESTING_SELECTION_INVALID: {
40
44
  why: ({ problem }) => `[vitehub] ${problem}`,
41
45
  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."
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
- import { t as choicesDiagnostics } from "./diagnostics-D9hxehC1.js";
2
- import { t as resolveSelection } from "./selection-gateway-BB8o3bIT.js";
1
+ import { t as choicesDiagnostics } from "./diagnostics-Canya8Hh.js";
2
+ import { r as resolveSelection, t as keylessWordGateway } from "./word-gateway-BjWCwLP_.js";
3
3
  import { ask, askWithModel } from "@vite-hub/gateways";
4
4
  import { getPublicAiGatewayDiagnostic } from "@vite-hub/gateways/internal";
5
+ import { formatDiagnostic } from "nostics";
5
6
  // src/choices.ts
6
7
  const defaultLimits = {
7
8
  groups: 40,
@@ -36,6 +37,14 @@ function gatewayFailed(cause) {
36
37
  reason: diagnostic?.message.replace(/^\[vitehub\]\s*/, "")
37
38
  });
38
39
  }
40
+ function isProduction() {
41
+ if (import.meta.dev === false) return true;
42
+ return globalThis.process?.env?.NODE_ENV === "production";
43
+ }
44
+ function missingKey(cause) {
45
+ if (!(cause instanceof Error) || Reflect.get(cause, "code") !== "GATEWAYS_R0002") return;
46
+ return getPublicAiGatewayDiagnostic(cause)?.message.replace(/^\[vitehub\]\s*/, "") ?? cause.message;
47
+ }
39
48
  function probability(value) {
40
49
  return typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;
41
50
  }
@@ -272,6 +281,25 @@ function defineChoices(definition) {
272
281
  const base = definition;
273
282
  const asker = checkDefinition(base, limits, thresholds);
274
283
  const hints = definition.hints?.trim() ?? "";
284
+ let words;
285
+ const keyless = definition.gateway !== void 0;
286
+ async function askGateway(plan, options) {
287
+ const questions = plan.questions;
288
+ let reason;
289
+ try {
290
+ const result = await asker.ask(plan.state, questions, options);
291
+ reason = missingKey(result[0]);
292
+ if (reason === void 0 || !keyless || isProduction()) return result;
293
+ } catch (cause) {
294
+ reason = missingKey(cause);
295
+ if (reason === void 0 || !keyless || isProduction()) throw cause;
296
+ }
297
+ if (!words) {
298
+ console.warn(formatDiagnostic(choicesDiagnostics.DECISIONS_KEYLESS_WORD_MATCH({ reason })));
299
+ words = keylessWordGateway();
300
+ }
301
+ return await words.ask(plan.state, questions, options);
302
+ }
275
303
  async function prepare(text, request) {
276
304
  const trimmed = typeof text === "string" ? text.trim() : "";
277
305
  if (!trimmed) return [fail("DECISIONS_R0003", "The text is empty. Nothing was asked.")];
@@ -306,7 +334,7 @@ function defineChoices(definition) {
306
334
  }
307
335
  let answers = {};
308
336
  if (Object.keys(prepared.plan.questions).length) try {
309
- const [askError, asked] = await asker.ask(prepared.plan.state, prepared.plan.questions, {
337
+ const [askError, asked] = await askGateway(prepared.plan, {
310
338
  signal: request?.signal,
311
339
  ...request?.onUsage && { onUsage: request.onUsage }
312
340
  });
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,15 @@
1
1
  import { g as GroupsContext, h as GroupValue, i as ChoiceValue, n as ChoiceGroups } from "./types-DNHgwMWj.js";
2
2
  import { AiGatewayAsk } from "@vite-hub/gateways";
3
+ /**
4
+ * An offline gateway that answers by word match, for get-started and local dev without an API key. It is not a model:
5
+ * an option is included when the text names its label or one of its aliases as whole words, and excluded when "except",
6
+ * "not", or "without" comes before that name. A single group without inference chooses the first named option that is
7
+ * not excluded. An infer group also matches words of five letters or more from the option descriptions. Text with the
8
+ * word "unsupported" fails the supported check, so you can see `DECISIONS_R0004`.
9
+ */
10
+ export declare function wordGateway(): {
11
+ ask: AiGatewayAsk;
12
+ };
3
13
  type MaybePromise<T> = T | Promise<T>;
4
14
  /** Return it from `selectionGateway()` to say that the options cannot express the text. `resolve()` returns `DECISIONS_R0004`. */
5
15
  export declare const unsupported: unique symbol;
@@ -33,14 +43,4 @@ type TestAnswer<TGroups extends ChoiceGroups> = TestSelection<TGroups> | typeof
33
43
  export declare function selectionGateway<TGroups extends ChoiceGroups = ChoiceGroups>(selection: TestAnswer<TGroups> | ((text: string, context: TestContext<TGroups>) => MaybePromise<TestAnswer<TGroups>>)): {
34
44
  ask: AiGatewayAsk;
35
45
  };
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
46
  export {};
package/dist/testing.js CHANGED
@@ -1,6 +1,5 @@
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";
1
+ import { t as choicesDiagnostics } from "./diagnostics-Canya8Hh.js";
2
+ import { n as wordGateway, r as resolveSelection } from "./word-gateway-BjWCwLP_.js";
4
3
  // src/testing.ts
5
4
  /** Return it from `selectionGateway()` to say that the options cannot express the text. `resolve()` returns `DECISIONS_R0004`. */
6
5
  const unsupported = Symbol("unsupported");
@@ -62,64 +61,4 @@ function selectionGateway(selection) {
62
61
  }
63
62
  };
64
63
  }
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
64
  export { selectionGateway, unsupported, wordGateway };
@@ -0,0 +1,72 @@
1
+ import { answers } from "@vite-hub/gateways/testing";
2
+ // src/selection-gateway.ts
3
+ /** Internal protocol shared by the production and testing entries, even across package copies. */
4
+ const resolveSelection = Symbol.for("vitehub.choices.resolveSelection");
5
+ // src/word-gateway.ts
6
+ function escapeRegExp(text) {
7
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8
+ }
9
+ const edge = String.raw`[\p{L}\p{M}\p{N}_]`;
10
+ function wordPattern(pattern) {
11
+ return new RegExp(`(?<!${edge})${pattern}(?!${edge})`, "u");
12
+ }
13
+ function matchOption(text, option) {
14
+ let named = false;
15
+ for (const name of [option.label, ...option.aliases ?? []]) {
16
+ if (!name.trim()) continue;
17
+ const pattern = escapeRegExp(name.toLowerCase());
18
+ if (!wordPattern(pattern).test(text)) continue;
19
+ if (wordPattern(String.raw`(?:except|not|without)\s+(?:${edge}+\s+)?${pattern}`).test(text)) return "exclude";
20
+ named = true;
21
+ }
22
+ return named ? "include" : "none";
23
+ }
24
+ /**
25
+ * An offline gateway that answers by word match, for get-started and local dev without an API key. It is not a model:
26
+ * an option is included when the text names its label or one of its aliases as whole words, and excluded when "except",
27
+ * "not", or "without" comes before that name. A single group without inference chooses the first named option that is
28
+ * not excluded. An infer group also matches words of five letters or more from the option descriptions. Text with the
29
+ * word "unsupported" fails the supported check, so you can see `DECISIONS_R0004`.
30
+ */
31
+ function wordGateway() {
32
+ return createWordGateway(true);
33
+ }
34
+ function keylessWordGateway() {
35
+ return createWordGateway(false);
36
+ }
37
+ function createWordGateway(unsupportedWord) {
38
+ const ask = async (state, questions, options) => {
39
+ options?.signal?.throwIfAborted();
40
+ const { groups, query } = state;
41
+ const text = query.toLowerCase();
42
+ const answer = (key, question) => {
43
+ if (key === "supported") return answers.chance(unsupportedWord && wordPattern("unsupported").test(text) ? .1 : .95);
44
+ const [, groupIndex, optionIndex] = /^g(\d+)(?:_o(\d+))?$/.exec(key) ?? [];
45
+ const group = groups[Number(groupIndex)];
46
+ if (!group || question.type !== "choice") return answers.first(question);
47
+ if (optionIndex !== void 0) return answers.choice(question, matchOption(text, group.options[Number(optionIndex)]), .9);
48
+ if (group.infer) {
49
+ const criteriaWords = (label) => {
50
+ const criteria = question.criteria[label];
51
+ return typeof criteria === "string" ? criteria.toLowerCase().match(/\w{5,}/g) ?? [] : [];
52
+ };
53
+ const fit = group.options.find((option) => matchOption(text, option) !== "none" || criteriaWords(option.label).some((word) => text.includes(word)));
54
+ return answers.choice(question, (fit ?? group.options[0]).label, fit ? .8 : Math.max(.4, 1 / group.options.length));
55
+ }
56
+ const best = group.options.find((option) => matchOption(text, option) === "include");
57
+ return answers.choice(question, best?.label ?? "(none)", best ? .8 : .9);
58
+ };
59
+ const entries = Object.entries(questions).map(([key, question]) => [key, answer(key, question)]);
60
+ options?.onUsage?.({
61
+ provider: "scripted",
62
+ usage: {
63
+ inputTokens: 0,
64
+ outputTokens: 0,
65
+ totalTokens: 0
66
+ }
67
+ });
68
+ return [void 0, Object.fromEntries(entries)];
69
+ };
70
+ return { ask };
71
+ }
72
+ export { wordGateway as n, resolveSelection as r, keylessWordGateway as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/choices",
3
- "version": "0.6.1",
3
+ "version": "0.7.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",
@@ -51,7 +51,7 @@
51
51
  "./package.json": "./package.json"
52
52
  },
53
53
  "dependencies": {
54
- "@vite-hub/gateways": "0.6.1",
54
+ "@vite-hub/gateways": "0.7.0",
55
55
  "nostics": "1.4.0"
56
56
  },
57
57
  "devDependencies": {
@@ -1,4 +0,0 @@
1
- // 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
- export { resolveSelection as t };