@r_masseater/oxlint-plugin-decision 0.4.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 +22 -16
- package/dist/cloudflare-worker.d.mts +1 -0
- package/dist/cloudflare-worker.mjs +185 -0
- package/dist/cloudflare-worker.mjs.map +1 -0
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +46 -22
- package/dist/index.mjs.map +1 -1
- package/dist/openrouter-app.d.mts +6 -1
- package/dist/openrouter-app.mjs +10 -2
- package/dist/openrouter-app.mjs.map +1 -1
- package/dist/openrouter-worker.mjs +10 -103
- package/dist/openrouter-worker.mjs.map +1 -1
- package/dist/runtime-CICpEidL.mjs +271 -0
- package/dist/runtime-CICpEidL.mjs.map +1 -0
- package/dist/serve-decisions-pOSYU_8a.mjs +112 -0
- package/dist/serve-decisions-pOSYU_8a.mjs.map +1 -0
- package/dist/wire-BbVK3Q_K.mjs +246 -0
- package/dist/wire-BbVK3Q_K.mjs.map +1 -0
- package/package.json +13 -11
- package/skills/write-decision-rules/SKILL.md +19 -14
- package/skills/write-decision-rules/references/providers.md +1 -1
- package/skills/write-decision-rules/references/tuning.md +1 -1
- package/dist/wire-XbLEwd0i.mjs +0 -508
- package/dist/wire-XbLEwd0i.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
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
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
|
|
|
@@ -11,18 +11,21 @@ Decision models do not write text. They return a probability for a yes/no questi
|
|
|
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)
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
|
@@ -192,7 +195,10 @@ More context costs more tokens. It is cached together with the match, so an edit
|
|
|
192
195
|
|
|
193
196
|
### Models
|
|
194
197
|
|
|
195
|
-
A model id is `<provider>/<model>`.
|
|
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
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
|
|
|
@@ -203,17 +209,17 @@ createDecisionPlugin({
|
|
|
203
209
|
});
|
|
204
210
|
```
|
|
205
211
|
|
|
206
|
-
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.
|
|
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
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.
|
|
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
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
|
|
|
@@ -265,7 +271,7 @@ 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` | `"
|
|
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
|
|
|
@@ -338,7 +344,7 @@ Rules on different models are asked separately, one request per file and model.
|
|
|
338
344
|
|
|
339
345
|
## Providers
|
|
340
346
|
|
|
341
|
-
`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.
|
|
342
348
|
|
|
343
349
|
```js
|
|
344
350
|
// decision-plugin.mjs
|
|
@@ -391,9 +397,9 @@ export default defineConfig({
|
|
|
391
397
|
|
|
392
398
|
`createDecisionPlugin` checks every rule and setting when the plugin loads. A typo in a rule fails the oxlint run instead of being ignored.
|
|
393
399
|
|
|
394
|
-
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 `openRouter`
|
|
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.
|
|
395
401
|
|
|
396
|
-
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
|
|
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`.
|
|
397
403
|
|
|
398
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.
|
|
399
405
|
|
|
@@ -401,11 +407,11 @@ Types for all of this are exported. The rule types include `DecisionRule`, `Deci
|
|
|
401
407
|
|
|
402
408
|
## How it works
|
|
403
409
|
|
|
404
|
-
Each file gets one request per model, with every match for that model in it. Respan models get one request per
|
|
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.
|
|
405
411
|
|
|
406
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.
|
|
407
413
|
|
|
408
|
-
|
|
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`.
|
|
409
415
|
|
|
410
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"`.
|
|
411
417
|
|
|
@@ -432,7 +438,7 @@ Before running the plugin on a real codebase, put these three in place.
|
|
|
432
438
|
restore-keys: oxlint-decision-
|
|
433
439
|
```
|
|
434
440
|
|
|
435
|
-
|
|
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.
|
|
436
442
|
|
|
437
443
|
## In the editor
|
|
438
444
|
|
|
@@ -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;AAC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YAAY,eAAe,CACpC;CACA,MAAM,MAAM,OAAO;CACnB,MAAM,OAAO,OAAO,MAAMA,OAAI,UAAU,KAAK,SAAS,CAAC;CACvD,MAAM,UAAU,OAAO,WAAW,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
|
@@ -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
|
package/dist/index.mjs
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { S as isReported, _ as resolveModel, a as messageOf, c as toJson, d as PREFIX, f as STRICT, g as optionsError, h as modelIdsOf, i as failsInCi, l as warnOnce, m as checked, n as envNameOf, o as nowMs, p as checkRules, r as envOf, s as runOrElse, u as ModelSpecSchema, v as resolveOptions } from "./runtime-CICpEidL.mjs";
|
|
2
|
+
import { a as buildRequest, c as refAt, d as locates, f as locationCandidates, g as sourceLines, h as selectedLocation, i as yesNoRequestsFor, l as truncateSnippet, m as locationQuestion, o as locationRefOf, p as locationOfLine, r as wireRequestsFor, s as parseVerdicts, u as EVERY_LINE } from "./wire-BbVK3Q_K.mjs";
|
|
2
3
|
import { Array, Boolean, Console, Effect, Function, Match, Option, Predicate, Record, Schema, String as String$1, Struct, pipe } from "effect";
|
|
3
4
|
import { createSyncFn } from "synckit";
|
|
4
5
|
// src/define.ts
|
|
5
6
|
const defineDecisionRule = (rule) => rule;
|
|
6
7
|
const defineProvider = (provider) => provider;
|
|
7
|
-
// src/
|
|
8
|
+
// src/sync-provider.ts
|
|
8
9
|
const BACKSTOP_MS = 6e4;
|
|
9
10
|
const SYNCKIT_TIMEOUT = "Internal error: Atomics.wait() failed: timed-out";
|
|
10
|
-
const workers = /* @__PURE__ */ new Map();
|
|
11
|
-
const WORKER_NAME = "openrouter-worker";
|
|
12
11
|
const BUILT_EXTENSION = ".mjs";
|
|
13
12
|
const MODULE_EXTENSION = /\.[cm]?[jt]s$/u;
|
|
14
|
-
const
|
|
13
|
+
const workers = /* @__PURE__ */ new Map();
|
|
14
|
+
const workerUrl = (worker) => {
|
|
15
15
|
const extension = pipe(String$1.match(MODULE_EXTENSION)(import.meta.url), Option.flatMap(Array.head), Option.getOrElse(() => BUILT_EXTENSION));
|
|
16
|
-
return new URL(`${
|
|
16
|
+
return new URL(`${worker}${extension}`, import.meta.url);
|
|
17
17
|
};
|
|
18
|
-
const workerCall = () => {
|
|
19
|
-
const existing = workers.get(
|
|
18
|
+
const workerCall = (worker) => {
|
|
19
|
+
const existing = workers.get(worker);
|
|
20
20
|
if (Predicate.isNotUndefined(existing)) return existing;
|
|
21
|
-
const created = createSyncFn(workerUrl(), { timeout: BACKSTOP_MS });
|
|
22
|
-
workers.set(
|
|
21
|
+
const created = createSyncFn(workerUrl(worker), { timeout: BACKSTOP_MS });
|
|
22
|
+
workers.set(worker, created);
|
|
23
23
|
return created;
|
|
24
24
|
};
|
|
25
25
|
const reasonOf = (error) => {
|
|
@@ -27,19 +27,31 @@ const reasonOf = (error) => {
|
|
|
27
27
|
if (message === SYNCKIT_TIMEOUT) return "timeout";
|
|
28
28
|
return `network: ${message}`;
|
|
29
29
|
};
|
|
30
|
-
const
|
|
30
|
+
const askWorker = (worker, inputs) => runOrElse(Effect.sync(() => workerCall(worker)(inputs)), (cause) => pipe(inputs, Array.map(() => ({
|
|
31
31
|
ok: false,
|
|
32
32
|
reason: reasonOf(cause)
|
|
33
33
|
}))));
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
decide: (input) => Array.headNonEmpty(ask([input])),
|
|
34
|
+
const syncProvider = ({ worker, ...provider }) => ({
|
|
35
|
+
...provider,
|
|
36
|
+
decide: (input) => Array.headNonEmpty(askWorker(worker, [input])),
|
|
38
37
|
decideAll: (inputs) => Array.match(inputs, {
|
|
39
38
|
onEmpty: () => [],
|
|
40
|
-
onNonEmpty: (some) =>
|
|
39
|
+
onNonEmpty: (some) => askWorker(worker, some)
|
|
41
40
|
})
|
|
42
|
-
};
|
|
41
|
+
});
|
|
42
|
+
// src/cloudflare.ts
|
|
43
|
+
const cloudflare = syncProvider({
|
|
44
|
+
name: "cloudflare",
|
|
45
|
+
worker: "cloudflare-worker",
|
|
46
|
+
requiredEnv: ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"],
|
|
47
|
+
yesNo: true
|
|
48
|
+
});
|
|
49
|
+
// src/openrouter.ts
|
|
50
|
+
const openRouter = syncProvider({
|
|
51
|
+
name: "openrouter",
|
|
52
|
+
worker: "openrouter-worker",
|
|
53
|
+
requiredEnv: ["OPENROUTER_API_KEY"]
|
|
54
|
+
});
|
|
43
55
|
// src/override.ts
|
|
44
56
|
const DATA_FIRST_ARITY_3$3 = 3;
|
|
45
57
|
const RuleOverrideSchema = Schema.Struct({ model: Schema.optionalKey(ModelSpecSchema) });
|
|
@@ -193,6 +205,9 @@ const isSelected = Function.dual(DATA_FIRST_ARITY_3$1, (context, node, { select
|
|
|
193
205
|
context
|
|
194
206
|
})
|
|
195
207
|
}));
|
|
208
|
+
// src/budget.ts
|
|
209
|
+
const OUT_OF_BUDGET = /^http (?:402|403): .*(?:credit|budget)/iu;
|
|
210
|
+
const outOfBudget = (reason) => OUT_OF_BUDGET.test(reason);
|
|
196
211
|
// src/explain-text.ts
|
|
197
212
|
const DECIMALS$1 = 2;
|
|
198
213
|
const fixed = (value) => value.toFixed(DECIMALS$1);
|
|
@@ -295,7 +310,10 @@ const printerFor = (mode) => (explanation) => {
|
|
|
295
310
|
Effect.runFork(Console.error(line));
|
|
296
311
|
};
|
|
297
312
|
const explaining = (pass, mode) => {
|
|
298
|
-
const sent =
|
|
313
|
+
const sent = Boolean.match(pass.yesNo, {
|
|
314
|
+
onTrue: () => yesNoRequestsFor(pass.request),
|
|
315
|
+
onFalse: () => wireRequestsFor(pass.request)
|
|
316
|
+
});
|
|
299
317
|
const print = printerFor(mode);
|
|
300
318
|
return {
|
|
301
319
|
outcome: (match, at, { served, answers, cached, verdict, reported }) => {
|
|
@@ -409,12 +427,13 @@ const locateMatch = Function.dual(DATA_FIRST_ARITY_3, (asking, match, { ref, ver
|
|
|
409
427
|
});
|
|
410
428
|
// src/report.ts
|
|
411
429
|
const DECIMALS = 2;
|
|
430
|
+
const failsHere = (pass, reason) => failsInCi(pass.options) && !outOfBudget(reason);
|
|
412
431
|
const degrade = (pass, reason) => {
|
|
413
|
-
if (
|
|
432
|
+
if (failsHere(pass, reason)) throw optionsError(`${reason} (${pass.filename})`);
|
|
414
433
|
warnOnce(reason, `${reason} (${pass.filename})`);
|
|
415
434
|
};
|
|
416
435
|
const reportFailure = (pass, failure) => {
|
|
417
|
-
if (
|
|
436
|
+
if (failsHere(pass, failure.reason)) {
|
|
418
437
|
pass.contextOf(failure.match).report({
|
|
419
438
|
loc: failure.loc,
|
|
420
439
|
messageId: "unlocated",
|
|
@@ -504,6 +523,7 @@ const explainPassOf = (pass, { request, durationMs }) => ({
|
|
|
504
523
|
}),
|
|
505
524
|
filename: pass.filename,
|
|
506
525
|
model: pass.model.id,
|
|
526
|
+
yesNo: pass.model.provider.yesNo === true,
|
|
507
527
|
request,
|
|
508
528
|
durationMs
|
|
509
529
|
});
|
|
@@ -740,7 +760,11 @@ const memoizedRules = (providers) => {
|
|
|
740
760
|
};
|
|
741
761
|
const createDecisionPlugin = (setup) => {
|
|
742
762
|
const name = setup.name ?? DEFAULT_NAME;
|
|
743
|
-
const providers = Record.fromEntries(pipe([
|
|
763
|
+
const providers = Record.fromEntries(pipe([
|
|
764
|
+
cloudflare,
|
|
765
|
+
openRouter,
|
|
766
|
+
...setup.providers ?? []
|
|
767
|
+
], Array.map((provider) => [provider.name, provider])));
|
|
744
768
|
const rules = checkRules(setup.rules);
|
|
745
769
|
const options = optionsOf(setup);
|
|
746
770
|
const resolve = memoized((settings) => resolveOptions({
|
|
@@ -757,6 +781,6 @@ const createDecisionPlugin = (setup) => {
|
|
|
757
781
|
}])))
|
|
758
782
|
};
|
|
759
783
|
};
|
|
760
|
-
export { createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };
|
|
784
|
+
export { cloudflare, createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };
|
|
761
785
|
|
|
762
786
|
//# sourceMappingURL=index.mjs.map
|