@r_masseater/oxlint-plugin-decision 0.3.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/README.md CHANGED
@@ -3,30 +3,33 @@
3
3
  > [!WARNING]
4
4
  > This package is experimental. Use at your own risk.
5
5
 
6
- [Oxlint](https://oxc.rs/docs/guide/usage/linter.html) rules written in plain English, answered by decision models on [OpenRouter](https://openrouter.ai).
6
+ [Oxlint](https://oxc.rs/docs/guide/usage/linter.html) rules written in plain English, answered by models on [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/) or by decision models on [OpenRouter](https://openrouter.ai).
7
7
 
8
- A rule is a question about a function, a call, a JSX element, or a whole file. Each match is sent to one or more decision models with the question, and the plugin reports an error when the answer the rule cares about clears its cutoff.
8
+ A rule is a question about a function, a call, a JSX element or a whole file. Each match is sent to one or more decision models with the question. The plugin reports an error when the answer the rule cares about clears its cutoff.
9
9
 
10
- Decision models do not write text. They return a probability for a yes/no question, or pick one of the options you list. That makes them fast and cheap enough to run over a codebase, and it is why every rule here is a question with a fixed set of answers.
10
+ Decision models do not write text. They return a probability for a yes/no question, or pick one of the options you list. That makes them fast and cheap enough to run over a codebase. It is also why every rule here is a question with a fixed set of answers.
11
11
 
12
12
  For ready-made rules, see [`@r_masseater/oxlint-plugin-decision-presets`](https://www.npmjs.com/package/@r_masseater/oxlint-plugin-decision-presets).
13
13
 
14
- This is a fork of [oxlint-plugin-jev](https://github.com/wobsoriano/oxlint-plugin-jev) by [Robert Soriano](https://github.com/wobsoriano), rebuilt on the OpenRouter Decisions API.
14
+ This is a fork of [oxlint-plugin-jev](https://github.com/wobsoriano/oxlint-plugin-jev) by [Robert Soriano](https://github.com/wobsoriano). It asks Cloudflare AI Gateway or the OpenRouter Decisions API.
15
15
 
16
16
  ## Install
17
17
 
18
18
  ```sh
19
19
  npm i -D oxlint @r_masseater/oxlint-plugin-decision
20
- export OPENROUTER_API_KEY="..." # https://openrouter.ai/settings/keys
20
+ export CLOUDFLARE_ACCOUNT_ID="..."
21
+ export CLOUDFLARE_API_TOKEN="..." # an account API token with Workers AI Read
21
22
  ```
22
23
 
23
- The plugin reads the key from the `OPENROUTER_API_KEY` environment variable. Without it, the plugin warns once and reports nothing. To read the key from a variable with another name, set `env` (see [Settings](#settings)). The key itself is never passed in code or config.
24
+ The default model runs on Workers AI through the account's AI Gateway, so it needs no other key. The plugin reads the account and the token from `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`. Without them, the plugin warns once and reports nothing. To read them from variables with other names, set `env` (see [Settings](#settings)). Neither is ever passed in code or config.
24
25
 
25
- In CI (when the `CI` environment variable is set), a run that could not reach a model fails instead of passing quietly. Set `ci: "skip"` to only warn there too.
26
+ Requests go to the gateway named `default`, which Cloudflare creates on the first request. `CLOUDFLARE_AI_GATEWAY_ID` picks another gateway. Its cache, logs and rate limits apply to every request.
27
+
28
+ In CI (when the `CI` environment variable is set), a run that could not reach a model fails instead of passing quietly. Set `ci: "skip"` to only warn there too. A provider that refuses for a spent budget only warns, even in CI. That is HTTP 402, or a 403 that names the budget.
26
29
 
27
30
  ## Write your rules
28
31
 
29
- The plugin ships no rules of its own. You write each rule with `defineDecisionRule` in a plugin file of your own, pass them to `createDecisionPlugin`, and load that file from `oxlint.config.ts`. For ready-made rules, use [`@r_masseater/oxlint-plugin-decision-presets`](https://www.npmjs.com/package/@r_masseater/oxlint-plugin-decision-presets).
32
+ The plugin ships no rules of its own. You write each rule with `defineDecisionRule` in a plugin file of your own and pass the rules to `createDecisionPlugin`. Then you load that file from `oxlint.config.ts`. For ready-made rules, use [`@r_masseater/oxlint-plugin-decision-presets`](https://www.npmjs.com/package/@r_masseater/oxlint-plugin-decision-presets).
30
33
 
31
34
  ```js
32
35
  // decision-plugin.mjs
@@ -54,7 +57,7 @@ export default createDecisionPlugin({
54
57
  });
55
58
  ```
56
59
 
57
- Each rule becomes an oxlint rule named `<plugin name>/<rule id>`, so you turn rules on and set their severity one by one, like any other oxlint rule. The plugin name defaults to `decision`.
60
+ Each rule becomes an oxlint rule named `<plugin name>/<rule id>`. You turn rules on and set their severity one by one, like any other oxlint rule. The plugin name defaults to `decision`.
58
61
 
59
62
  ```ts
60
63
  // oxlint.config.ts
@@ -101,7 +104,7 @@ The wording of the question is the rule, so be precise about what counts. "Does
101
104
 
102
105
  `select` decides from the AST which matches are worth a question, before any request is sent. It gets the matched ESTree node, as oxlint parsed it, and returns `true` to ask about it. Matches it rejects cost nothing.
103
106
 
104
- The second argument carries `context`, the oxlint rule context, and `name`, the match's name as source text, or `undefined` when it has none:
107
+ The second argument carries `context` and `name`. `context` is the oxlint rule context. `name` is the match's name as source text, or `undefined` when it has none.
105
108
 
106
109
  | Target | `name` |
107
110
  | ------------ | --------------------------------------------------------------------------- |
@@ -186,15 +189,18 @@ By default the model reads only the match. `context` sends more source with it,
186
189
  | `{ scope: "file" }` | The whole file. |
187
190
  | `{ scope: "comment" }` | See below. |
188
191
 
189
- `{ scope: "comment" }` is for rules about the comment above the code. The match is sent starting at the comments directly above it (or above the `export` or declaration that holds it), with nothing between them but whitespace. A match without such a comment is not asked about.
192
+ `{ scope: "comment" }` is for rules about the comment above the code. The match is sent starting at the comments directly above it, with nothing between them but whitespace. The comments may also sit above the `export` or declaration that holds the match. A match without such a comment is not asked about.
190
193
 
191
- More context costs more tokens and is cached together with the match, so an edit anywhere in the context re-asks that file.
194
+ More context costs more tokens. It is cached together with the match, so an edit anywhere in the context re-asks that file.
192
195
 
193
196
  ### Models
194
197
 
195
- A model id is `<provider>/<model>`. The built-in provider is `openrouter`, so `openrouter/inception/mercury-decide` asks `inception/mercury-decide` on OpenRouter. Browse decision models at [openrouter.ai/models](https://openrouter.ai/models?output_modalities=decisions).
198
+ A model id is `<provider>/<model>`. There are two built-in providers.
199
+
200
+ - `cloudflare` asks a chat model through the [AI Gateway REST API](https://developers.cloudflare.com/ai-gateway/usage/rest-api/). `cloudflare/@cf/qwen/qwen3.8-27b`, the default, asks `@cf/qwen/qwen3.8-27b` on Workers AI. The model answers each question with `yes` or `no`, and the yes probability comes from the log probabilities of that word. A model must return `logprobs` to be used here. Third-party models such as `cloudflare/openai/gpt-5.5` are billed through Unified Billing and need credits on the account.
201
+ - `openrouter` asks a decision model on the OpenRouter Decisions API. `openrouter/inception/mercury-decide` asks `inception/mercury-decide`. It reads the key from `OPENROUTER_API_KEY`. Browse decision models at [openrouter.ai/models](https://openrouter.ai/models?output_modalities=decisions).
196
202
 
197
- `model` takes one id or a list. With a list, every model answers every match, each model's request is separate, and each model's yes is its own diagnostic, so you can compare models on the same code.
203
+ `model` takes one id or a list. With a list, every model answers every match in a separate request. Each model's yes is its own diagnostic, so you can compare models on the same code.
198
204
 
199
205
  ```js
200
206
  createDecisionPlugin({
@@ -203,21 +209,21 @@ createDecisionPlugin({
203
209
  });
204
210
  ```
205
211
 
206
- Respan models, such as `openrouter/respan/span-01-lite`, answer only yes/no questions, so the plugin splits every choice into yes/no questions for them:
212
+ Cloudflare models and Respan models, such as `openrouter/respan/span-01-lite`, answer only yes/no questions. The plugin splits every choice into yes/no questions for them.
207
213
 
208
214
  - `classify` asks whether each label fits and picks the label with the highest yes probability.
209
- - `severity` asks whether the match is at least `info`, at least `warn`, and at least `error`, and picks the most serious level with a yes probability of 0.8 or more. A level's probability is never below that of a more serious level.
215
+ - `severity` asks whether the match is at least `info`, at least `warn` and at least `error`. It picks the most serious level with a yes probability of 0.8 or more. A level's probability is never below that of a more serious level.
210
216
  - File-rule `location` asks about each candidate line. It finds clear cases, but is less precise than on the default model.
211
217
 
212
- The probability in the message is the yes probability of the picked label or level. Respan models are also asked about one match per request, so they send more requests than other models on files with many matches. The default `openrouter/~typesafe/jev-latest` answers every answer kind in one question.
218
+ The probability in the message is the yes probability of the picked label or level. These models are also asked one question per request. So they send more requests than other models on files with many matches. `openrouter/~typesafe/jev-latest` answers every answer kind in one question.
213
219
 
214
- Probabilities are not calibrated the same way across models, so a cutoff tuned for one model does not carry over to another. Pin a versioned id once your cutoffs are tuned. Each diagnostic names the model that answered.
220
+ Probabilities are not calibrated the same way across models. A cutoff tuned for one model does not carry over to another. Pin a versioned id once your cutoffs are tuned. Each diagnostic names the model that answered.
215
221
 
216
- A key is required only for providers the rules you turned on use. `OPENROUTER_BASE_URL` points the plugin at another OpenRouter-compatible host.
222
+ A key is required only for providers the rules you turned on use. `OPENROUTER_BASE_URL` points the plugin at another OpenRouter-compatible host. `CLOUDFLARE_API_BASE_URL` points it at another Cloudflare API host.
217
223
 
218
224
  ### File locations
219
225
 
220
- File rules can point editor diagnostics and GitHub annotations to the suspected violation:
226
+ File rules can point editor diagnostics and GitHub annotations to the suspected violation.
221
227
 
222
228
  ```js
223
229
  defineDecisionRule({
@@ -233,7 +239,7 @@ defineDecisionRule({
233
239
  });
234
240
  ```
235
241
 
236
- The violation and location have separate cutoffs. An uncertain or invalid location keeps the finding on the first line. Files truncated by `maxSnippetChars` also keep the first-line diagnostic, since location questions only use complete source.
242
+ The violation and location have separate cutoffs. An uncertain or invalid location keeps the finding on the first line. Files truncated by `maxSnippetChars` also keep the first-line diagnostic. Location questions only use complete source.
237
243
 
238
244
  ### Settings
239
245
 
@@ -265,13 +271,13 @@ export default defineConfig({
265
271
  | `ci` | `"fail"` | What happens when a model can't be asked and `CI` is set. `"fail"` fails the run. `"skip"` warns once and reports nothing. Outside CI it always skips. |
266
272
  | `timeoutMs` | `10000` | Per-file budget shared by every model's request, retries and location refinements. |
267
273
  | `maxSnippetChars` | `4000` | Longer snippets are cut and end with `/* ...truncated */`. |
268
- | `model` | `"openrouter/~typesafe/jev-latest"` | The default model id or list of ids. |
274
+ | `model` | `"cloudflare/@cf/qwen/qwen3.8-27b"` | The default model id or list of ids. |
269
275
  | `env` | `{}` | Renames the environment variables providers read, such as `{ "OPENROUTER_API_KEY": "TEAM_OPENROUTER_KEY" }`. Values are variable names, not keys. |
270
276
  | `explain` | `false` | `true` or `"text"` prints why each match was or wasn't reported, `"json"` prints the same as JSON Lines. See [Explain mode](#explain-mode). |
271
277
 
272
278
  ## Explain mode
273
279
 
274
- When you tune a question or try another model, explain mode shows why each match was or wasn't reported. Turn it on for one run with an environment variable, since oxlint does not pass command-line flags to plugins:
280
+ When you tune a question or try another model, explain mode shows why each match was or wasn't reported. Turn it on for one run with an environment variable, since oxlint does not pass command-line flags to plugins.
275
281
 
276
282
  ```sh
277
283
  OXLINT_DECISION_EXPLAIN=1 npx oxlint # readable text
@@ -280,7 +286,7 @@ OXLINT_DECISION_EXPLAIN=json npx oxlint # one JSON object per match
280
286
 
281
287
  You can also set `explain: true` (or `"json"`) in `createDecisionPlugin` or in `settings.<plugin name>`. The environment variable wins when it is set, and `OXLINT_DECISION_EXPLAIN=0` turns it off.
282
288
 
283
- For every match the plugin asked a model about, it prints to stderr, so oxlint's own output stays as it is:
289
+ For every match the plugin asked a model about, it prints to stderr, so oxlint's own output stays as it is.
284
290
 
285
291
  ```text
286
292
  oxlint-plugin-decision explain: fail.js:5:3 [no-pii-in-logs] openrouter/respan/span-01-lite (served openrouter/respan/span-01-lite-20260925) cached=no 412ms
@@ -290,13 +296,14 @@ oxlint-plugin-decision explain: fail.js:5:3 [no-pii-in-logs] openrouter/respan/s
290
296
  verdict: yes 0.93, cutoff 0.80, reported
291
297
  ```
292
298
 
293
- - The file and position, the rule, the model id the rule was asked with (after any per-rule override), and the model that served the answer.
299
+ - The file and position, and the rule.
300
+ - The model id the rule was asked with (after any per-rule override), and the model that served the answer.
294
301
  - Whether the answer came from the cache, and how long the plugin waited for the answers of that file, in milliseconds. Every model of a file is asked together, so they share one wait.
295
302
  - The length and first characters of the source sent as state. The full source is not printed.
296
303
  - Each question exactly as sent, with the probability of each answer. When a Respan model answers a `classify` or `severity` rule, each yes/no question it was asked is listed on its own.
297
304
  - The verdict, the rule's cutoff, and whether it was reported.
298
305
 
299
- If the request failed, the record says why instead. In JSON Lines the same fields are `file`, `line`, `column`, `rule`, `model`, `served`, `cutoff`, `cached`, `durationMs`, `state`, `questions`, `verdict`, `reported`, and `error`.
306
+ If the request failed, the record says why instead. JSON Lines uses the same fields. The position is in `file`, `line` and `column`. The rule and models are in `rule`, `model` and `served`. The cutoff and cache state are in `cutoff` and `cached`, and the time taken is in `durationMs`. The request is in `state` and `questions`. The result is in `verdict`, `reported` and `error`.
300
307
 
301
308
  Explain mode only prints. It does not change what is asked, what is cached, or what is reported.
302
309
 
@@ -331,13 +338,13 @@ export default defineConfig({
331
338
  | ------- | ---------------------------------------- |
332
339
  | `model` | A model id or list of ids for this rule. |
333
340
 
334
- A rule's model comes from the first of these that sets one: the rule's options in `oxlint.config.ts`, the rule's own `model`, `settings.<plugin name>.model`, the `model` passed to `createDecisionPlugin`, and the default.
341
+ A rule's model comes from the first source that sets one. The rule's options in `oxlint.config.ts` come first. Next comes the rule's own `model`, and then `settings.<plugin name>.model`. After that comes the `model` passed to `createDecisionPlugin`. The default comes last.
335
342
 
336
- Rules on different models are asked separately, one request per file and model, so a Respan model and `~typesafe/jev-latest` can share a config: each model gets only the matches of the rules that use it. Answers are cached by the request each model receives, so rules never share or overwrite each other's cached answers.
343
+ Rules on different models are asked separately, one request per file and model. So a Respan model and `~typesafe/jev-latest` can share a config. Each model gets only the matches of the rules that use it. Answers are cached by the request each model receives. Rules never share or overwrite each other's cached answers.
337
344
 
338
345
  ## Providers
339
346
 
340
- `createDecisionPlugin` also takes providers, so rules can ask a decision service other than OpenRouter.
347
+ `createDecisionPlugin` also takes providers, so rules can ask a decision service other than Cloudflare and OpenRouter.
341
348
 
342
349
  ```js
343
350
  // decision-plugin.mjs
@@ -388,31 +395,54 @@ export default defineConfig({
388
395
  });
389
396
  ```
390
397
 
391
- `createDecisionPlugin` checks every rule and setting when the plugin loads, so a typo in a rule fails the oxlint run instead of being ignored.
398
+ `createDecisionPlugin` checks every rule and setting when the plugin loads. A typo in a rule fails the oxlint run instead of being ignored.
392
399
 
393
- A provider's `decide` is synchronous, because oxlint rules are. It gets an OpenRouter Decisions request (`model`, `state`, `questions`) and returns `{ ok: true, response }` with a Decisions response, or `{ ok: false, reason }`. The built-in `openRouter` provider does its network call on a worker thread through [synckit](https://github.com/un-ts/synckit); a custom provider that calls a network service should do the same.
400
+ A provider's `decide` is synchronous, because oxlint rules are. It gets an OpenRouter Decisions request (`model`, `state`, `questions`). It returns `{ ok: true, response }` with a Decisions response, or `{ ok: false, reason }`. The built-in `cloudflare` and `openRouter` providers do their network calls on a worker thread through [synckit](https://github.com/un-ts/synckit). A custom provider that calls a network service should do the same.
394
401
 
395
- oxlint runs JS plugins on one thread, so files are asked one after another. Within a file, the plugin hands every model of the same provider to the provider's optional `decideAll` in one call, and the built-in provider sends them at the same time. A provider without `decideAll` is asked one model at a time through `decide`.
402
+ oxlint runs JS plugins on one thread, so files are asked one after another. Within a file, the plugin hands every model of the same provider to the provider's optional `decideAll` in one call. The built-in providers send them at the same time. A provider without `decideAll` is asked one model at a time through `decide`.
396
403
 
397
- The built-in provider's worker reports its `decide`, `ask` and `send` steps as spans over OTLP when the standard `OTEL_TRACES_EXPORTER=otlp` and `OTEL_EXPORTER_OTLP_ENDPOINT` (or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) are set, and does nothing otherwise.
404
+ The built-in provider's worker can report its `decide`, `ask` and `send` steps as spans over OTLP. It does so when the standard `OTEL_TRACES_EXPORTER=otlp` and `OTEL_EXPORTER_OTLP_ENDPOINT` are set. `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` also works in place of the endpoint. Otherwise it does nothing.
398
405
 
399
- Types for all of this are exported: `DecisionRule`, `DecisionOptions`, `RuleAnswer`, `RuleContext`, `DecisionProvider`, `DecisionRequest`, `DecideResult`, and more.
406
+ Types for all of this are exported. The rule types include `DecisionRule`, `DecisionOptions`, `RuleAnswer` and `RuleContext`. The provider types include `DecisionProvider`, `DecisionRequest` and `DecideResult`.
400
407
 
401
408
  ## How it works
402
409
 
403
- Each file gets one request per model, with every match for that model in it. Respan models get one request per match instead, with each choice question split into yes/no questions. A file rule with `location` adds numbered source and a choice question. Above 254 nonblank lines the model selects a range and refines it in follow-up requests with the same context. All requests share the per-file `timeoutMs` budget.
410
+ Each file gets one request per model, with every match for that model in it. Cloudflare and Respan models get one request per question instead. Each of their choice questions becomes yes/no questions. A file rule with `location` adds numbered source and a choice question. Above 254 nonblank lines the model selects a range and refines it in follow-up requests with the same context. All requests share the per-file `timeoutMs` budget.
404
411
 
405
- Answers are cached under `node_modules/.cache/oxlint-plugin-decision`, keyed by the endpoint and the request. Changing a snippet, its context, a question or an answer kind re-asks that file. Changing a cutoff or an `id` does not. Malformed answers are never cached, and malformed entries already on disk are asked again. See [Cost and caching](https://github.com/masseater/lint-kit#cost-and-caching) for how to keep the cost down.
412
+ Answers are cached under `node_modules/.cache/oxlint-plugin-decision`, keyed by the endpoint and the request. Changing a snippet, its context, a question or an answer kind re-asks that file. Changing a cutoff or an `id` does not. Malformed answers are never cached, and malformed entries already on disk are asked again. See [Cost and caching](#cost-and-caching) for how to keep the cost down.
406
413
 
407
- Requests go through the official [`@openrouter/sdk`](https://www.npmjs.com/package/@openrouter/sdk) client, which retries rate limits and server errors within `timeoutMs`.
414
+ OpenRouter requests use Effect's [`@effect/ai-openrouter`](https://www.npmjs.com/package/@effect/ai-openrouter) client. Cloudflare requests use Effect's HTTP client. Both retry rate limits and server errors within `timeoutMs`.
408
415
 
409
- If a model can't be asked, because the key is missing, the request times out, or the API errors, the plugin prints one warning and reports nothing for that model on that file. Under CI the run fails instead, unless `ci` is `"skip"`.
416
+ A model may not be reachable, because the key is missing, the request times out or the API errors. Then the plugin prints one warning and reports nothing for that model on that file. Under CI the run fails instead, unless `ci` is `"skip"`.
410
417
 
411
418
  If only a location refinement fails, confirmed violations are still reported at the file level. Under CI (unless `ci` is `"skip"`), the refinement failure produces a separate diagnostic; otherwise it warns.
412
419
 
420
+ ## Cost and caching
421
+
422
+ Before running the plugin on a real codebase, put these three in place.
423
+
424
+ 1. Exclude files you don't need. List generated and vendored code in `ignorePatterns`, and use `overrides` to turn rules on only where they matter.
425
+ 2. Lint only changed files instead of the whole tree.
426
+
427
+ ```sh
428
+ git diff --name-only --diff-filter=d origin/main... -- '*.ts' '*.tsx' '*.js' '*.jsx' | xargs -r npx oxlint
429
+ ```
430
+
431
+ 3. Keep the cache. Answers are cached under `node_modules/.cache/oxlint-plugin-decision`, so unchanged code is not asked again. Don't delete it between local runs, and persist it in CI.
432
+
433
+ ```yaml
434
+ - uses: actions/cache@v4
435
+ with:
436
+ path: node_modules/.cache/oxlint-plugin-decision
437
+ key: oxlint-decision-${{ github.sha }}
438
+ restore-keys: oxlint-decision-
439
+ ```
440
+
441
+ Workers AI models are billed by the account's Workers AI usage, which includes a free daily allocation. The AI Gateway cache can also answer a request the account has already sent, so set a cache TTL on the gateway.
442
+
413
443
  ## In the editor
414
444
 
415
- The oxlint VS Code extension lints as you type, and every keystroke inside a match is a paid request that blocks the language server until the model answers.
445
+ The oxlint VS Code extension lints as you type. Every keystroke inside a match is a paid request that blocks the language server until the model answers.
416
446
 
417
447
  Keep your decision rules off in the config your editor reads, and turn them on in an overlay for CI and pre-push. Leave `jsPlugins` in the base config, since the overlay inherits it.
418
448
 
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,185 @@
1
+ import { appContext } from "./openrouter-app.mjs";
2
+ import { c as toJson, n as envNameOf, t as captured } from "./runtime-CICpEidL.mjs";
3
+ import { t as serveDecisions } from "./serve-decisions-pOSYU_8a.mjs";
4
+ import { i as yesNoRequestsFor, n as mergeYesNo } from "./wire-BbVK3Q_K.mjs";
5
+ import { Array, Boolean, Config, Effect, Number as Number$1, Option, Record, Schedule, Schema, String as String$1, pipe } from "effect";
6
+ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
7
+ // src/cloudflare-chat.ts
8
+ const TOOL = "oxlint-plugin-decision";
9
+ const DEFAULT_API_URL = "https://api.cloudflare.com/client/v4";
10
+ const DEFAULT_GATEWAY = "default";
11
+ const CHAT_PATH = "/ai/v1/chat/completions";
12
+ const TRAILING_SLASHES = /\/+$/u;
13
+ const WORKERS_AI = "@cf/";
14
+ const TOP_LOGPROBS = 10;
15
+ const TOKENS_PER_ANSWER = 8;
16
+ const SPARE_TOKENS = 16;
17
+ const FIRST_LABEL = 1;
18
+ const NONE = 0;
19
+ const CERTAIN = 1;
20
+ const FIRST_REDIRECT = 300;
21
+ const RETRY_INITIAL_MS = 10;
22
+ const RETRY_EXPONENT = 2;
23
+ const LEADING_JUNK = /^(?<lead>[\s::*]*)(?<word>[\s\S]*)$/u;
24
+ const LABEL_BEFORE = /(?:^|\n)[\s*]*q(?<index>\d+)[\s*]*[::]\s*$/u;
25
+ const ANSWER_WORD = /^(?<word>yes|no)[\s.,!*]*$/iu;
26
+ const SYSTEM = Array.join([
27
+ "You answer yes-or-no questions about the material the user gives you.",
28
+ "Answer every question on its own line in the form `q<number>: yes` or `q<number>: no`, in the order asked.",
29
+ "Write nothing else."
30
+ ], " ");
31
+ const TopLogprob = Schema.Struct({
32
+ token: Schema.String,
33
+ logprob: Schema.Finite
34
+ });
35
+ const TokenLogprob = Schema.Struct({
36
+ token: Schema.String,
37
+ logprob: Schema.Finite,
38
+ top_logprobs: Schema.optional(Schema.Array(TopLogprob))
39
+ });
40
+ const Logprobs = Schema.Struct({ content: Schema.NullOr(Schema.Array(TokenLogprob)) });
41
+ const OptionalLogprobs = Schema.optional(Schema.NullOr(Logprobs));
42
+ const Choice = Schema.Struct({ logprobs: OptionalLogprobs });
43
+ const ChatResponse = Schema.Struct({
44
+ model: Schema.optional(Schema.String),
45
+ choices: Schema.NonEmptyArray(Choice)
46
+ });
47
+ const ChatBody = Schema.Struct({ body: ChatResponse });
48
+ const ErrorBody = Schema.Struct({ errors: Schema.NonEmptyArray(Schema.Struct({ message: Schema.String })) });
49
+ const decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);
50
+ const labelOf = (index) => `q${String(Number$1.sum(index, FIRST_LABEL))}`;
51
+ const accountUrl = ({ api, account }) => `${String$1.replace(TRAILING_SLASHES, "")(String$1.trim(api))}/accounts/${String$1.trim(account)}`;
52
+ const endpointOf = (env) => Config.all({
53
+ api: Config.String(envNameOf(env, "CLOUDFLARE_API_BASE_URL")).pipe(Config.withDefault(DEFAULT_API_URL)),
54
+ account: Config.NonEmptyString(envNameOf(env, "CLOUDFLARE_ACCOUNT_ID"))
55
+ }).pipe(Config.map(accountUrl));
56
+ const yesNoOf = (word) => Boolean.match(String$1.toLowerCase(word) === "yes", {
57
+ onTrue: () => "yes",
58
+ onFalse: () => "no"
59
+ });
60
+ const answerOf = (text) => captured(String$1.match(ANSWER_WORD)(text), "word").pipe(Option.map(yesNoOf));
61
+ const splitToken = (token) => {
62
+ const match = String$1.match(LEADING_JUNK)(token);
63
+ return {
64
+ lead: Option.getOrElse(captured(match, "lead"), () => ""),
65
+ word: Option.getOrElse(captured(match, "word"), () => token)
66
+ };
67
+ };
68
+ const massOf = (token) => {
69
+ const mass = {
70
+ yes: NONE,
71
+ no: NONE
72
+ };
73
+ for (const alternative of token.top_logprobs ?? [token]) {
74
+ const answer = answerOf(splitToken(alternative.token).word);
75
+ if (Option.isSome(answer)) mass[answer.value] += Math.exp(alternative.logprob);
76
+ }
77
+ return mass;
78
+ };
79
+ const yesOf = (token, answer) => {
80
+ const mass = massOf(token);
81
+ const total = Number$1.sum(mass.yes, mass.no);
82
+ if (total > NONE) return mass.yes / total;
83
+ return Boolean.match(answer === "yes", {
84
+ onTrue: () => CERTAIN,
85
+ onFalse: () => NONE
86
+ });
87
+ };
88
+ const labelIndexOf = (text) => captured(String$1.match(LABEL_BEFORE)(text), "index").pipe(Option.map((index) => Number$1.subtract(Number(index), FIRST_LABEL)));
89
+ const yesByLabel = (tokens) => {
90
+ const found = /* @__PURE__ */ new Map();
91
+ let text = "";
92
+ for (const token of tokens) {
93
+ const { lead, word } = splitToken(token.token);
94
+ const answer = answerOf(word);
95
+ const index = labelIndexOf(`${text}${lead}`);
96
+ if (Option.isSome(answer) && Option.isSome(index) && !found.has(index.value)) found.set(index.value, yesOf(token, answer.value));
97
+ text = `${text}${token.token}`;
98
+ }
99
+ return found;
100
+ };
101
+ const stateText = (state) => {
102
+ if (typeof state === "string") return state;
103
+ return toJson(state);
104
+ };
105
+ const promptOf = (wire, questions) => {
106
+ const asked = pipe(questions, Array.map(([, question], index) => `${labelOf(index)}: ${question.instructions}`), Array.join("\n"));
107
+ return `${stateText(wire.state)}\n\nQuestions:\n${asked}`;
108
+ };
109
+ const templateOf = (model) => {
110
+ if (String$1.startsWith(WORKERS_AI)(model)) return { chat_template_kwargs: {
111
+ enable_thinking: false,
112
+ thinking: false
113
+ } };
114
+ return {};
115
+ };
116
+ const bodyOf = (wire, questions) => ({
117
+ model: wire.model,
118
+ temperature: NONE,
119
+ logprobs: true,
120
+ top_logprobs: TOP_LOGPROBS,
121
+ max_tokens: Number$1.sum(Number$1.multiply(questions.length, TOKENS_PER_ANSWER), SPARE_TOKENS),
122
+ messages: [{
123
+ role: "system",
124
+ content: SYSTEM
125
+ }, {
126
+ role: "user",
127
+ content: promptOf(wire, questions)
128
+ }],
129
+ ...templateOf(wire.model)
130
+ });
131
+ const messageOfBody = (body) => Option.match(decodeErrorBody(body), {
132
+ onNone: () => "request failed",
133
+ onSome: ({ errors }) => pipe(errors, Array.map(({ message }) => message), Array.join("; "))
134
+ });
135
+ const failureOf = (response) => response.json.pipe(Effect.option, Effect.flatMap((body) => Effect.fail(`http ${String(response.status)}: ${messageOfBody(Option.getOrUndefined(body))}`)));
136
+ const answersOf = (questions, tokens) => {
137
+ const byLabel = yesByLabel(tokens);
138
+ const answered = pipe(questions, Array.flatMap(([id], index) => pipe(Option.fromUndefinedOr(byLabel.get(index)), Option.map((noul) => [id, {
139
+ type: "noul",
140
+ noul
141
+ }]), Option.toArray)));
142
+ if (answered.length < questions.length) return Effect.fail("the model did not answer every question with yes or no");
143
+ return Effect.succeed(Record.fromEntries(answered));
144
+ };
145
+ const tokensOf = ({ body }) => {
146
+ const [{ logprobs }] = body.choices;
147
+ return Option.fromNullishOr(logprobs).pipe(Option.flatMap(({ content }) => Option.fromNullishOr(content)), Option.getOrElse(() => []));
148
+ };
149
+ const post = Effect.fn("post")(function* post(endpoint, wire, { env }) {
150
+ const token = yield* Config.Redacted(envNameOf(env, "CLOUDFLARE_API_TOKEN"));
151
+ const gateway = yield* Config.String(envNameOf(env, "CLOUDFLARE_AI_GATEWAY_ID")).pipe(Config.withDefault(DEFAULT_GATEWAY));
152
+ const app = yield* appContext;
153
+ const body = bodyOf(wire, Record.toEntries(wire.questions));
154
+ const client = (yield* HttpClient.HttpClient).pipe(HttpClient.retryTransient({
155
+ retryOn: "response-only",
156
+ schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT)
157
+ }));
158
+ return yield* HttpClientRequest.post(`${endpoint}${CHAT_PATH}`).pipe(HttpClientRequest.bearerToken(token), HttpClientRequest.setHeaders({
159
+ "cf-aig-gateway-id": gateway,
160
+ "cf-aig-metadata": toJson({
161
+ tool: TOOL,
162
+ ...app
163
+ })
164
+ }), HttpClientRequest.bodyJsonUnsafe(body), client.execute);
165
+ });
166
+ const sendChat = Effect.fn("sendChat")(function* sendChat(endpoint, wire, input) {
167
+ const response = yield* post(endpoint, wire, input).pipe(Effect.mapError((error) => `network: ${error.message}`));
168
+ if (response.status >= FIRST_REDIRECT) return yield* failureOf(response);
169
+ const chat = yield* HttpClientResponse.schemaJson(ChatBody)(response).pipe(Effect.mapError((error) => `invalid response: ${error.message}`));
170
+ const answers = yield* answersOf(Record.toEntries(wire.questions), tokensOf(chat));
171
+ return {
172
+ model: chat.body.model ?? wire.model,
173
+ answers
174
+ };
175
+ });
176
+ // src/cloudflare-worker.ts
177
+ serveDecisions({
178
+ endpoint: endpointOf,
179
+ wires: yesNoRequestsFor,
180
+ combine: mergeYesNo,
181
+ send: sendChat
182
+ });
183
+ export {};
184
+
185
+ //# sourceMappingURL=cloudflare-worker.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-worker.mjs","names":["Arr","Num","Str","Bool","Rec"],"sources":["../src/cloudflare-chat.ts","../src/cloudflare-worker.ts"],"sourcesContent":["import {\n Array as Arr,\n Boolean as Bool,\n Config,\n Effect,\n Number as Num,\n Option,\n Record as Rec,\n Schedule,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\";\n\nimport { appContext } from \"./openrouter-app.ts\";\nimport { captured, envNameOf, toJson } from \"./runtime.ts\";\nimport type { Answers, DecideInput, DecisionResponse, Question } from \"./types.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst DEFAULT_API_URL = \"https://api.cloudflare.com/client/v4\";\nconst DEFAULT_GATEWAY = \"default\";\nconst CHAT_PATH = \"/ai/v1/chat/completions\";\nconst TRAILING_SLASHES = /\\/+$/u;\nconst WORKERS_AI = \"@cf/\";\nconst TOP_LOGPROBS = 10;\nconst TOKENS_PER_ANSWER = 8;\nconst SPARE_TOKENS = 16;\nconst FIRST_LABEL = 1;\nconst NONE = 0;\nconst CERTAIN = 1;\nconst FIRST_REDIRECT = 300;\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\nconst LEADING_JUNK = /^(?<lead>[\\s::*]*)(?<word>[\\s\\S]*)$/u;\nconst LABEL_BEFORE = /(?:^|\\n)[\\s*]*q(?<index>\\d+)[\\s*]*[::]\\s*$/u;\nconst ANSWER_WORD = /^(?<word>yes|no)[\\s.,!*]*$/iu;\n\nconst SYSTEM = Arr.join(\n [\n \"You answer yes-or-no questions about the material the user gives you.\",\n \"Answer every question on its own line in the form `q<number>: yes` or `q<number>: no`, in the order asked.\",\n \"Write nothing else.\",\n ],\n \" \",\n);\n\nconst TopLogprob = Schema.Struct({ token: Schema.String, logprob: Schema.Finite });\n\nconst TokenLogprob = Schema.Struct({\n token: Schema.String,\n logprob: Schema.Finite,\n top_logprobs: Schema.optional(Schema.Array(TopLogprob)),\n});\n\nconst Logprobs = Schema.Struct({ content: Schema.NullOr(Schema.Array(TokenLogprob)) });\n\nconst OptionalLogprobs = Schema.optional(Schema.NullOr(Logprobs));\n\nconst Choice = Schema.Struct({ logprobs: OptionalLogprobs });\n\nconst ChatResponse = Schema.Struct({\n model: Schema.optional(Schema.String),\n choices: Schema.NonEmptyArray(Choice),\n});\n\nconst ChatBody = Schema.Struct({ body: ChatResponse });\n\nconst ErrorBody = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ message: Schema.String })),\n});\n\nconst decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);\n\ntype Token = typeof TokenLogprob.Type;\n\ntype YesNo = \"yes\" | \"no\";\n\ntype Mass = Readonly<Record<YesNo, number>>;\n\ntype Asked = readonly (readonly [string, Question])[];\n\ninterface Split {\n readonly lead: string;\n readonly word: string;\n}\n\nconst labelOf = (index: number): string => `q${String(Num.sum(index, FIRST_LABEL))}`;\n\nconst accountUrl = ({ api, account }: Readonly<{ api: string; account: string }>): string =>\n `${Str.replace(TRAILING_SLASHES, \"\")(Str.trim(api))}/accounts/${Str.trim(account)}`;\n\nconst endpointOf = (env: DecideInput[\"env\"]): Config.Config<string> =>\n Config.all({\n api: Config.String(envNameOf(env, \"CLOUDFLARE_API_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_API_URL),\n ),\n account: Config.NonEmptyString(envNameOf(env, \"CLOUDFLARE_ACCOUNT_ID\")),\n }).pipe(Config.map(accountUrl));\n\nconst yesNoOf = (word: string): YesNo =>\n Bool.match(Str.toLowerCase(word) === \"yes\", { onTrue: () => \"yes\", onFalse: () => \"no\" });\n\nconst answerOf = (text: string): Option.Option<YesNo> =>\n captured(Str.match(ANSWER_WORD)(text), \"word\").pipe(Option.map(yesNoOf));\n\nconst splitToken = (token: string): Split => {\n const match = Str.match(LEADING_JUNK)(token);\n return {\n lead: Option.getOrElse(captured(match, \"lead\"), () => \"\"),\n word: Option.getOrElse(captured(match, \"word\"), () => token),\n };\n};\n\nconst massOf = (token: Token): Mass => {\n const mass = { yes: NONE, no: NONE };\n for (const alternative of token.top_logprobs ?? [token]) {\n const answer = answerOf(splitToken(alternative.token).word);\n if (Option.isSome(answer)) {\n mass[answer.value] += Math.exp(alternative.logprob);\n }\n }\n return mass;\n};\n\nconst yesOf = (token: Token, answer: YesNo): number => {\n const mass = massOf(token);\n const total = Num.sum(mass.yes, mass.no);\n if (total > NONE) {\n return mass.yes / total;\n }\n return Bool.match(answer === \"yes\", { onTrue: () => CERTAIN, onFalse: () => NONE });\n};\n\nconst labelIndexOf = (text: string): Option.Option<number> =>\n captured(Str.match(LABEL_BEFORE)(text), \"index\").pipe(\n Option.map((index) => Num.subtract(Number(index), FIRST_LABEL)),\n );\n\nconst yesByLabel = (tokens: readonly Token[]): ReadonlyMap<number, number> => {\n const found = new Map<number, number>();\n let text = \"\";\n for (const token of tokens) {\n const { lead, word } = splitToken(token.token);\n const answer = answerOf(word);\n const index = labelIndexOf(`${text}${lead}`);\n if (Option.isSome(answer) && Option.isSome(index) && !found.has(index.value)) {\n found.set(index.value, yesOf(token, answer.value));\n }\n text = `${text}${token.token}`;\n }\n return found;\n};\n\nconst stateText = (state: WireRequest[\"state\"]): string => {\n if (typeof state === \"string\") {\n return state;\n }\n return toJson(state);\n};\n\nconst promptOf = (wire: WireRequest, questions: Asked): string => {\n const asked = pipe(\n questions,\n Arr.map(([, question], index) => `${labelOf(index)}: ${question.instructions}`),\n Arr.join(\"\\n\"),\n );\n return `${stateText(wire.state)}\\n\\nQuestions:\\n${asked}`;\n};\n\nconst templateOf = (model: string): Readonly<Record<string, unknown>> => {\n if (Str.startsWith(WORKERS_AI)(model)) {\n return { chat_template_kwargs: { enable_thinking: false, thinking: false } };\n }\n return {};\n};\n\nconst bodyOf = (wire: WireRequest, questions: Asked): Readonly<Record<string, unknown>> => ({\n model: wire.model,\n temperature: NONE,\n logprobs: true,\n top_logprobs: TOP_LOGPROBS,\n max_tokens: Num.sum(Num.multiply(questions.length, TOKENS_PER_ANSWER), SPARE_TOKENS),\n messages: [\n { role: \"system\", content: SYSTEM },\n { role: \"user\", content: promptOf(wire, questions) },\n ],\n ...templateOf(wire.model),\n});\n\nconst messageOfBody = (body: unknown): string =>\n Option.match(decodeErrorBody(body), {\n onNone: () => \"request failed\",\n onSome: ({ errors }) =>\n pipe(\n errors,\n Arr.map(({ message }) => message),\n Arr.join(\"; \"),\n ),\n });\n\nconst failureOf = (response: HttpClientResponse.HttpClientResponse): Effect.Effect<never, string> =>\n response.json.pipe(\n Effect.option,\n Effect.flatMap((body) =>\n Effect.fail(`http ${String(response.status)}: ${messageOfBody(Option.getOrUndefined(body))}`),\n ),\n );\n\nconst answersOf = (questions: Asked, tokens: readonly Token[]): Effect.Effect<Answers, string> => {\n const byLabel = yesByLabel(tokens);\n const answered = pipe(\n questions,\n Arr.flatMap(([id], index) =>\n pipe(\n Option.fromUndefinedOr(byLabel.get(index)),\n Option.map((noul) => [id, { type: \"noul\", noul }] as const),\n Option.toArray,\n ),\n ),\n );\n if (answered.length < questions.length) {\n return Effect.fail(\"the model did not answer every question with yes or no\");\n }\n return Effect.succeed(Rec.fromEntries(answered));\n};\n\nconst tokensOf = ({ body }: typeof ChatBody.Type): readonly Token[] => {\n const [{ logprobs }] = body.choices;\n return Option.fromNullishOr(logprobs).pipe(\n Option.flatMap(({ content }) => Option.fromNullishOr(content)),\n Option.getOrElse((): readonly Token[] => []),\n );\n};\n\nconst post = Effect.fn(\"post\")(function* post(\n endpoint: string,\n wire: WireRequest,\n { env }: Pick<DecideInput, \"env\">,\n) {\n const token = yield* Config.Redacted(envNameOf(env, \"CLOUDFLARE_API_TOKEN\"));\n const gateway = yield* Config.String(envNameOf(env, \"CLOUDFLARE_AI_GATEWAY_ID\")).pipe(\n Config.withDefault(DEFAULT_GATEWAY),\n );\n const app = yield* appContext;\n const body = bodyOf(wire, Rec.toEntries(wire.questions));\n const client = (yield* HttpClient.HttpClient).pipe(\n HttpClient.retryTransient({\n retryOn: \"response-only\",\n schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT),\n }),\n );\n return yield* HttpClientRequest.post(`${endpoint}${CHAT_PATH}`).pipe(\n HttpClientRequest.bearerToken(token),\n HttpClientRequest.setHeaders({\n \"cf-aig-gateway-id\": gateway,\n \"cf-aig-metadata\": toJson({ tool: TOOL, ...app }),\n }),\n HttpClientRequest.bodyJsonUnsafe(body),\n client.execute,\n );\n});\n\nconst sendChat = Effect.fn(\"sendChat\")(function* sendChat(\n endpoint: string,\n wire: WireRequest,\n input: Pick<DecideInput, \"env\">,\n) {\n const response = yield* post(endpoint, wire, input).pipe(\n Effect.mapError((error) => `network: ${error.message}`),\n );\n if (response.status >= FIRST_REDIRECT) {\n return yield* failureOf(response);\n }\n const chat = yield* HttpClientResponse.schemaJson(ChatBody)(response).pipe(\n Effect.mapError((error) => `invalid response: ${error.message}`),\n );\n const answers = yield* answersOf(Rec.toEntries(wire.questions), tokensOf(chat));\n return { model: chat.body.model ?? wire.model, answers } satisfies DecisionResponse;\n});\n\n/** @internal */\nexport { endpointOf, sendChat, yesByLabel };\n/** @internal */\nexport type { Token, YesNo };\n","import { endpointOf, sendChat } from \"./cloudflare-chat.ts\";\nimport { serveDecisions } from \"./serve-decisions.ts\";\nimport { mergeYesNo, yesNoRequestsFor } from \"./wire.ts\";\n\nserveDecisions({\n endpoint: endpointOf,\n wires: yesNoRequestsFor,\n combine: mergeYesNo,\n send: sendChat,\n});\n"],"mappings":";;;;;;;AAoBA,MAAM,OAAO;AACb,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,mBAAmB;AACzB,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,eAAe;AAC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WAAA,CAAY,KAC5C,WAAW,eAAe;EACxB,SAAS;EACT,UAAU,SAAS,YAAY,kBAAkB,cAAc;CACjE,CAAC,CACH;CACA,OAAO,OAAO,kBAAkB,KAAK,GAAG,WAAW,WAAW,CAAC,CAAC,KAC9D,kBAAkB,YAAY,KAAK,GACnC,kBAAkB,WAAW;EAC3B,qBAAqB;EACrB,mBAAmB,OAAO;GAAE,MAAM;GAAM,GAAG;EAAI,CAAC;CAClD,CAAC,GACD,kBAAkB,eAAe,IAAI,GACrC,OAAO,OACT;AACF,CAAC;AAED,MAAM,WAAW,OAAO,GAAG,UAAU,CAAC,CAAC,UAAU,SAC/C,UACA,MACA,OACA;CACA,MAAM,WAAW,OAAO,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,KAClD,OAAO,UAAU,UAAU,YAAY,MAAM,SAAS,CACxD;CACA,IAAI,SAAS,UAAU,gBACrB,OAAO,OAAO,UAAU,QAAQ;CAElC,MAAM,OAAO,OAAO,mBAAmB,WAAW,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,KACpE,OAAO,UAAU,UAAU,qBAAqB,MAAM,SAAS,CACjE;CACA,MAAM,UAAU,OAAO,UAAUA,OAAI,UAAU,KAAK,SAAS,GAAG,SAAS,IAAI,CAAC;CAC9E,OAAO;EAAE,OAAO,KAAK,KAAK,SAAS,KAAK;EAAO;CAAQ;AACzD,CAAC;;ACpRD,eAAe;CACb,UAAU;CACV,OAAO;CACP,SAAS;CACT,MAAM;AACR,CAAC"}
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Schema } from "effect";
2
- import { DecisionsChoiceQuestion, DecisionsNoulQuestion, DecisionsRequest, DecisionsResponse } from "@openrouter/sdk/models";
2
+ import { ChoiceQuestion as ChoiceQuestion$1, DecisionsRequest, DecisionsResponse, NoulQuestion as NoulQuestion$1 } from "@effect/ai-openrouter/OpenRouterSchema";
3
3
  //#endregion
4
4
  //#region src-js/plugins/globals.d.ts
5
5
  /**
@@ -3316,22 +3316,22 @@ interface DecisionOptions {
3316
3316
  readonly env?: Readonly<Record<string, string>>;
3317
3317
  readonly explain?: ExplainSetting;
3318
3318
  }
3319
- interface NoulQuestion extends Readonly<Pick<DecisionsNoulQuestion, "type" | "instructions">> {
3319
+ interface NoulQuestion extends Readonly<Pick<typeof NoulQuestion$1.Encoded, "type" | "instructions">> {
3320
3320
  readonly instructions: string;
3321
3321
  }
3322
- interface ChoiceQuestion extends Readonly<Pick<DecisionsChoiceQuestion, "type" | "instructions" | "criteria">> {
3322
+ interface ChoiceQuestion extends Readonly<Pick<typeof ChoiceQuestion$1.Encoded, "type" | "instructions" | "criteria">> {
3323
3323
  readonly instructions: string;
3324
3324
  readonly criteria: Readonly<Record<string, string | null>>;
3325
3325
  }
3326
3326
  type Question = NoulQuestion | ChoiceQuestion;
3327
- interface DecisionRequest extends Readonly<Pick<DecisionsRequest, "model" | "state" | "questions">> {
3327
+ interface DecisionRequest extends Readonly<Pick<typeof DecisionsRequest.Encoded, "model" | "state" | "questions">> {
3328
3328
  readonly state: {
3329
3329
  readonly snippets: Readonly<Record<string, string>>;
3330
3330
  readonly contexts?: Readonly<Record<string, string>>;
3331
3331
  };
3332
3332
  readonly questions: Readonly<Record<string, Question>>;
3333
3333
  }
3334
- type DecisionResponse = Frozen<Pick<DecisionsResponse, "model" | "answers">>;
3334
+ type DecisionResponse = Pick<typeof DecisionsResponse.Type, "model" | "answers">;
3335
3335
  type DecideResult = {
3336
3336
  readonly ok: true;
3337
3337
  readonly response: DecisionResponse;
@@ -3348,6 +3348,7 @@ interface DecideInput {
3348
3348
  interface DecisionProvider {
3349
3349
  readonly name: string;
3350
3350
  readonly requiredEnv: readonly string[];
3351
+ readonly yesNo?: boolean;
3351
3352
  readonly decide: (input: DecideInput) => DecideResult;
3352
3353
  readonly decideAll?: (inputs: readonly DecideInput[]) => readonly DecideResult[];
3353
3354
  }
@@ -3364,7 +3365,8 @@ interface DecisionPlugin {
3364
3365
  }
3365
3366
  declare const defineDecisionRule: <const Rule extends DecisionRule>(rule: Rule) => Rule;
3366
3367
  declare const defineProvider: <const Provider extends DecisionProvider>(provider: Provider) => Provider;
3368
+ declare const cloudflare: DecisionProvider;
3367
3369
  declare const openRouter: DecisionProvider;
3368
3370
  declare const createDecisionPlugin: (setup: DecisionPluginSetup) => DecisionPlugin;
3369
- export { type ChoiceQuestion, type CiBehavior, type DecideInput, type DecideResult, type DecisionOptions, type DecisionPlugin, type DecisionPluginSetup, type DecisionProvider, type DecisionRequest, type DecisionResponse, type DecisionRule, type EnclosingKind, type ExplainSetting, type Frozen, type ModelSpec, type NoulQuestion, type Question, type RuleAnswer, type RuleContext, type RuleLocation, type SelectMatch, type SelectedNode, type Severity, type Target, createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };
3371
+ export { type ChoiceQuestion, type CiBehavior, type DecideInput, type DecideResult, type DecisionOptions, type DecisionPlugin, type DecisionPluginSetup, type DecisionProvider, type DecisionRequest, type DecisionResponse, type DecisionRule, type EnclosingKind, type ExplainSetting, type Frozen, type ModelSpec, type NoulQuestion, type Question, type RuleAnswer, type RuleContext, type RuleLocation, type SelectMatch, type SelectedNode, type Severity, type Target, cloudflare, createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };
3370
3372
  //# sourceMappingURL=index.d.mts.map