@r_masseater/oxlint-plugin-decision 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +23 -395
  2. package/dist/app-Bso1uwY5.mjs +662 -0
  3. package/dist/app-Bso1uwY5.mjs.map +1 -0
  4. package/dist/cloudflare-worker.mjs +6 -179
  5. package/dist/cloudflare-worker.mjs.map +1 -1
  6. package/dist/decision-BtTZ52be.mjs +643 -0
  7. package/dist/decision-BtTZ52be.mjs.map +1 -0
  8. package/dist/define-presets-clyqLZxo.mjs +550 -0
  9. package/dist/define-presets-clyqLZxo.mjs.map +1 -0
  10. package/dist/index-BOrpK3Iv.d.mts +89 -0
  11. package/dist/index-Cgg-w0hb.d.mts +3370 -0
  12. package/dist/index-D7VrRpTx.d.mts +6 -0
  13. package/dist/index.d.mts +3 -3372
  14. package/dist/index.mjs +1 -786
  15. package/dist/openrouter-app.d.mts +12 -4
  16. package/dist/openrouter-app.mjs +1 -87
  17. package/dist/openrouter-worker.mjs +5 -35
  18. package/dist/openrouter-worker.mjs.map +1 -1
  19. package/dist/preset-plugin-AAwedMeS.mjs +10 -0
  20. package/dist/preset-plugin-AAwedMeS.mjs.map +1 -0
  21. package/dist/presets/ai-slop.d.mts +6 -0
  22. package/dist/presets/ai-slop.mjs +10 -0
  23. package/dist/presets/ai-slop.mjs.map +1 -0
  24. package/dist/presets/index.d.mts +3 -0
  25. package/dist/presets/index.mjs +3 -0
  26. package/dist/presets/recommended.d.mts +5 -0
  27. package/dist/presets/recommended.mjs +7 -0
  28. package/dist/presets/recommended.mjs.map +1 -0
  29. package/dist/presets/review-only.d.mts +5 -0
  30. package/dist/presets/review-only.mjs +7 -0
  31. package/dist/presets/review-only.mjs.map +1 -0
  32. package/dist/presets/strict.d.mts +5 -0
  33. package/dist/presets/strict.mjs +7 -0
  34. package/dist/presets/strict.mjs.map +1 -0
  35. package/dist/serve-decisions-CjlhvYm7.mjs +290 -0
  36. package/dist/serve-decisions-CjlhvYm7.mjs.map +1 -0
  37. package/package.json +25 -3
  38. package/skills/write-decision-rules/SKILL.md +18 -17
  39. package/skills/write-decision-rules/references/tuning.md +1 -1
  40. package/dist/index.mjs.map +0 -1
  41. package/dist/openrouter-app.mjs.map +0 -1
  42. package/dist/runtime-CICpEidL.mjs +0 -271
  43. package/dist/runtime-CICpEidL.mjs.map +0 -1
  44. package/dist/serve-decisions-cQpGj_Fq.mjs +0 -112
  45. package/dist/serve-decisions-cQpGj_Fq.mjs.map +0 -1
  46. package/dist/wire-CRD1mSAo.mjs +0 -251
  47. package/dist/wire-CRD1mSAo.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,786 +1 @@
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 { _ as sourceLines, a as yesNoRequestsFor, c as parseVerdicts, d as EVERY_LINE, f as locates, g as selectedLocation, h as locationQuestion, l as refAt, m as locationOfLine, o as buildRequest, p as locationCandidates, r as wireRequestsFor, s as locationRefOf, u as truncateSnippet } from "./wire-CRD1mSAo.mjs";
3
- import { Array, Boolean, Console, Effect, Function, Match, Option, Predicate, Record, Schema, String as String$1, Struct, pipe } from "effect";
4
- import { createSyncFn } from "synckit";
5
- // src/define.ts
6
- const defineDecisionRule = (rule) => rule;
7
- const defineProvider = (provider) => provider;
8
- // src/sync-provider.ts
9
- const BACKSTOP_MS = 6e4;
10
- const SYNCKIT_TIMEOUT = "Internal error: Atomics.wait() failed: timed-out";
11
- const BUILT_EXTENSION = ".mjs";
12
- const MODULE_EXTENSION = /\.[cm]?[jt]s$/u;
13
- const workers = /* @__PURE__ */ new Map();
14
- const workerUrl = (worker) => {
15
- const extension = pipe(String$1.match(MODULE_EXTENSION)(import.meta.url), Option.flatMap(Array.head), Option.getOrElse(() => BUILT_EXTENSION));
16
- return new URL(`${worker}${extension}`, import.meta.url);
17
- };
18
- const workerCall = (worker) => {
19
- const existing = workers.get(worker);
20
- if (Predicate.isNotUndefined(existing)) return existing;
21
- const created = createSyncFn(workerUrl(worker), { timeout: BACKSTOP_MS });
22
- workers.set(worker, created);
23
- return created;
24
- };
25
- const reasonOf = (error) => {
26
- const message = messageOf(error);
27
- if (message === SYNCKIT_TIMEOUT) return "timeout";
28
- return `network: ${message}`;
29
- };
30
- const askWorker = (worker, inputs) => runOrElse(Effect.sync(() => workerCall(worker)(inputs)), (cause) => pipe(inputs, Array.map(() => ({
31
- ok: false,
32
- reason: reasonOf(cause)
33
- }))));
34
- const syncProvider = ({ worker, ...provider }) => ({
35
- ...provider,
36
- decide: (input) => Array.headNonEmpty(askWorker(worker, [input])),
37
- decideAll: (inputs) => Array.match(inputs, {
38
- onEmpty: () => [],
39
- onNonEmpty: (some) => askWorker(worker, some)
40
- })
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
- });
55
- // src/override.ts
56
- const DATA_FIRST_ARITY_3$3 = 3;
57
- const RuleOverrideSchema = Schema.Struct({ model: Schema.optionalKey(ModelSpecSchema) });
58
- const RULE_OPTIONS_SCHEMA = [{
59
- type: "object",
60
- additionalProperties: false,
61
- properties: { model: { oneOf: [{
62
- type: "string",
63
- minLength: 1
64
- }, {
65
- type: "array",
66
- minItems: 1,
67
- items: {
68
- type: "string",
69
- minLength: 1
70
- }
71
- }] } }
72
- }];
73
- const decodeOverride = Schema.decodeUnknownResult(RuleOverrideSchema, STRICT);
74
- const overrideRule = Function.dual(DATA_FIRST_ARITY_3$3, (rule, raw, providers) => {
75
- if (Predicate.isUndefined(raw)) return rule;
76
- const { model } = checked(decodeOverride, raw, `options for rule "${rule.id}"`);
77
- return {
78
- ...rule,
79
- models: Option.match(Option.fromUndefinedOr(model), {
80
- onNone: () => rule.models,
81
- onSome: (spec) => pipe(modelIdsOf(spec), Array.map((id) => resolveModel(id, providers)))
82
- })
83
- };
84
- });
85
- // src/nodes.ts
86
- const FIRST_LINE$1 = 1;
87
- const FIRST_COLUMN = 0;
88
- const TARGET_NODE_TYPES = {
89
- function: [
90
- "FunctionDeclaration",
91
- "FunctionExpression",
92
- "ArrowFunctionExpression"
93
- ],
94
- call: ["CallExpression"],
95
- jsx: ["JSXElement"],
96
- file: ["Program"]
97
- };
98
- const NAMED_PARENTS = {
99
- VariableDeclarator: "init",
100
- Property: "value",
101
- MethodDefinition: "value",
102
- PropertyDefinition: "value"
103
- };
104
- const NAMED_PARENT_TYPES = new Set(Record.keys(NAMED_PARENTS));
105
- const isNamedParentType = (type) => NAMED_PARENT_TYPES.has(type);
106
- const ANONYMOUS_FUNCTIONS = /* @__PURE__ */ new Set(["FunctionExpression", "ArrowFunctionExpression"]);
107
- const holdsAsName = (parent, node) => {
108
- if (!isNamedParentType(parent.type)) return false;
109
- const field = NAMED_PARENTS[parent.type];
110
- return ANONYMOUS_FUNCTIONS.has(node.type) && parent[field] === node;
111
- };
112
- const snippetNodeFor = (node) => Option.fromNullishOr(node.parent).pipe(Option.filter((parent) => holdsAsName(parent, node)), Option.getOrElse(() => node));
113
- const headOf = (text, line, column) => {
114
- const [first] = String$1.split(text, "\n");
115
- return {
116
- start: {
117
- line,
118
- column
119
- },
120
- end: {
121
- line,
122
- column: column + first.length
123
- }
124
- };
125
- };
126
- const REPORT_LOC = {
127
- function: (node, text) => headOf(text, node.loc.start.line, node.loc.start.column),
128
- call: (node) => node.loc,
129
- jsx: (node) => Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,
130
- file: (_node, text) => headOf(text, FIRST_LINE$1, FIRST_COLUMN)
131
- };
132
- // src/context.ts
133
- const DATA_FIRST_ARITY_3$2 = 3;
134
- const DEFAULT_LINES = 5;
135
- const FIRST_LINE = 1;
136
- const LAST = 1;
137
- const END = 1;
138
- const ENCLOSING_TYPES = {
139
- function: [
140
- "FunctionDeclaration",
141
- "FunctionExpression",
142
- "ArrowFunctionExpression"
143
- ],
144
- class: ["ClassDeclaration", "ClassExpression"],
145
- block: [
146
- "BlockStatement",
147
- "StaticBlock",
148
- "Program"
149
- ]
150
- };
151
- const ancestorsOf = (node) => Array.unfold(Option.fromNullishOr(node.parent), (current) => current.pipe(Option.map((ancestor) => [ancestor, Option.fromNullishOr(ancestor.parent)])));
152
- const enclosingText = (context, node, kind) => Array.findFirst(ancestorsOf(node), (ancestor) => ENCLOSING_TYPES[kind].includes(ancestor.type)).pipe(Option.match({
153
- onNone: () => context.sourceCode.text,
154
- onSome: (ancestor) => context.sourceCode.getText(ancestor)
155
- }));
156
- const linesAround = (context, node, { before = DEFAULT_LINES, after = DEFAULT_LINES }) => {
157
- const lines = sourceLines(context.sourceCode.text);
158
- const first = Math.max(FIRST_LINE, node.loc.start.line - before);
159
- const last = Math.min(lines.length, node.loc.end.line + after);
160
- return pipe(lines, Array.drop(first - FIRST_LINE), Array.take(last - first + FIRST_LINE), Array.map((text, index) => `L${String(first + index)}| ${text}`), Array.join("\n"));
161
- };
162
- const DECLARING_PARENTS = /* @__PURE__ */ new Set([
163
- "VariableDeclaration",
164
- "ExportNamedDeclaration",
165
- "ExportDefaultDeclaration"
166
- ]);
167
- const declarationOf = (node) => Option.fromNullishOr(node.parent).pipe(Option.filter((parent) => DECLARING_PARENTS.has(parent.type)), Option.match({
168
- onNone: () => node,
169
- onSome: declarationOf
170
- }));
171
- const leadingOf = (text, comments, until) => Option.match(Array.last(comments), {
172
- onNone: () => [],
173
- onSome: (last) => {
174
- if (String$1.isNonEmpty(String$1.trim(String$1.slice(last.end, until)(text)))) return [];
175
- return [...leadingOf(text, Array.dropRight(comments, LAST), last.start), last];
176
- }
177
- });
178
- const commentedTextOf = (context, node) => {
179
- const { text } = context.sourceCode;
180
- const named = snippetNodeFor(node);
181
- const [start] = declarationOf(named).range;
182
- const before = pipe(context.sourceCode.getAllComments(), Array.filter((comment) => comment.type !== "Shebang" && comment.end <= start));
183
- return Array.match(leadingOf(text, before, start), {
184
- onEmpty: () => Option.none(),
185
- onNonEmpty: ([first]) => Option.some(String$1.slice(first.start, named.range[END])(text))
186
- });
187
- };
188
- const isCommented = ({ context: wanted }) => Predicate.isNotUndefined(wanted) && wanted.scope === "comment";
189
- const commentedSnippetOf = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node)));
190
- const lacksComment = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => isCommented(rule) && Option.isNone(commentedTextOf(context, node)));
191
- const contextOf = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => {
192
- if (rule.scope === "lines") return Option.some(linesAround(context, node, rule));
193
- if (rule.scope === "enclosing") return Option.some(enclosingText(context, node, rule.kind));
194
- return Option.liftPredicate(context.sourceCode.text, () => rule.scope === "file");
195
- });
196
- // src/name.ts
197
- const DATA_FIRST_ARITY_3$1 = 3;
198
- const heldName = (node) => Option.flatMap(Option.fromNullishOr(node.parent), (parent) => Match.value(parent).pipe(Match.when({ type: "VariableDeclarator" }, (holder) => Option.liftPredicate(holder.id, () => holder.init === node)), Match.when({ type: Match.is("Property", "MethodDefinition", "PropertyDefinition") }, (holder) => Option.liftPredicate(holder.key, () => holder.value === node)), Match.orElse(() => Option.none())));
199
- const nameNodeOf = (node) => Match.value(node).pipe(Match.when({ type: Match.is("FunctionDeclaration", "FunctionExpression") }, (fn) => Option.orElse(Option.fromNullishOr(fn.id), () => heldName(fn))), Match.when({ type: "ArrowFunctionExpression" }, heldName), Match.when({ type: Match.is("CallExpression", "NewExpression") }, (call) => Option.some(call.callee)), Match.when({ type: "JSXElement" }, (element) => Option.some(element.openingElement.name)), Match.orElse(() => Option.none()));
200
- const nameOf = (node, context) => Option.getOrUndefined(Option.map(nameNodeOf(node), (name) => String$1.slice(name.start, name.end)(context.sourceCode.text)));
201
- const isSelected = Function.dual(DATA_FIRST_ARITY_3$1, (context, node, { select }) => Option.match(Option.fromUndefinedOr(select), {
202
- onNone: () => true,
203
- onSome: (selects) => selects(node, {
204
- name: nameOf(node, context),
205
- context
206
- })
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);
211
- // src/explain-text.ts
212
- const DECIMALS$1 = 2;
213
- const fixed = (value) => value.toFixed(DECIMALS$1);
214
- const cachedText = (cached) => Option.match(Option.fromUndefinedOr(cached), {
215
- onNone: () => "unknown",
216
- onSome: (hit) => Boolean.match(hit, {
217
- onTrue: () => "yes",
218
- onFalse: () => "no"
219
- })
220
- });
221
- const probabilitiesText = (probabilities) => Option.match(Array.match(Record.toEntries(probabilities), {
222
- onEmpty: () => Option.none(),
223
- onNonEmpty: (entries) => Option.some(pipe(entries, Array.map(([label, value]) => `${label}=${fixed(value)}`), Array.join(" ")))
224
- }), {
225
- onNone: () => "(no answer)",
226
- onSome: (text) => text
227
- });
228
- const verdictText = (explanation) => {
229
- if (Predicate.isNotUndefined(explanation.error)) return `error: ${explanation.error}`;
230
- const outcome = Boolean.match(explanation.reported, {
231
- onTrue: () => "reported",
232
- onFalse: () => "not reported"
233
- });
234
- const cutoff = `cutoff ${fixed(explanation.cutoff)}`;
235
- return Option.match(Option.fromUndefinedOr(explanation.verdict), {
236
- onNone: () => `no verdict, ${cutoff}, ${outcome}`,
237
- onSome: ({ answer, probability }) => `${answer} ${fixed(probability)}, ${cutoff}, ${outcome}`
238
- });
239
- };
240
- const servedText = (served) => Option.match(Option.fromUndefinedOr(served), {
241
- onNone: () => "",
242
- onSome: (id) => ` (served ${id})`
243
- });
244
- const asText = (explanation) => pipe([
245
- `${PREFIX} explain: ${explanation.file}:${String(explanation.line)}:${String(explanation.column)} [${explanation.rule}] ${explanation.model}${servedText(explanation.served)} cached=${cachedText(explanation.cached)} ${String(explanation.durationMs)}ms`,
246
- ` state: ${String(explanation.state.chars)} chars ${toJson(explanation.state.head)}`,
247
- ...pipe(explanation.questions, Array.map(({ id, question, probabilities }) => ` ${id}: ${probabilitiesText(probabilities)}\n ${question}`)),
248
- ` verdict: ${verdictText(explanation)}`
249
- ], Array.join("\n"));
250
- // src/explain.ts
251
- const EXPLAIN_ENV = "OXLINT_DECISION_EXPLAIN";
252
- const OFF_VALUES = /* @__PURE__ */ new Set([
253
- "0",
254
- "false",
255
- "off",
256
- "no"
257
- ]);
258
- const STATE_HEAD_CHARS = 60;
259
- const OPTION_SEPARATOR = "__";
260
- const FIRST = 1;
261
- const START = 0;
262
- const COLUMN_BASE = 1;
263
- const SEPARATOR = /^[/\\]/u;
264
- const relativeTo = (root, filename) => Boolean.match(String$1.isNonEmpty(root) && String$1.startsWith(root)(filename) && SEPARATOR.test(String$1.slice(root.length)(filename)), {
265
- onTrue: () => String$1.slice(root.length + FIRST)(filename),
266
- onFalse: () => filename
267
- });
268
- const fromSetting = (setting) => Match.value(setting).pipe(Match.when("json", () => "json"), Match.when(true, () => "text"), Match.when("text", () => "text"), Match.orElse(() => "off"));
269
- const fromEnv = (value) => Match.value(String$1.toLowerCase(value)).pipe(Match.when("json", () => "json"), Match.when((lower) => OFF_VALUES.has(lower), () => "off"), Match.orElse(() => "text"));
270
- const explainModeOf = (setting) => Option.match(envOf(EXPLAIN_ENV), {
271
- onNone: () => fromSetting(setting),
272
- onSome: fromEnv
273
- });
274
- const probabilitiesIn = (answer) => {
275
- if (answer.type === "noul") return Option.some({ yes: answer.noul });
276
- if (answer.type === "choice") return Option.fromUndefinedOr(answer.probabilities);
277
- return Option.none();
278
- };
279
- const probabilitiesOf = (answer) => Option.fromUndefinedOr(answer).pipe(Option.flatMap(probabilitiesIn), Option.getOrElse(() => ({})));
280
- const asksAbout = (ref, id) => pipe(String$1.split(id, OPTION_SEPARATOR), Array.take(FIRST), Array.contains(ref));
281
- const sentFor = (sent, ref) => pipe(sent, Array.flatMap((wire) => pipe(Record.toEntries(wire.questions), Array.filter(([id]) => asksAbout(ref, id)))));
282
- const stateTextOf = (sent, ref, snippet) => Array.findFirst(sent, (wire) => pipe(Record.keys(wire.questions), Array.some((id) => asksAbout(ref, id)))).pipe(Option.map(({ state }) => state), Option.filter(Predicate.isString), Option.getOrElse(() => snippet));
283
- const summaryOf = (text) => ({
284
- chars: text.length,
285
- head: String$1.slice(START, STATE_HEAD_CHARS)(String$1.trim(String$1.replaceAll(/\s+/gu, " ")(text)))
286
- });
287
- const baseOf = ({ pass, sent }, match, { ref, loc }) => {
288
- const questions = sentFor(sent, ref);
289
- return (answers) => ({
290
- file: relativeTo(pass.cwd, pass.filename),
291
- line: loc.start.line,
292
- column: loc.start.column + COLUMN_BASE,
293
- rule: match.rule.id,
294
- model: pass.model,
295
- cutoff: match.rule.cutoff,
296
- durationMs: pass.durationMs,
297
- state: summaryOf(stateTextOf(sent, ref, match.snippet)),
298
- questions: pipe(questions, Array.map(([id, question]) => ({
299
- id,
300
- question: question.instructions,
301
- probabilities: probabilitiesOf(answers[id])
302
- })))
303
- });
304
- };
305
- const printerFor = (mode) => (explanation) => {
306
- const line = Boolean.match(mode === "json", {
307
- onTrue: () => toJson(explanation),
308
- onFalse: () => asText(explanation)
309
- });
310
- Effect.runFork(Console.error(line));
311
- };
312
- const explaining = (pass, mode) => {
313
- const sent = Boolean.match(pass.yesNo, {
314
- onTrue: () => yesNoRequestsFor(pass.request),
315
- onFalse: () => wireRequestsFor(pass.request)
316
- });
317
- const print = printerFor(mode);
318
- return {
319
- outcome: (match, at, { served, answers, cached, verdict, reported }) => {
320
- print({
321
- ...baseOf({
322
- pass,
323
- sent
324
- }, match, at)(answers),
325
- served,
326
- ...Option.match(Option.fromUndefinedOr(cached), {
327
- onNone: () => ({}),
328
- onSome: (hit) => ({ cached: hit })
329
- }),
330
- ...Option.match(verdict, {
331
- onNone: () => ({}),
332
- onSome: (found) => ({ verdict: found })
333
- }),
334
- reported
335
- });
336
- },
337
- failure: (matches, reason) => {
338
- for (const [index, match] of matches.entries()) {
339
- const at = {
340
- ref: refAt(index),
341
- loc: match.loc
342
- };
343
- print({
344
- ...baseOf({
345
- pass,
346
- sent
347
- }, match, at)({}),
348
- reported: false,
349
- error: reason
350
- });
351
- }
352
- }
353
- };
354
- };
355
- const SILENT = {
356
- outcome: Function.constVoid,
357
- failure: Function.constVoid
358
- };
359
- const explainerFor = (pass) => Match.value(explainModeOf(pass.setting)).pipe(Match.when("off", () => SILENT), Match.orElse((mode) => explaining(pass, mode)));
360
- // src/locate.ts
361
- const DATA_FIRST_ARITY_3 = 3;
362
- const DATA_FIRST_ARITY$1 = 2;
363
- const MINIMUM_TIMEOUT_MS = 1;
364
- const remainingMs = (deadline) => Math.max(MINIMUM_TIMEOUT_MS, deadline - nowMs());
365
- const verdictsOf = Function.dual(DATA_FIRST_ARITY$1, (result, request) => {
366
- if (!result.ok) return result;
367
- return runOrElse(Effect.sync(() => ({
368
- ok: true,
369
- verdicts: parseVerdicts(result.response, request),
370
- cached: result.cached
371
- })), (cause) => ({
372
- ok: false,
373
- reason: messageOf(cause)
374
- }));
375
- });
376
- const inputOf = Function.dual(DATA_FIRST_ARITY$1, (asking, request) => ({
377
- request,
378
- timeoutMs: remainingMs(asking.deadline),
379
- env: asking.env
380
- }));
381
- const fetchVerdicts = (asking, request) => verdictsOf(asking.model.provider.decide(inputOf(asking, request)), request);
382
- const isRange = (location) => Option.exists(location, ({ start, end }) => start !== end);
383
- const refineOnce = ({ asking, match, ref, state }, within) => {
384
- const questionId = locationRefOf(ref);
385
- const candidates = locationCandidates(match.snippet, within);
386
- const refined = fetchVerdicts(asking, {
387
- model: asking.model.model,
388
- state,
389
- questions: { [questionId]: locationQuestion(match, ref, candidates) }
390
- });
391
- if (!refined.ok) return refined;
392
- return {
393
- ...refined,
394
- next: selectedLocation(refined.verdicts.answers[questionId], candidates, match.rule.location.cutoff)
395
- };
396
- };
397
- const refine = (refinement, first) => {
398
- let location = first;
399
- while (isRange(location)) {
400
- const step = refineOnce(refinement, location.value);
401
- if (!step.ok) return {
402
- loc: refinement.match.loc,
403
- failure: Option.some(step.reason)
404
- };
405
- location = step.next ?? Option.none();
406
- }
407
- return {
408
- loc: Option.match(location, {
409
- onNone: () => refinement.match.loc,
410
- onSome: ({ start }) => locationOfLine(refinement.match.snippet, start)
411
- }),
412
- failure: Option.none()
413
- };
414
- };
415
- const locateMatch = Function.dual(DATA_FIRST_ARITY_3, (asking, match, { ref, verdicts, request }) => {
416
- if (!locates(match)) return {
417
- loc: match.loc,
418
- failure: Option.none()
419
- };
420
- const first = selectedLocation(verdicts.answers[locationRefOf(ref)], locationCandidates(match.snippet, EVERY_LINE), match.rule.location.cutoff);
421
- return refine({
422
- asking,
423
- match,
424
- ref,
425
- state: request.state
426
- }, first);
427
- });
428
- // src/report.ts
429
- const DECIMALS = 2;
430
- const failsHere = (pass, reason) => failsInCi(pass.options) && !outOfBudget(reason);
431
- const degrade = (pass, reason) => {
432
- if (failsHere(pass, reason)) throw optionsError(`${reason} (${pass.filename})`);
433
- warnOnce(reason, `${reason} (${pass.filename})`);
434
- };
435
- const reportFailure = (pass, failure) => {
436
- if (failsHere(pass, failure.reason)) {
437
- pass.contextOf(failure.match).report({
438
- loc: failure.loc,
439
- messageId: "unlocated",
440
- data: {
441
- id: failure.match.rule.id,
442
- reason: failure.reason
443
- }
444
- });
445
- return;
446
- }
447
- warnOnce(failure.reason, `${failure.reason} (${pass.filename})`);
448
- };
449
- const locate = (answered, match, { ref, failed }) => {
450
- if (failed) return {
451
- loc: match.loc,
452
- failure: Option.none()
453
- };
454
- return locateMatch(answered.asking, match, {
455
- ...answered,
456
- ref
457
- });
458
- };
459
- const outcomeOf = (answered, match, ref) => {
460
- const verdict = Option.fromUndefinedOr(answered.verdicts.results[ref]);
461
- return {
462
- served: `${answered.asking.model.provider.name}/${answered.verdicts.model}`,
463
- cached: answered.cached,
464
- answers: answered.verdicts.answers,
465
- verdict,
466
- reported: Option.exists(verdict, (found) => isReported(match.rule, found))
467
- };
468
- };
469
- const reportMatch = (pass, answered, { match, ref, failed }) => {
470
- const outcome = outcomeOf(answered, match, ref);
471
- const { verdict } = outcome;
472
- if (!outcome.reported || Option.isNone(verdict)) {
473
- answered.explainer.outcome(match, {
474
- ref,
475
- loc: match.loc
476
- }, outcome);
477
- return Option.none();
478
- }
479
- const located = locate(answered, match, {
480
- ref,
481
- failed
482
- });
483
- const at = {
484
- ref,
485
- loc: located.loc
486
- };
487
- answered.explainer.outcome(match, at, outcome);
488
- pass.contextOf(match).report({
489
- loc: located.loc,
490
- messageId: "yes",
491
- data: {
492
- id: match.rule.id,
493
- model: `${pass.model.provider.name}/${answered.verdicts.model}`,
494
- answer: verdict.value.answer,
495
- score: verdict.value.probability.toFixed(DECIMALS),
496
- cutoff: match.rule.cutoff.toFixed(DECIMALS),
497
- question: match.rule.message ?? match.rule.question
498
- }
499
- });
500
- return located.failure;
501
- };
502
- const reportMatches = (pass, answered) => {
503
- let failure = Option.none();
504
- for (const [index, match] of pass.matches.entries()) {
505
- const located = reportMatch(pass, answered, {
506
- match,
507
- ref: refAt(index),
508
- failed: Option.isSome(failure)
509
- });
510
- failure = Option.orElse(failure, () => located.pipe(Option.map((reason) => ({
511
- match,
512
- loc: match.loc,
513
- reason
514
- }))));
515
- }
516
- return failure;
517
- };
518
- const explainPassOf = (pass, { request, durationMs }) => ({
519
- setting: pass.options.explain,
520
- cwd: Option.match(Array.head(pass.matches), {
521
- onNone: () => "",
522
- onSome: (match) => pass.contextOf(match).cwd
523
- }),
524
- filename: pass.filename,
525
- model: pass.model.id,
526
- yesNo: pass.model.provider.yesNo === true,
527
- request,
528
- durationMs
529
- });
530
- const explainerOf = (pass, timed) => explainerFor(explainPassOf(pass, timed));
531
- const prepare = (pass) => ({
532
- pass,
533
- asking: {
534
- model: pass.model,
535
- deadline: pass.deadline,
536
- env: pass.options.env
537
- },
538
- request: buildRequest(pass.model.model, pass.matches)
539
- });
540
- const reportAnswer = ({ pass, asking, request }, { decided, durationMs }) => {
541
- const explainer = explainerOf(pass, {
542
- request,
543
- durationMs
544
- });
545
- const result = verdictsOf(decided, request);
546
- if (!result.ok) {
547
- explainer.failure(pass.matches, result.reason);
548
- degrade(pass, result.reason);
549
- return;
550
- }
551
- Option.map(reportMatches(pass, {
552
- ...result,
553
- asking,
554
- request,
555
- explainer
556
- }), (failure) => {
557
- reportFailure(pass, failure);
558
- });
559
- };
560
- const decideWith = (provider, prepared) => {
561
- const inputs = pipe(prepared, Array.map(({ asking, request }) => inputOf(asking, request)));
562
- return Option.match(Option.fromUndefinedOr(provider.decideAll), {
563
- onNone: () => pipe(inputs, Array.map((input) => provider.decide(input))),
564
- onSome: (decideAll) => decideAll(inputs)
565
- });
566
- };
567
- const reportProvider = (prepared) => {
568
- const { provider } = Array.headNonEmpty(prepared).pass.model;
569
- const started = performance.now();
570
- const results = decideWith(provider, prepared);
571
- const durationMs = Math.round(performance.now() - started);
572
- const answers = Boolean.match(results.length === prepared.length, {
573
- onTrue: () => results,
574
- onFalse: () => pipe(prepared, Array.map(() => ({
575
- ok: false,
576
- reason: `provider ${provider.name} returned ${String(results.length)} results for ${String(prepared.length)} requests`
577
- })))
578
- });
579
- for (const [one, decided] of Array.zip(prepared, answers)) reportAnswer(one, {
580
- decided,
581
- durationMs
582
- });
583
- };
584
- const reportModels = (passes) => {
585
- const byProvider = Array.groupBy(pipe(passes, Array.map((pass) => prepare(pass))), ({ pass }) => pass.model.provider.name);
586
- for (const prepared of Record.values(byProvider)) reportProvider(prepared);
587
- };
588
- // src/visitor.ts
589
- const DATA_FIRST_ARITY = 2;
590
- const raisedMissing = /* @__PURE__ */ new Set();
591
- const missingEnvOf = (options, provider) => pipe(provider.requiredEnv, Array.map((name) => envNameOf(options.env, name)), Array.filter((name) => Option.isNone(envOf(name))));
592
- const isAvailable = (options, { provider }) => {
593
- const missingNames = missingEnvOf(options, provider);
594
- if (Array.isReadonlyArrayEmpty(missingNames)) return true;
595
- const missing = pipe(missingNames, Array.join(", "));
596
- if (!failsInCi(options)) warnOnce(`missing:${provider.name}`, `${missing} is not set, skipping ${provider.name} models`);
597
- else if (!raisedMissing.has(provider.name)) {
598
- raisedMissing.add(provider.name);
599
- throw optionsError(`${missing} is not set`);
600
- }
601
- return false;
602
- };
603
- const availableModels = (batch) => {
604
- const models = pipe(Record.values(batch.rules), Array.flatMap((rule) => rule.models), Array.map((model) => [model.id, model]));
605
- return pipe(Array.fromIterable(new Map(models).values()), Array.filter((model) => isAvailable(batch.options, model)));
606
- };
607
- const snippetOf = (context, node) => {
608
- if (node.type === "Program") return context.sourceCode.text;
609
- return context.sourceCode.getText(node);
610
- };
611
- const namedSnippetOf = (context, node) => {
612
- const named = snippetNodeFor(node);
613
- if (named === node) return snippetOf(context, node);
614
- return context.sourceCode.getText(named);
615
- };
616
- const matchOf = (context, node, { rule, options }) => {
617
- const text = Option.getOrElse(commentedSnippetOf(context, node, rule), () => namedSnippetOf(context, node));
618
- const surrounding = contextOf(context, node, rule.context ?? { scope: "node" });
619
- return {
620
- ...Option.match(surrounding, {
621
- onNone: () => ({}),
622
- onSome: (value) => ({ context: value })
623
- }),
624
- rule,
625
- loc: REPORT_LOC[rule.target](node, snippetOf(context, node)),
626
- snippet: truncateSnippet(text, options.maxSnippetChars),
627
- truncated: text.length > options.maxSnippetChars
628
- };
629
- };
630
- const contextOfRule = (batch, id) => Option.getOrThrow(Option.fromUndefinedOr(batch.contexts[id]));
631
- const finish = (batch) => {
632
- const [first] = Record.values(batch.contexts);
633
- if (Predicate.isUndefined(first)) return;
634
- const deadline = nowMs() + batch.options.timeoutMs;
635
- const passes = pipe(availableModels(batch), Array.flatMap((model) => {
636
- const matches = pipe(batch.matches, Array.filter(({ rule }) => pipe(rule.models, Array.some(({ id }) => id === model.id))));
637
- return Array.match(matches, {
638
- onEmpty: () => [],
639
- onNonEmpty: (some) => [{
640
- contextOf: (match) => contextOfRule(batch, match.rule.id),
641
- filename: first.filename,
642
- options: batch.options,
643
- model,
644
- matches: some,
645
- deadline
646
- }]
647
- });
648
- }));
649
- reportModels(passes);
650
- };
651
- const ruleIn = (batch, id) => Option.getOrThrow(Array.findFirst(batch.options.rules, (rule) => rule.id === id));
652
- const sharedFile = Function.dual(DATA_FIRST_ARITY, (optionsFor, ruleFor) => {
653
- let current = Option.none();
654
- const start = (context) => {
655
- const batch = {
656
- options: optionsFor(context.settings),
657
- contexts: {},
658
- rules: {},
659
- matches: [],
660
- exiting: false,
661
- exits: 0
662
- };
663
- current = Option.some(batch);
664
- return batch;
665
- };
666
- return {
667
- join: (context, id) => {
668
- const batch = Option.match(current, {
669
- onNone: () => start(context),
670
- onSome: (open) => {
671
- if (open.exiting) return start(context);
672
- return open;
673
- }
674
- });
675
- const [options] = context.options;
676
- const rule = ruleFor(ruleIn(batch, id), options);
677
- batch.contexts[id] = context;
678
- batch.rules[id] = rule;
679
- return {
680
- batch,
681
- rule
682
- };
683
- },
684
- leave: () => {
685
- if (Option.isNone(current)) return;
686
- const batch = current.value;
687
- batch.exits += 1;
688
- if (batch.exits >= Record.keys(batch.contexts).length) current = Option.none();
689
- if (!batch.exiting) {
690
- batch.exiting = true;
691
- finish(batch);
692
- }
693
- }
694
- };
695
- });
696
- const isSkipped = (context, node, rule) => !isSelected(context, node, rule) || lacksComment(context, node, rule);
697
- const visitorFor = Function.dual(DATA_FIRST_ARITY, (shared, { id, target }) => (context) => {
698
- let file = Option.none();
699
- const collect = (node) => {
700
- if (Option.isNone(file)) return;
701
- const { batch, rule } = file.value;
702
- if (isSkipped(context, node, rule)) return;
703
- batch.matches.push(matchOf(context, node, {
704
- rule,
705
- options: batch.options
706
- }));
707
- };
708
- const nodeTypes = TARGET_NODE_TYPES[target];
709
- return {
710
- ...Record.fromEntries(pipe(nodeTypes, Array.map((type) => [type, collect]))),
711
- Program: (node) => {
712
- file = Option.some(shared.join(context, id));
713
- if (target === "file") collect(node);
714
- },
715
- "Program:exit": () => {
716
- file = Option.none();
717
- shared.leave();
718
- }
719
- };
720
- });
721
- // src/plugin.ts
722
- const DEFAULT_NAME = "decision";
723
- const metaOf = (rule) => ({
724
- type: "problem",
725
- docs: { description: rule.question },
726
- schema: RULE_OPTIONS_SCHEMA,
727
- messages: {
728
- yes: "[{{id}}] {{model}} answered {{answer}} ({{score}} >= {{cutoff}}): {{question}}",
729
- unlocated: `${PREFIX}: {{reason}} while refining the location of [{{id}}]; the finding is reported at the file level`
730
- }
731
- });
732
- const optionsOf = (setup) => Struct.omit(setup, [
733
- "name",
734
- "rules",
735
- "providers"
736
- ]);
737
- const memoized = (resolve) => {
738
- const resolved = /* @__PURE__ */ new Map();
739
- return (settings) => {
740
- const key = toJson([settings]);
741
- const cached = resolved.get(key);
742
- if (Predicate.isNotUndefined(cached)) return cached;
743
- const fresh = resolve(settings);
744
- resolved.set(key, fresh);
745
- return fresh;
746
- };
747
- };
748
- const memoizedRules = (providers) => {
749
- const resolved = /* @__PURE__ */ new WeakMap();
750
- return (rule, options) => {
751
- const known = resolved.get(rule) ?? /* @__PURE__ */ new Map();
752
- resolved.set(rule, known);
753
- const key = toJson([options]);
754
- const cached = known.get(key);
755
- if (Predicate.isNotUndefined(cached)) return cached;
756
- const fresh = overrideRule(rule, options, providers);
757
- known.set(key, fresh);
758
- return fresh;
759
- };
760
- };
761
- const createDecisionPlugin = (setup) => {
762
- const name = setup.name ?? DEFAULT_NAME;
763
- const providers = Record.fromEntries(pipe([
764
- cloudflare,
765
- openRouter,
766
- ...setup.providers ?? []
767
- ], Array.map((provider) => [provider.name, provider])));
768
- const rules = checkRules(setup.rules);
769
- const options = optionsOf(setup);
770
- const resolve = memoized((settings) => resolveOptions({
771
- options,
772
- settings
773
- }, rules, providers));
774
- resolve({});
775
- const shared = sharedFile((settings) => resolve(settings[name]), memoizedRules(providers));
776
- return {
777
- meta: { name },
778
- rules: Record.fromEntries(pipe(rules, Array.map((rule) => [rule.id, {
779
- meta: metaOf(rule),
780
- createOnce: visitorFor(shared, rule)
781
- }])))
782
- };
783
- };
784
- export { cloudflare, createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };
785
-
786
- //# sourceMappingURL=index.mjs.map
1
+ export { r as cloudflare, t as createDecisionPlugin, i as defineDecisionRule, a as defineProvider, n as openRouter } from "./app-Bso1uwY5.mjs";