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