@r_masseater/oxlint-plugin-decision 0.7.0 → 0.8.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 (42) hide show
  1. package/README.md +12 -3
  2. package/dist/{app-Bso1uwY5.mjs → app-UakaWKAT.mjs} +57 -73
  3. package/dist/app-UakaWKAT.mjs.map +1 -0
  4. package/dist/cloudflare-worker.mjs +2 -3
  5. package/dist/cloudflare-worker.mjs.map +1 -1
  6. package/dist/{decision-BtTZ52be.mjs → decision-B7hahWHz.mjs} +48 -130
  7. package/dist/decision-B7hahWHz.mjs.map +1 -0
  8. package/dist/{define-presets-clyqLZxo.mjs → define-presets-yflVt8vT.mjs} +3 -3
  9. package/dist/{define-presets-clyqLZxo.mjs.map → define-presets-yflVt8vT.mjs.map} +1 -1
  10. package/dist/{index-Cgg-w0hb.d.mts → index-C0Twu0w7.d.mts} +26 -31
  11. package/dist/{index-BOrpK3Iv.d.mts → index-HOwrGbIA.d.mts} +2 -2
  12. package/dist/index.d.mts +2 -3
  13. package/dist/index.mjs +1 -1
  14. package/dist/{preset-plugin-AAwedMeS.mjs → preset-plugin-ClpEFUN5.mjs} +2 -2
  15. package/dist/{preset-plugin-AAwedMeS.mjs.map → preset-plugin-ClpEFUN5.mjs.map} +1 -1
  16. package/dist/presets/ai-slop.d.mts +2 -3
  17. package/dist/presets/ai-slop.mjs +2 -2
  18. package/dist/presets/index.d.mts +1 -1
  19. package/dist/presets/index.mjs +1 -1
  20. package/dist/presets/recommended.d.mts +1 -2
  21. package/dist/presets/recommended.mjs +2 -2
  22. package/dist/presets/review-only.d.mts +1 -2
  23. package/dist/presets/review-only.mjs +2 -2
  24. package/dist/presets/strict.d.mts +1 -2
  25. package/dist/presets/strict.mjs +2 -2
  26. package/dist/{serve-decisions-CjlhvYm7.mjs → serve-decisions-DYGwLMft.mjs} +86 -89
  27. package/dist/serve-decisions-DYGwLMft.mjs.map +1 -0
  28. package/dist/typesafe-worker.mjs +11 -0
  29. package/dist/typesafe-worker.mjs.map +1 -0
  30. package/package.json +5 -10
  31. package/skills/write-decision-rules/SKILL.md +6 -6
  32. package/skills/write-decision-rules/references/tuning.md +1 -3
  33. package/dist/app-Bso1uwY5.mjs.map +0 -1
  34. package/dist/decision-BtTZ52be.mjs.map +0 -1
  35. package/dist/index-D7VrRpTx.d.mts +0 -6
  36. package/dist/openrouter-app.d.mts +0 -19
  37. package/dist/openrouter-app.mjs +0 -1
  38. package/dist/openrouter-worker.mjs +0 -15
  39. package/dist/openrouter-worker.mjs.map +0 -1
  40. package/dist/serve-decisions-CjlhvYm7.mjs.map +0 -1
  41. package/skills/write-decision-rules/references/providers.md +0 -55
  42. /package/dist/{openrouter-worker.d.mts → typesafe-worker.d.mts} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"decision-BtTZ52be.mjs","names":["Arr","Rec","DATA_FIRST_ARITY","Rec","Fn","DATA_FIRST_ARITY","DATA_FIRST_ARITY_3","FIRST_LINE","Str","Num","Bool","Arr","Fn","Rec","FIRST_LINE","Rec","Str","DATA_FIRST_ARITY_3","FIRST_LINE","Arr","Str","Fn","DATA_FIRST_ARITY_3","Str","Fn","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","DATA_FIRST_ARITY","Bool","Str","Num","Fn","Arr","Rec","choiceQuestionsOf","DATA_FIRST_ARITY","Fn","Str","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","Num","Bool","Rec","Arr","Fn"],"sources":["../src/entities/decision/model/schema.ts","../src/entities/decision/model/answer.ts","../src/entities/decision/model/location.ts","../src/entities/decision/model/nodes.ts","../src/entities/decision/model/context.ts","../src/entities/decision/model/name.ts","../src/entities/decision/model/options.ts","../src/entities/decision/model/request.ts","../src/entities/decision/model/runtime.ts","../src/entities/decision/model/wire-choice.ts","../src/entities/decision/model/wire.ts"],"sourcesContent":["import { Schema, Array as Arr, Record as Rec, pipe } from \"effect\";\n\nconst NONE = 0;\nconst MINIMUM_LABELS = 2;\n\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(NONE));\n\nexport const Probability = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 }));\n\nexport const CONFIDENT = 0.8;\n\nexport const Cutoff = Schema.Finite.check(\n Schema.isBetween(\n { minimum: CONFIDENT, maximum: 1 },\n { message: `cutoff must be between ${CONFIDENT} and 1` },\n ),\n);\n\nexport const TargetSchema = Schema.Literals([\"function\", \"call\", \"jsx\", \"file\"]);\n\nexport const CiBehaviorSchema = Schema.Literals([\"skip\", \"fail\"]);\n\nexport const ExplainSettingSchema = Schema.Union([\n Schema.Boolean,\n Schema.Literals([\"text\", \"json\"]),\n]);\n\nexport const EnclosingKindSchema = Schema.Literals([\"function\", \"class\", \"block\"]);\n\nexport const RuleContextSchema = Schema.Union([\n Schema.Struct({ scope: Schema.Literals([\"node\", \"file\", \"comment\"]) }),\n Schema.Struct({\n scope: Schema.Literal(\"lines\"),\n before: Schema.optionalKey(NonNegativeInt),\n after: Schema.optionalKey(NonNegativeInt),\n }),\n Schema.Struct({ scope: Schema.Literal(\"enclosing\"), kind: EnclosingKindSchema }),\n]);\n\nexport const SeveritySchema = Schema.Literals([\"info\", \"warn\", \"error\"]);\n\nconst Label = Schema.NonEmptyString;\n\nconst BooleanAnswer = Schema.Struct({ kind: Schema.Literal(\"boolean\") });\n\nconst ClassifyAnswer = Schema.Struct({\n kind: Schema.Literal(\"classify\"),\n labels: Schema.Record(Label, Schema.String).check(Schema.isMinProperties(MINIMUM_LABELS)),\n report: Schema.NonEmptyArray(Label),\n}).check(\n Schema.makeFilter(\n ({ labels, report }) =>\n pipe(\n report,\n Arr.every((label) => Rec.has(labels, label)),\n ),\n {\n message: \"every label in report must be one of labels\",\n },\n ),\n);\n\nconst SeverityAnswer = Schema.Struct({\n kind: Schema.Literal(\"severity\"),\n minimum: Schema.optionalKey(SeveritySchema),\n});\n\nexport const RuleAnswerSchema = Schema.Union([BooleanAnswer, ClassifyAnswer, SeverityAnswer]);\n","import { Option, Result, Schema, Record as Rec, Function as Fn } from \"effect\";\n\nimport { Probability, RuleAnswerSchema } from \"./schema.ts\";\nimport type {\n Answer,\n ChoiceAnswer,\n NoulAnswer,\n Question,\n RuleAnswer,\n Severity,\n Verdict,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst YES = \"yes\";\nconst DEFAULT_MINIMUM: Severity = \"warn\";\n\nconst SEVERITY_CRITERIA = {\n none: \"No problem\",\n info: \"Worth noting, but not a problem\",\n warn: \"Likely a problem\",\n error: \"Clearly a problem\",\n} as const;\n\nexport const SEVERITY_ORDER: readonly string[] = Rec.keys(SEVERITY_CRITERIA);\n\nexport const BOOLEAN_ANSWER: RuleAnswer = { kind: \"boolean\" };\n\nconst decodeAnswer = Schema.decodeUnknownResult(RuleAnswerSchema);\n\nexport const decodeRuleAnswer = (answer: unknown): Result.Result<RuleAnswer, string> => {\n const decoded = decodeAnswer(answer);\n if (Result.isSuccess(decoded)) {\n return Result.succeed(decoded.success);\n }\n return Result.fail(decoded.failure.message);\n};\n\nconst NoulAnswerSchema = Schema.Struct({ type: Schema.Literal(\"noul\"), noul: Probability });\n\nconst ChoiceAnswerSchema = Schema.Struct({\n type: Schema.Literal(\"choice\"),\n choice: Schema.String,\n probabilities: Schema.optional(Schema.Record(Schema.String, Probability)),\n} satisfies Partial<Record<keyof ChoiceAnswer, Schema.Top>>);\n\nexport const AnswerSchema = Schema.Union([NoulAnswerSchema, ChoiceAnswerSchema]);\n\nconst decodeNoul = Schema.decodeOption(NoulAnswerSchema);\n\nconst decodeChoice = Schema.decodeOption(ChoiceAnswerSchema);\n\nconst isNoul = (answer: Answer): answer is NoulAnswer => answer.type === \"noul\";\n\nconst isChoice = (answer: Answer): answer is ChoiceAnswer => answer.type === \"choice\";\n\nexport const noulOf = (answer: Answer | undefined): Option.Option<NoulAnswer> =>\n Option.fromUndefinedOr(answer).pipe(Option.filter(isNoul), Option.flatMap(decodeNoul));\n\nexport const choiceOf = (answer: Answer | undefined): Option.Option<ChoiceAnswer> =>\n Option.fromUndefinedOr(answer).pipe(Option.filter(isChoice), Option.flatMap(decodeChoice));\n\nexport const probabilityOfChoice = ({\n choice,\n probabilities,\n}: ChoiceAnswer): Option.Option<number> =>\n Option.fromUndefinedOr(probabilities).pipe(\n Option.flatMap((byLabel) => Option.fromUndefinedOr(byLabel[choice])),\n );\n\nexport const questionFor: {\n (instructions: string): (answer: RuleAnswer) => Question;\n (answer: RuleAnswer, instructions: string): Question;\n} = Fn.dual(DATA_FIRST_ARITY, (answer: RuleAnswer, instructions: string): Question => {\n switch (answer.kind) {\n case \"classify\": {\n return {\n type: \"choice\",\n instructions: `${instructions} Select the label that fits best.`,\n criteria: answer.labels,\n };\n }\n case \"severity\": {\n return {\n type: \"choice\",\n instructions: `${instructions} Rate how serious the problem is, and select none if there is no problem.`,\n criteria: SEVERITY_CRITERIA,\n };\n }\n case \"boolean\": {\n return { type: \"noul\", instructions };\n }\n default: {\n return { type: \"noul\", instructions };\n }\n }\n});\n\nconst choiceVerdictOf = (\n criteria: Readonly<Record<string, unknown>>,\n answer: Answer | undefined,\n): Option.Option<Verdict> =>\n choiceOf(answer).pipe(\n Option.filter(({ choice }) => Rec.has(criteria, choice)),\n Option.flatMap((chosen) =>\n Option.map(probabilityOfChoice(chosen), (probability) => ({\n answer: chosen.choice,\n probability,\n })),\n ),\n );\n\nexport const verdictOf: {\n (answer: Answer | undefined): (question: Question) => Option.Option<Verdict>;\n (question: Question, answer: Answer | undefined): Option.Option<Verdict>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (question: Question, answer: Answer | undefined): Option.Option<Verdict> => {\n if (question.type === \"choice\") {\n return choiceVerdictOf(question.criteria, answer);\n }\n return noulOf(answer).pipe(Option.map(({ noul }) => ({ answer: YES, probability: noul })));\n },\n);\n\nconst severityMatches = (\n { minimum = DEFAULT_MINIMUM }: { readonly minimum?: Severity },\n label: string,\n): boolean => SEVERITY_ORDER.indexOf(label) >= SEVERITY_ORDER.indexOf(minimum);\n\nconst answerMatches = (answer: RuleAnswer, label: string): boolean => {\n switch (answer.kind) {\n case \"classify\": {\n return answer.report.includes(label);\n }\n case \"severity\": {\n return severityMatches(answer, label);\n }\n case \"boolean\": {\n return label === YES;\n }\n default: {\n return false;\n }\n }\n};\n\nexport const isReported: {\n (verdict: Verdict): (rule: { readonly answer: RuleAnswer; readonly cutoff: number }) => boolean;\n (rule: { readonly answer: RuleAnswer; readonly cutoff: number }, verdict: Verdict): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (rule: { readonly answer: RuleAnswer; readonly cutoff: number }, verdict: Verdict): boolean =>\n verdict.probability >= rule.cutoff && answerMatches(rule.answer, verdict.answer),\n);\n","import type { Location } from \"@oxlint/plugins\";\nimport {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { choiceOf, probabilityOfChoice } from \"./answer.ts\";\nimport type { Answer, ChoiceQuestion, LineRange, RequestMatch, RuleLocation } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\nconst DATA_FIRST_ARITY_3 = 3;\nconst CHOICE_OPTION_LIMIT = 254;\nconst FIRST_LINE = 1;\nconst MINIMUM_WIDTH = 1;\nconst UNKNOWN_CHOICE = \"unknown\";\n\nexport const sourceLines = (text: string): readonly string[] =>\n Str.split(text, /\\r\\n|[\\n\\r\\u2028\\u2029]/u);\n\nexport type LocatedMatch = RequestMatch & {\n readonly rule: { readonly question: string; readonly location: RuleLocation };\n};\n\nexport const locates = (match: RequestMatch): match is LocatedMatch =>\n Predicate.isNotUndefined(match.rule.location) && !match.truncated;\n\nexport interface NumberedLine {\n readonly text: string;\n readonly line: number;\n}\n\nexport const EVERY_LINE: LineRange = { start: FIRST_LINE, end: Number.POSITIVE_INFINITY };\n\nconst isWithin = (line: number, within: LineRange): boolean =>\n Num.between(line, { minimum: within.start, maximum: within.end });\n\nconst rangeKey = ({ start, end }: LineRange): string =>\n Bool.match(start === end, {\n onTrue: () => `L${String(start)}`,\n onFalse: () => `L${String(start)}-L${String(end)}`,\n });\n\nconst rangeLabel = ({ start, end }: LineRange): string =>\n Bool.match(start === end, {\n onTrue: () => `Line ${String(start)}`,\n onFalse: () => `Lines ${String(start)} to ${String(end)}`,\n });\n\nconst rangeOf = (group: Arr.NonEmptyReadonlyArray<NumberedLine>): LineRange => ({\n start: Arr.headNonEmpty(group).line,\n end: Arr.lastNonEmpty(group).line,\n});\n\nexport const numberedLines = (snippet: string): readonly NumberedLine[] =>\n pipe(\n sourceLines(snippet),\n Arr.map((text, index) => ({ text, line: Num.sum(index, FIRST_LINE) })),\n );\n\nexport const locationCandidates: {\n (within: LineRange): (snippet: string) => Readonly<Record<string, LineRange>>;\n (snippet: string, within: LineRange): Readonly<Record<string, LineRange>>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (snippet: string, within: LineRange): Readonly<Record<string, LineRange>> => {\n const lines = pipe(\n numberedLines(snippet),\n Arr.filter(({ text, line }) => Str.trim(text).length >= FIRST_LINE && isWithin(line, within)),\n );\n const width = Math.max(MINIMUM_WIDTH, Math.ceil(lines.length / CHOICE_OPTION_LIMIT));\n return Rec.fromEntries(\n pipe(\n Arr.chunksOf(lines, width),\n Arr.map((group) => {\n const range = rangeOf(group);\n return [rangeKey(range), range];\n }),\n ),\n );\n },\n);\n\nexport const locationQuestion: {\n (\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): (match: LocatedMatch) => ChoiceQuestion;\n (\n match: LocatedMatch,\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): ChoiceQuestion;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n match: LocatedMatch,\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): ChoiceQuestion => ({\n type: \"choice\",\n instructions: `Consider only the numbered source in state.snippets.${ref}. If it violates this rule, select the line (or range containing that line) to annotate. Rule: ${match.rule.question} Location: ${match.rule.location.question} If multiple violations exist, select the earliest one. Select ${UNKNOWN_CHOICE} if no violation exists or its location is unclear.`,\n criteria: {\n ...Rec.fromEntries(\n pipe(\n Rec.toEntries(candidates),\n Arr.map(([key, range]) => [key, rangeLabel(range)]),\n ),\n ),\n [UNKNOWN_CHOICE]: \"No clear source location for this violation\",\n },\n }),\n);\n\nexport type ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nexport const validChoice: {\n (criteria: ChoiceCriteria): (answer: Answer | undefined) => boolean;\n (answer: Answer | undefined, criteria: ChoiceCriteria): boolean;\n} = Fn.dual(DATA_FIRST_ARITY, (answer: Answer | undefined, criteria: ChoiceCriteria): boolean =>\n Option.exists(\n choiceOf(answer),\n (chosen) => Rec.has(criteria, chosen.choice) && Option.isSome(probabilityOfChoice(chosen)),\n ),\n);\n\nexport const selectedLocation: {\n (\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): (answer: Answer | undefined) => Option.Option<LineRange>;\n (\n answer: Answer | undefined,\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): Option.Option<LineRange>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n answer: Answer | undefined,\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): Option.Option<LineRange> =>\n choiceOf(answer).pipe(\n Option.filter((chosen) =>\n Option.exists(probabilityOfChoice(chosen), (probability) =>\n Num.isGreaterThanOrEqualTo(probability, cutoff),\n ),\n ),\n Option.flatMap(({ choice }) => Option.fromUndefinedOr(candidates[choice])),\n ),\n);\n\nexport const locationOfLine: {\n (line: number): (snippet: string) => Location;\n (snippet: string, line: number): Location;\n} = Fn.dual(DATA_FIRST_ARITY, (snippet: string, line: number): Location => {\n const text = Option.getOrElse(Arr.get(sourceLines(snippet), Num.decrement(line)), () => \"\");\n return {\n start: {\n line,\n column: Option.getOrElse(Str.search(/\\S/u)(text), () => Num.decrement(FIRST_LINE)),\n },\n end: { line, column: Str.trimEnd(text).length },\n };\n});\n","import type { Location } from \"@oxlint/plugins\";\nimport { Option, String as Str, Record as Rec } from \"effect\";\n\nimport type { AstNode, Target } from \"./types.ts\";\n\nconst FIRST_LINE = 1;\nconst FIRST_COLUMN = 0;\nexport const TARGET_NODE_TYPES = {\n function: [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"],\n call: [\"CallExpression\"],\n jsx: [\"JSXElement\"],\n file: [\"Program\"],\n} as const satisfies Readonly<Record<Target, readonly string[]>>;\n\nconst NAMED_PARENTS = {\n VariableDeclarator: \"init\",\n Property: \"value\",\n MethodDefinition: \"value\",\n PropertyDefinition: \"value\",\n} as const;\n\ntype NamedField = (typeof NAMED_PARENTS)[keyof typeof NAMED_PARENTS];\n\nconst NAMED_PARENT_TYPES: ReadonlySet<string> = new Set(Rec.keys(NAMED_PARENTS));\n\nconst isNamedParentType = (type: string): type is keyof typeof NAMED_PARENTS =>\n NAMED_PARENT_TYPES.has(type);\n\nconst ANONYMOUS_FUNCTIONS: ReadonlySet<string> = new Set([\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n]);\n\nconst holdsAsName = (parent: AstNode, node: AstNode): boolean => {\n if (!isNamedParentType(parent.type)) {\n return false;\n }\n const field: NamedField = NAMED_PARENTS[parent.type];\n return ANONYMOUS_FUNCTIONS.has(node.type) && parent[field] === node;\n};\n\nexport const snippetNodeFor = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => holdsAsName(parent, node)),\n Option.getOrElse((): AstNode => node),\n );\nconst headOf = (text: string, line: number, column: number): Location => {\n const [first] = Str.split(text, \"\\n\");\n return { start: { line, column }, end: { line, column: column + first.length } };\n};\n\nexport const REPORT_LOC = {\n function: (node: AstNode, text: string): Location =>\n headOf(text, node.loc.start.line, node.loc.start.column),\n call: (node: AstNode): Location => node.loc,\n jsx: (node: AstNode): Location =>\n Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,\n file: (_node: AstNode, text: string): Location => headOf(text, FIRST_LINE, FIRST_COLUMN),\n} as const satisfies Readonly<Record<Target, (node: AstNode, text: string) => Location>>;\n","import type { Context } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, Predicate, String as Str, pipe, Function as Fn } from \"effect\";\n\nimport { sourceLines } from \"./location.ts\";\nimport { snippetNodeFor } from \"./nodes.ts\";\nimport type { AstNode, EnclosingKind, ResolvedRule, RuleContext } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DEFAULT_LINES = 5;\nconst FIRST_LINE = 1;\nconst LAST = 1;\nconst END = 1;\n\nconst ENCLOSING_TYPES: Readonly<Record<EnclosingKind, readonly string[]>> = {\n function: [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"],\n class: [\"ClassDeclaration\", \"ClassExpression\"],\n block: [\"BlockStatement\", \"StaticBlock\", \"Program\"],\n};\n\nconst ancestorsOf = (node: AstNode): readonly AstNode[] =>\n Arr.unfold(Option.fromNullishOr(node.parent), (current) =>\n current.pipe(\n Option.map((ancestor) => [ancestor, Option.fromNullishOr(ancestor.parent)] as const),\n ),\n );\n\nconst enclosingText = (context: Context, node: AstNode, kind: EnclosingKind): string =>\n Arr.findFirst(ancestorsOf(node), (ancestor) =>\n ENCLOSING_TYPES[kind].includes(ancestor.type),\n ).pipe(\n Option.match({\n onNone: () => context.sourceCode.text,\n onSome: (ancestor) => context.sourceCode.getText(ancestor),\n }),\n );\n\nconst linesAround = (\n context: Context,\n node: AstNode,\n {\n before = DEFAULT_LINES,\n after = DEFAULT_LINES,\n }: { readonly before?: number; readonly after?: number },\n): string => {\n const lines = sourceLines(context.sourceCode.text);\n const first = Math.max(FIRST_LINE, node.loc.start.line - before);\n const last = Math.min(lines.length, node.loc.end.line + after);\n return pipe(\n lines,\n Arr.drop(first - FIRST_LINE),\n Arr.take(last - first + FIRST_LINE),\n Arr.map((text, index) => `L${String(first + index)}| ${text}`),\n Arr.join(\"\\n\"),\n );\n};\n\nconst DECLARING_PARENTS: ReadonlySet<string> = new Set([\n \"VariableDeclaration\",\n \"ExportNamedDeclaration\",\n \"ExportDefaultDeclaration\",\n]);\n\nconst declarationOf = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => DECLARING_PARENTS.has(parent.type)),\n Option.match({ onNone: () => node, onSome: declarationOf }),\n );\n\ninterface Span {\n readonly start: number;\n readonly end: number;\n}\n\nconst leadingOf = (text: string, comments: readonly Span[], until: number): readonly Span[] =>\n Option.match(Arr.last(comments), {\n onNone: () => [],\n onSome: (last) => {\n if (Str.isNonEmpty(Str.trim(Str.slice(last.end, until)(text)))) {\n return [];\n }\n return [...leadingOf(text, Arr.dropRight(comments, LAST), last.start), last];\n },\n });\n\nconst commentedTextOf = (context: Context, node: AstNode): Option.Option<string> => {\n const { text } = context.sourceCode;\n const named = snippetNodeFor(node);\n const [start] = declarationOf(named).range;\n const before = pipe(\n context.sourceCode.getAllComments(),\n Arr.filter((comment) => comment.type !== \"Shebang\" && comment.end <= start),\n );\n return Arr.match(leadingOf(text, before, start), {\n onEmpty: () => Option.none(),\n onNonEmpty: ([first]) => Option.some(Str.slice(first.start, named.range[END])(text)),\n });\n};\n\nconst isCommented = ({ context: wanted }: ResolvedRule): boolean =>\n Predicate.isNotUndefined(wanted) && wanted.scope === \"comment\";\n\nexport const commentedSnippetOf: {\n (node: AstNode, rule: ResolvedRule): (context: Context) => Option.Option<string>;\n (context: Context, node: AstNode, rule: ResolvedRule): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: ResolvedRule): Option.Option<string> =>\n Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node)),\n);\n\nexport const lacksComment: {\n (node: AstNode, rule: ResolvedRule): (context: Context) => boolean;\n (context: Context, node: AstNode, rule: ResolvedRule): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: ResolvedRule): boolean =>\n isCommented(rule) && Option.isNone(commentedTextOf(context, node)),\n);\n\nexport const contextOf: {\n (node: AstNode, rule: RuleContext): (context: Context) => Option.Option<string>;\n (context: Context, node: AstNode, rule: RuleContext): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: RuleContext): Option.Option<string> => {\n if (rule.scope === \"lines\") {\n return Option.some(linesAround(context, node, rule));\n }\n if (rule.scope === \"enclosing\") {\n return Option.some(enclosingText(context, node, rule.kind));\n }\n return Option.liftPredicate(context.sourceCode.text, () => rule.scope === \"file\");\n },\n);\n","import type { Context } from \"@oxlint/plugins\";\nimport { Match, Option, String as Str, Function as Fn } from \"effect\";\n\nimport type { DecisionRule, SelectedNode } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst heldName = (node: SelectedNode): Option.Option<SelectedNode> =>\n Option.flatMap(Option.fromNullishOr(node.parent), (parent) =>\n Match.value(parent).pipe(\n Match.when({ type: \"VariableDeclarator\" }, (holder) =>\n Option.liftPredicate(holder.id, () => holder.init === node),\n ),\n Match.when(\n { type: Match.is(\"Property\", \"MethodDefinition\", \"PropertyDefinition\") },\n (holder) => Option.liftPredicate(holder.key, () => holder.value === node),\n ),\n Match.orElse(() => Option.none<SelectedNode>()),\n ),\n );\n\nconst nameNodeOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: Match.is(\"FunctionDeclaration\", \"FunctionExpression\") }, (fn) =>\n Option.orElse(Option.fromNullishOr(fn.id), () => heldName(fn)),\n ),\n Match.when({ type: \"ArrowFunctionExpression\" }, heldName),\n Match.when({ type: Match.is(\"CallExpression\", \"NewExpression\") }, (call) =>\n Option.some(call.callee),\n ),\n Match.when({ type: \"JSXElement\" }, (element) => Option.some(element.openingElement.name)),\n Match.orElse(() => Option.none<SelectedNode>()),\n );\n\nconst nameOf = (node: SelectedNode, context: Context): string | undefined =>\n Option.getOrUndefined(\n Option.map(nameNodeOf(node), (name) =>\n Str.slice(name.start, name.end)(context.sourceCode.text),\n ),\n );\n\nexport const isSelected: {\n (node: SelectedNode, rule: DecisionRule): (context: Context) => boolean;\n (context: Context, node: SelectedNode, rule: DecisionRule): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: SelectedNode, { select }: DecisionRule): boolean =>\n Option.match(Option.fromUndefinedOr(select), {\n onNone: () => true,\n onSome: (selects) => selects(node, { name: nameOf(node, context), context }),\n }),\n);\n","import {\n Array as Arr,\n Option,\n Predicate,\n Result,\n Schema,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { BOOLEAN_ANSWER, decodeRuleAnswer } from \"./answer.ts\";\nimport {\n CiBehaviorSchema,\n Cutoff,\n ExplainSettingSchema,\n RuleContextSchema,\n TargetSchema,\n} from \"./schema.ts\";\nimport type {\n DecisionOptions,\n DecisionProvider,\n DecisionRule,\n ModelRef,\n ModelSpec,\n ResolvedOptions,\n ResolvedRule,\n RuleAnswer,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DATA_FIRST_ARITY = 2;\n\nexport const PREFIX = \"oxlint-plugin-decision\";\nconst PROVIDER_SEPARATOR = \"/\";\nconst ONE_RULE = 1;\n\nconst DEFAULTS = {\n ci: \"fail\",\n timeoutMs: 10_000,\n maxSnippetChars: 4000,\n model: \"cloudflare/@cf/cloudflare/clef-flash\",\n env: {},\n explain: false,\n} as const satisfies Required<DecisionOptions>;\n\nconst isSelector = (input: unknown): input is DecisionRule[\"select\"] => Predicate.isFunction(input);\n\nconst RULE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\n\nexport const ModelSpecSchema = Schema.Union([\n Schema.NonEmptyString,\n Schema.NonEmptyArray(Schema.NonEmptyString),\n]);\n\nconst ONE = 1;\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(ONE));\n\nconst RuleId = Schema.NonEmptyString.check(\n Schema.isPattern(RULE_ID, { message: \"id must be lowercase words joined by hyphens\" }),\n);\n\nconst OptionsSchema = Schema.Struct({\n ci: Schema.optionalKey(CiBehaviorSchema),\n timeoutMs: Schema.optionalKey(PositiveInt),\n maxSnippetChars: Schema.optionalKey(PositiveInt),\n model: Schema.optionalKey(ModelSpecSchema),\n env: Schema.optionalKey(Schema.Record(Schema.NonEmptyString, Schema.NonEmptyString)),\n explain: Schema.optionalKey(ExplainSettingSchema),\n});\n\nconst RuleSchema = Schema.Struct({\n id: RuleId,\n target: TargetSchema,\n question: Schema.NonEmptyString,\n cutoff: Cutoff,\n message: Schema.optionalKey(Schema.NonEmptyString),\n select: Schema.optionalKey(Schema.declare(isSelector)),\n location: Schema.optionalKey(Schema.Struct({ question: Schema.NonEmptyString, cutoff: Cutoff })),\n model: Schema.optionalKey(ModelSpecSchema),\n context: Schema.optionalKey(RuleContextSchema),\n answer: Schema.optionalKey(Schema.Unknown),\n});\n\nexport const STRICT = { onExcessProperty: \"error\" } as const;\n\nconst decodeOptions = Schema.decodeUnknownResult(OptionsSchema, STRICT);\nconst decodeRule = Schema.decodeUnknownResult(RuleSchema, STRICT);\n\nconst taggedError = Schema.TaggedError;\n\nclass OptionsError extends taggedError<OptionsError, { readonly brand: unique symbol }>()(\n \"OptionsError\",\n { message: Schema.String },\n) {}\n\nexport const optionsError = (message: string): Error =>\n OptionsError.make({ message: `${PREFIX}: ${message}` });\n\nexport const modelIdsOf = (spec: ModelSpec): readonly string[] => Arr.dedupe(Arr.ensure(spec));\n\nconst splitModelId = (id: string): Option.Option<readonly [string, string]> => {\n const [provider, ...rest] = Str.split(id, PROVIDER_SEPARATOR);\n const model = pipe(rest, Arr.join(PROVIDER_SEPARATOR));\n return Option.liftPredicate(\n [provider, model] as const,\n ([left, right]) => Str.isNonEmpty(left) && Str.isNonEmpty(right),\n );\n};\n\nconst acceptedModel = (ref: ModelRef): ModelRef => {\n const { models, name } = ref.provider;\n if (Predicate.isNotUndefined(models) && !models.test(ref.model)) {\n throw optionsError(\n `model \"${ref.id}\" is not a decision model that the \"${name}\" provider accepts`,\n );\n }\n return ref;\n};\n\nexport const resolveModel: {\n (providers: Readonly<Record<string, DecisionProvider>>): (id: string) => ModelRef;\n (id: string, providers: Readonly<Record<string, DecisionProvider>>): ModelRef;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (id: string, providers: Readonly<Record<string, DecisionProvider>>): ModelRef =>\n acceptedModel(\n splitModelId(id).pipe(\n Option.flatMap(([name, model]) =>\n Option.map(Option.fromUndefinedOr(providers[name]), (provider) => ({\n id,\n provider,\n model,\n })),\n ),\n\n Option.getOrThrowWith(() =>\n optionsError(\n `model \"${id}\" must be \"<provider>/<model>\" with a provider from: ${pipe(Rec.keys(providers), Arr.join(\", \"))}`,\n ),\n ),\n ),\n ),\n);\n\nconst duplicateIdOf = (rules: readonly DecisionRule[]): Option.Option<string> =>\n Arr.findFirst(\n Rec.toEntries(Arr.groupBy(rules, ({ id }) => id)),\n ([, same]) => same.length > ONE_RULE,\n ).pipe(Option.map(([id]) => id));\n\nconst answerOf = (rule: DecisionRule): RuleAnswer => {\n if (Predicate.isUndefined(rule.answer)) {\n return BOOLEAN_ANSWER;\n }\n return Result.getOrThrowWith(decodeRuleAnswer(rule.answer), (issue) =>\n optionsError(`rule \"${rule.id}\" has an invalid answer: ${issue}`),\n );\n};\n\nexport type Decode<Value> = (input: unknown) => Result.Result<Value, Schema.SchemaError>;\n\nexport const checked: {\n (input: unknown, what: string): <Value>(decode: Decode<Value>) => Value;\n <Value>(decode: Decode<Value>, input: unknown, what: string): Value;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n <Value>(decode: Decode<Value>, input: unknown, what: string): Value =>\n Result.getOrThrowWith(decode(input), (issue) =>\n optionsError(`invalid ${what}: ${issue.message}`),\n ),\n);\n\nconst checkRule = (rule: DecisionRule): DecisionRule => {\n checked(decodeRule, rule, `rule \"${rule.id}\"`);\n if (Predicate.isNotUndefined(rule.location) && rule.target !== \"file\") {\n throw optionsError(\"location is supported only for file rules\");\n }\n answerOf(rule);\n return rule;\n};\n\nexport const checkRules = (rules: readonly DecisionRule[]): readonly DecisionRule[] => {\n if (!Arr.isReadonlyArrayNonEmpty(rules)) {\n throw optionsError(\"rules must list at least one rule\");\n }\n Option.map(duplicateIdOf(rules), (duplicate) => {\n throw optionsError(`rule id \"${duplicate}\" is used more than once`);\n });\n return pipe(\n rules,\n Arr.map((rule) => checkRule(rule)),\n );\n};\n\nconst resolveRule =\n (fallback: ModelSpec, providers: Readonly<Record<string, DecisionProvider>>) =>\n (rule: DecisionRule): ResolvedRule => ({\n ...rule,\n answer: answerOf(rule),\n models: pipe(\n modelIdsOf(rule.model ?? fallback),\n Arr.map((id) => resolveModel(id, providers)),\n ),\n });\n\nexport interface Sources {\n readonly options: DecisionOptions;\n readonly settings?: unknown;\n}\n\nconst settingsFrom = (settings: unknown): DecisionOptions => {\n if (Predicate.isUndefined(settings)) {\n return {};\n }\n return checked(decodeOptions, settings, \"settings\");\n};\n\nexport const resolveOptions: {\n (\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n ): (sources: Sources) => ResolvedOptions;\n (\n sources: Sources,\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedOptions;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n { options, settings }: Sources,\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedOptions => {\n const fromCode = checked(decodeOptions, options, \"createDecisionPlugin options\");\n const { model, ...merged } = { ...DEFAULTS, ...fromCode, ...settingsFrom(settings) };\n return {\n ci: merged.ci,\n timeoutMs: merged.timeoutMs,\n maxSnippetChars: merged.maxSnippetChars,\n env: merged.env,\n explain: merged.explain,\n rules: pipe(\n checkRules(rules),\n Arr.map((rule) => resolveRule(model, providers)(rule)),\n ),\n };\n },\n);\n","import {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { questionFor, verdictOf } from \"./answer.ts\";\nimport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationQuestion,\n numberedLines,\n validChoice,\n} from \"./location.ts\";\nimport type { ChoiceCriteria } from \"./location.ts\";\nimport type {\n Answers,\n DecisionRequest,\n DecisionResponse,\n Question,\n RequestMatch,\n Verdict,\n Verdicts,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst FIRST_LINE = 1;\nconst LOCATION_SUFFIX = \"_location\";\nconst TRUNCATION_MARKER = \"/* ...truncated */\";\n\nexport const refAt = (index: number): string => `s${String(index)}`;\n\nexport const locationRefOf = (ref: string): string => `${ref}${LOCATION_SUFFIX}`;\n\nexport const snippetRefOf = (questionId: string): string =>\n Bool.match(Str.endsWith(LOCATION_SUFFIX)(questionId), {\n onTrue: () => Str.slice(Num.decrement(FIRST_LINE), -LOCATION_SUFFIX.length)(questionId),\n onFalse: () => questionId,\n });\n\nexport const truncateSnippet: {\n (maxChars: number): (text: string) => string;\n (text: string, maxChars: number): string;\n} = Fn.dual(DATA_FIRST_ARITY, (text: string, maxChars: number): string =>\n Bool.match(text.length <= maxChars, {\n onTrue: () => text,\n onFalse: () => `${Str.slice(Num.decrement(FIRST_LINE), maxChars)(text)}${TRUNCATION_MARKER}`,\n }),\n);\n\nconst numbered = (snippet: string): string =>\n pipe(\n numberedLines(snippet),\n Arr.map(({ text, line }) => `L${String(line)}| ${text}`),\n Arr.join(\"\\n\"),\n );\n\nconst contextNote = (match: RequestMatch, ref: string): string => {\n if (Predicate.isUndefined(match.context)) {\n return \"\";\n }\n return ` state.contexts.${ref} shows the source around it; use it only to understand the snippet.`;\n};\n\nconst mainQuestionFor = (match: RequestMatch, ref: string): readonly [string, Question] => [\n ref,\n questionFor(\n match.rule.answer,\n `Consider only snippet \"${ref}\" in state.snippets.${contextNote(match, ref)} ${match.rule.question}`,\n ),\n];\n\nconst questionsFor = (\n match: RequestMatch,\n ref: string,\n): readonly (readonly [string, Question])[] => {\n if (!locates(match)) {\n return [mainQuestionFor(match, ref)];\n }\n return [\n mainQuestionFor(match, ref),\n [\n locationRefOf(ref),\n locationQuestion(match, ref, locationCandidates(match.snippet, EVERY_LINE)),\n ],\n ];\n};\n\nconst snippetFor = (match: RequestMatch): string => {\n if (locates(match)) {\n return numbered(match.snippet);\n }\n return match.snippet;\n};\n\nconst contextsOf = (\n matches: readonly RequestMatch[],\n): Readonly<{ contexts?: Readonly<Record<string, string>> }> => {\n const contexts = pipe(\n matches,\n Arr.flatMap((match, index) =>\n Option.toArray(\n Option.map(Option.fromUndefinedOr(match.context), (text) => [refAt(index), text] as const),\n ),\n ),\n );\n if (Arr.isReadonlyArrayEmpty(contexts)) {\n return {};\n }\n return { contexts: Rec.fromEntries(contexts) };\n};\n\nexport const buildRequest: {\n (matches: readonly RequestMatch[]): (model: string) => DecisionRequest;\n (model: string, matches: readonly RequestMatch[]): DecisionRequest;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (model: string, matches: readonly RequestMatch[]): DecisionRequest => ({\n model,\n state: {\n snippets: Rec.fromEntries(\n pipe(\n matches,\n Arr.map((match, index) => [refAt(index), snippetFor(match)]),\n ),\n ),\n ...contextsOf(matches),\n },\n questions: Rec.fromEntries(\n pipe(\n matches,\n Arr.flatMap((match, index) => questionsFor(match, refAt(index))),\n ),\n ),\n }),\n);\n\nconst choiceQuestionsOf = (\n request: DecisionRequest,\n): readonly (readonly [string, ChoiceCriteria])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question.criteria] as const];\n }\n return [];\n }),\n );\n\nconst mainQuestionsOf = (request: DecisionRequest): readonly (readonly [string, Question])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.filter(([id]) => !Str.endsWith(LOCATION_SUFFIX)(id)),\n );\n\nconst resultOf = (\n answers: Answers,\n [ref, question]: readonly [string, Question],\n): readonly [string, Verdict] => [\n ref,\n Option.getOrThrowWith(\n verdictOf(question, answers[ref]),\n () => new Error(`response has no valid answer for \"${ref}\"`),\n ),\n];\n\nexport const parseVerdicts: {\n (request: DecisionRequest): (response: DecisionResponse) => Verdicts;\n (response: DecisionResponse, request: DecisionRequest): Verdicts;\n} = Fn.dual(DATA_FIRST_ARITY, (response: DecisionResponse, request: DecisionRequest): Verdicts => {\n const { model, answers } = Option.getOrThrowWith(\n Option.liftPredicate(response, ({ model: served }) => Str.isNonEmpty(served)),\n () => new Error(\"response has no model id\"),\n );\n const results = Rec.fromEntries(\n pipe(\n mainQuestionsOf(request),\n Arr.map((entry) => resultOf(answers, entry)),\n ),\n );\n const complete = pipe(\n choiceQuestionsOf(request),\n Arr.every(([id, criteria]) => validChoice(answers[id], criteria)),\n );\n return { model, results, answers, complete };\n});\n","import {\n Cause,\n DateTime,\n Config,\n Console,\n Effect,\n Exit,\n Option,\n Schema,\n String as Str,\n Function as Fn,\n} from \"effect\";\n\nimport { PREFIX } from \"./options.ts\";\nimport type { ResolvedOptions } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst encodeJson = Schema.encodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\nexport const toJson = (value: unknown): string =>\n Option.getOrElse(encodeJson(value), () => String(value));\n\nexport const nowMs = (): number => DateTime.toEpochMillis(DateTime.nowUnsafe());\n\nexport const runOrElse: {\n <Value>(\n fallback: (error: unknown) => Value,\n ): <Failure>(effect: Effect.Effect<Value, Failure>) => Value;\n <Value, Failure>(\n effect: Effect.Effect<Value, Failure>,\n fallback: (error: unknown) => Value,\n ): Value;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n <Value, Failure>(\n effect: Effect.Effect<Value, Failure>,\n fallback: (error: unknown) => Value,\n ): Value =>\n Exit.match(Effect.runSyncExit(effect), {\n onSuccess: (value) => value,\n onFailure: (cause) => fallback(Cause.squash(cause)),\n }),\n);\n\nexport const envOf = (name: string): Option.Option<string> =>\n runOrElse(Config.option(Config.NonEmptyString(name)), () => Option.none()).pipe(\n Option.map((value) => Str.trim(value)),\n Option.filter(Str.isNonEmpty),\n );\n\nexport const envNameOf: {\n (name: string): (env: Readonly<Record<string, string>>) => string;\n (env: Readonly<Record<string, string>>, name: string): string;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (env: Readonly<Record<string, string>>, name: string): string => env[name] ?? name,\n);\n\nexport const failsInCi = (options: ResolvedOptions): boolean =>\n options.ci === \"fail\" && Option.isSome(envOf(\"CI\"));\n\nconst warned = new Set<string>();\n\nexport const warnOnce: {\n (message: string): (reason: string) => void;\n (reason: string, message: string): void;\n} = Fn.dual(DATA_FIRST_ARITY, (reason: string, message: string): void => {\n if (warned.has(reason)) {\n return;\n }\n warned.add(reason);\n Effect.runFork(Console.warn(`${PREFIX}: ${message}`));\n});\n\nexport const messageOf = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n};\n\nexport const captured: {\n (name: string): (match: Option.Option<RegExpMatchArray>) => Option.Option<string>;\n (match: Option.Option<RegExpMatchArray>, name: string): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (match: Option.Option<RegExpMatchArray>, name: string): Option.Option<string> =>\n match.pipe(\n Option.flatMap((found) => Option.fromNullishOr(found.groups)),\n Option.flatMap((groups) => Option.fromNullishOr(groups[name])),\n ),\n);\n","import {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Order,\n pipe,\n Record as Rec,\n String as Str,\n Function as Fn,\n} from \"effect\";\n\nimport { SEVERITY_ORDER, noulOf } from \"./answer.ts\";\nimport { CONFIDENT } from \"./schema.ts\";\nimport type { Answers, ChoiceAnswer, ChoiceQuestion, DecisionRequest } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nexport type ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst RESPAN_MODELS = [\"respan/\"] as const;\nconst OPTION_SEPARATOR = \"__\";\nconst CERTAIN = 1;\nconst NO_SEVERITY = \"none\";\n\nexport const isRespan = (model: string): boolean =>\n pipe(\n RESPAN_MODELS,\n Arr.some((prefix) => Str.startsWith(prefix)(model)),\n );\n\nexport const optionIdOf: {\n (label: string): (id: string) => string;\n (id: string, label: string): string;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (id: string, label: string): string => `${id}${OPTION_SEPARATOR}${label}`,\n);\n\nexport const isSeverityScale = (criteria: ChoiceCriteria): boolean =>\n pipe(Rec.keys(criteria), Arr.join(\",\")) === pipe(SEVERITY_ORDER, Arr.join(\",\"));\n\nexport const levelsAboveNone = (\n criteria: ChoiceCriteria,\n): readonly (readonly [string, string | null])[] =>\n pipe(\n Rec.toEntries(criteria),\n Arr.filter(([label]) => label !== NO_SEVERITY),\n );\n\ninterface Score {\n readonly label: string;\n readonly yes: number;\n}\n\nconst byYes = Order.mapInput(Order.Number, ({ yes }: Score) => yes);\n\nconst scoreOf = (answers: Answers, id: string, label: string): Option.Option<Score> =>\n Option.map(noulOf(answers[optionIdOf(id, label)]), ({ noul }) => ({ label, yes: noul }));\n\nconst scoresOf = (\n answers: Answers,\n id: string,\n labels: readonly string[],\n): Option.Option<Arr.NonEmptyReadonlyArray<Score>> =>\n pipe(\n labels,\n Arr.map((label) => scoreOf(answers, id, label)),\n Option.all,\n Option.flatMap((scores) => Option.liftPredicate(scores, Arr.isArrayNonEmpty)),\n );\n\nconst probabilitiesOf = (scores: readonly Score[]): Readonly<Record<string, number>> =>\n Rec.fromEntries(\n pipe(\n scores,\n Arr.map(({ label, yes }) => [label, yes]),\n ),\n );\n\nconst choiceAnswer = (\n choice: string,\n probabilities: Readonly<Record<string, number>>,\n): ChoiceAnswer => ({\n type: \"choice\",\n choice,\n probabilities,\n});\n\nconst bestLabel = (scores: Arr.NonEmptyReadonlyArray<Score>): ChoiceAnswer =>\n choiceAnswer(Arr.max(scores, byYes).label, probabilitiesOf(scores));\n\nconst atLeast = (scores: Arr.NonEmptyReadonlyArray<Score>): Arr.NonEmptyReadonlyArray<Score> =>\n pipe(\n scores,\n Arr.map(({ label }, index) => ({\n label,\n yes: Math.max(\n ...pipe(\n scores.slice(index),\n Arr.map(({ yes }) => yes),\n ),\n ),\n })),\n );\n\nconst severityLevel = (scores: Arr.NonEmptyReadonlyArray<Score>): ChoiceAnswer => {\n const cumulative = atLeast(scores);\n const probabilities = {\n [NO_SEVERITY]: Num.subtract(CERTAIN, Arr.headNonEmpty(cumulative).yes),\n ...probabilitiesOf(cumulative),\n };\n const reached = pipe(\n cumulative,\n Arr.findLast(({ yes }) => yes >= CONFIDENT),\n );\n return choiceAnswer(\n Option.match(reached, { onNone: () => NO_SEVERITY, onSome: ({ label }) => label }),\n probabilities,\n );\n};\n\nconst labelsAsked = (criteria: ChoiceCriteria): readonly string[] => {\n if (isSeverityScale(criteria)) {\n return pipe(\n levelsAboveNone(criteria),\n Arr.map(([label]) => label),\n );\n }\n return Rec.keys(criteria);\n};\n\nconst choiceFromYesNo = (\n answers: Answers,\n [id, { criteria }]: readonly [string, ChoiceQuestion],\n): readonly (readonly [string, ChoiceAnswer])[] => {\n const collapse = Bool.match(isSeverityScale(criteria), {\n onTrue: () => severityLevel,\n onFalse: () => bestLabel,\n });\n return scoresOf(answers, id, labelsAsked(criteria)).pipe(\n Option.map((scores) => [id, collapse(scores)] as const),\n Option.toArray,\n );\n};\n\nconst choiceQuestionsOf = (\n request: DecisionRequest,\n): readonly (readonly [string, ChoiceQuestion])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question] as const];\n }\n return [];\n }),\n );\n\nexport const collapseChoices: {\n (answers: Answers): (request: DecisionRequest) => Answers;\n (request: DecisionRequest, answers: Answers): Answers;\n} = Fn.dual(DATA_FIRST_ARITY, (request: DecisionRequest, answers: Answers): Answers => ({\n ...answers,\n ...Rec.fromEntries(\n pipe(\n choiceQuestionsOf(request),\n Arr.flatMap((entry) => choiceFromYesNo(answers, entry)),\n ),\n ),\n}));\n\nexport const withChoices: {\n (answers: Answers): (request: DecisionRequest) => Answers;\n (request: DecisionRequest, answers: Answers): Answers;\n} = Fn.dual(DATA_FIRST_ARITY, (request: DecisionRequest, answers: Answers): Answers => {\n if (!isRespan(request.model)) {\n return answers;\n }\n return collapseChoices(request, answers);\n});\n","import { Array as Arr, Option, Predicate, pipe, Record as Rec, Function as Fn } from \"effect\";\n\nimport { snippetRefOf } from \"./request.ts\";\nimport type {\n ChoiceQuestion,\n DecisionRequest,\n DecisionResponse,\n NoulQuestion,\n Question,\n} from \"./types.ts\";\nimport {\n isRespan,\n withChoices,\n isSeverityScale,\n levelsAboveNone,\n optionIdOf,\n} from \"./wire-choice.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst MAX_QUESTIONS = 64;\n\ntype State = DecisionRequest[\"state\"];\n\nexport interface WireRequest extends Readonly<Pick<DecisionRequest, \"model\">> {\n readonly state: DecisionRequest[\"state\"] | string;\n readonly questions: Readonly<Record<string, Question>>;\n}\n\nconst sectionsOf = (name: string, entries: Readonly<Record<string, string>>): readonly string[] =>\n pipe(\n Rec.toEntries(entries),\n Arr.map(([ref, text]) => `state.${name}.${ref}:\\n${text}`),\n );\n\nconst stateAsText = ({ snippets, contexts = {} }: State): string =>\n pipe(\n [...sectionsOf(\"snippets\", snippets), ...sectionsOf(\"contexts\", contexts)],\n Arr.join(\"\\n\\n\"),\n );\n\nconst only = (\n entries: Readonly<Record<string, string>>,\n ref: string,\n): Readonly<Record<string, string>> =>\n Option.match(Option.fromUndefinedOr(entries[ref]), {\n onNone: () => ({}),\n onSome: (text) => ({ [ref]: text }),\n });\n\nconst stateOf = ({ snippets, contexts }: State, ref: string): State => {\n if (Predicate.isUndefined(contexts)) {\n return { snippets: only(snippets, ref) };\n }\n return { snippets: only(snippets, ref), contexts: only(contexts, ref) };\n};\n\nconst optionText = (label: string, description: string | null): string =>\n Option.match(Option.fromNullishOr(description), {\n onNone: () => `\"${label}\"`,\n onSome: (text) => `\"${label}\" (${text})`,\n });\n\nconst labelQuestion = (\n instructions: string,\n label: string,\n description: string | null,\n): NoulQuestion => ({\n type: \"noul\",\n instructions: `${instructions} Does the label ${optionText(label, description)} fit?`,\n});\n\nconst levelQuestion = (\n instructions: string,\n label: string,\n description: string | null,\n): NoulQuestion => ({\n type: \"noul\",\n instructions: `${instructions} Is it at least as serious as ${optionText(label, description)}?`,\n});\n\nconst yesNoQuestionsOf = (\n id: string,\n { instructions, criteria }: ChoiceQuestion,\n): readonly (readonly [string, NoulQuestion])[] => {\n if (isSeverityScale(criteria)) {\n return pipe(\n levelsAboveNone(criteria),\n Arr.map(([label, description]) => [\n optionIdOf(id, label),\n levelQuestion(instructions, label, description),\n ]),\n );\n }\n return pipe(\n Rec.toEntries(criteria),\n Arr.map(([label, description]) => [\n optionIdOf(id, label),\n labelQuestion(instructions, label, description),\n ]),\n );\n};\n\nconst asYesNo = ([id, question]: readonly [string, Question]): readonly (readonly [\n string,\n Question,\n])[] => {\n if (question.type === \"choice\") {\n return yesNoQuestionsOf(id, question);\n }\n return [[id, question]];\n};\n\ntype SnippetQuestions = Arr.NonEmptyReadonlyArray<readonly [string, Question]>;\n\nconst perSnippet =\n (wiresOf: (ref: string, questions: SnippetQuestions) => readonly WireRequest[]) =>\n (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => {\n const bySnippet = Arr.groupBy(Rec.toEntries(request.questions), ([id]) => snippetRefOf(id));\n const wires = pipe(\n Rec.toEntries(bySnippet),\n Arr.flatMap(([ref, questions]) => wiresOf(ref, questions)),\n );\n if (Arr.isReadonlyArrayNonEmpty(wires)) {\n return wires;\n }\n return [request];\n };\n\nexport const yesNoRequestsFor = (\n request: DecisionRequest,\n): Arr.NonEmptyReadonlyArray<WireRequest> =>\n perSnippet((ref, questions) => [\n {\n model: request.model,\n state: stateAsText(stateOf(request.state, ref)),\n questions: Rec.fromEntries(\n pipe(\n questions,\n Arr.flatMap((entry) => asYesNo(entry)),\n ),\n ),\n },\n ])(request);\n\nexport const snippetRequestsFor = (\n request: DecisionRequest,\n): Arr.NonEmptyReadonlyArray<WireRequest> =>\n perSnippet((ref, questions) =>\n pipe(\n Arr.chunksOf(questions, MAX_QUESTIONS),\n Arr.map((chunk): WireRequest => ({\n model: request.model,\n state: stateOf(request.state, ref),\n questions: Rec.fromEntries(chunk),\n })),\n ),\n )(request);\n\nexport const wireRequestsFor = (\n request: DecisionRequest,\n): Arr.NonEmptyReadonlyArray<WireRequest> => {\n if (isRespan(request.model)) {\n return yesNoRequestsFor(request);\n }\n return [request];\n};\n\ntype Collapse = (\n request: DecisionRequest,\n answers: DecisionResponse[\"answers\"],\n) => DecisionResponse[\"answers\"];\n\nconst merging =\n (collapse: Collapse) =>\n (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): DecisionResponse => ({\n ...Arr.headNonEmpty(responses),\n answers: collapse(\n request,\n pipe(\n responses,\n Arr.flatMap(({ answers }) => Rec.toEntries(answers)),\n Rec.fromEntries,\n ),\n ),\n });\n\nexport interface Merge {\n (\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): (request: DecisionRequest) => DecisionResponse;\n (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): DecisionResponse;\n}\n\nexport const mergeResponses: Merge = Fn.dual(DATA_FIRST_ARITY, merging(withChoices));\n"],"mappings":";;AAEA,MAAM,OAAO;AACb,MAAM,iBAAiB;AAEvB,MAAM,iBAAiB,OAAO,IAAI,MAAM,OAAO,uBAAuB,IAAI,CAAC;AAE3E,MAAa,cAAc,OAAO,OAAO,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAE,CAAC,CAAC;AAE3F,MAAa,YAAY;AAEzB,MAAa,SAAS,OAAO,OAAO,MAClC,OAAO,UACL;CAAE,SAAS;CAAW,SAAS;AAAE,GACjC,EAAE,SAAS,0BAA0B,UAAU,QAAQ,CACz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AI,KAAK,WAAwB;CAC/B,OAAO,QAAQ;CACf,OAAO,QAAQ,QAAQ,OAAO,GAAG;CACjC,WAAWD,OAAI,YAAY,KAAK;AAClC,EAAE,CACJ,CACF,CAAC,CAAC,OAAO;AAEX,MAAa,mBACX,YAC2C;CAC3C,IAAI,SAAS,QAAQ,KAAK,GACxB,OAAO,iBAAiB,OAAO;CAEjC,OAAO,CAAC,OAAO;AACjB;AAOA,MAAM,WACH,cAEC,SACA,eACsB;CACtB,GAAGC,MAAI,aAAa,SAAS;CAC7B,SAAS,SACP,SACA,KACE,WACAA,MAAI,SAAS,EAAE,cAAcD,OAAI,UAAU,OAAO,CAAC,GACnDA,OAAI,WACN,CACF;AACF;AAYF,MAAa,iBAAwBE,SAAG,KAAK,kBAAkB,QAAQ,WAAW,CAAC"}
@@ -1,6 +0,0 @@
1
- import { c as DecisionPlugin, l as DecisionPluginSetup, u as DecisionProvider } from "./index-Cgg-w0hb.mjs";
2
- declare const cloudflare: DecisionProvider;
3
- declare const openRouter: DecisionProvider;
4
- declare const createDecisionPlugin: (setup: DecisionPluginSetup) => DecisionPlugin;
5
- export { openRouter as n, cloudflare as r, createDecisionPlugin as t };
6
- //# sourceMappingURL=index-D7VrRpTx.d.mts.map
@@ -1,19 +0,0 @@
1
- import "./index-Cgg-w0hb.mjs";
2
- import { Array, Config, Effect, FileSystem, Option, Path, Schema } from "effect";
3
- import { HttpClient } from "effect/http";
4
- import { Digest } from "effect/crypto";
5
- /** @internal */
6
- type AppServices = FileSystem.FileSystem | Path.Path;
7
- /** @internal */
8
- interface AppContext {
9
- readonly repo: string;
10
- readonly context: string;
11
- }
12
- /** @internal */
13
- export declare const appContext: Effect.Effect<AppContext, never, AppServices>;
14
- /** @internal */
15
- type OpenRouterApp = Readonly<Record<"HTTP-Referer" | "X-OpenRouter-Title" | "X-OpenRouter-App-Visibility", string>>;
16
- /** @internal */
17
- export declare const openRouterApp: (tool: string) => Effect.Effect<OpenRouterApp, never, AppServices>;
18
- export type { AppContext, AppServices, OpenRouterApp };
19
- //# sourceMappingURL=openrouter-app.d.mts.map
@@ -1 +0,0 @@
1
- export { a as appContext, o as openRouterApp } from "./serve-decisions-CjlhvYm7.mjs";
@@ -1,15 +0,0 @@
1
- import { o as envNameOf, r as wireRequestsFor, t as mergeResponses } from "./decision-BtTZ52be.mjs";
2
- import { n as send, t as serveDecisions } from "./serve-decisions-CjlhvYm7.mjs";
3
- import { Config, String } from "effect";
4
- // src/app/openrouter-worker.ts
5
- const DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
6
- const API_SUFFIX = /\/api\/v1\/*$|\/+$/u;
7
- serveDecisions({
8
- endpoint: (env) => Config.String(envNameOf(env, "OPENROUTER_BASE_URL")).pipe(Config.withDefault(DEFAULT_BASE_URL), Config.map((url) => String.replace(API_SUFFIX, "")(String.trim(url)))),
9
- wires: wireRequestsFor,
10
- combine: mergeResponses,
11
- send
12
- });
13
- export {};
14
-
15
- //# sourceMappingURL=openrouter-worker.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"openrouter-worker.mjs","names":["Str"],"sources":["../src/app/openrouter-worker.ts"],"sourcesContent":["import { Config, String as Str } from \"effect\";\n\nimport { envNameOf, mergeResponses, wireRequestsFor } from \"#/entities/decision/index.ts\";\nimport { send, serveDecisions } from \"#/features/serve-decisions/index.ts\";\n\nconst DEFAULT_BASE_URL = \"https://openrouter.ai/api/v1\";\nconst API_SUFFIX = /\\/api\\/v1\\/*$|\\/+$/u;\n\nserveDecisions({\n endpoint: (env) =>\n Config.String(envNameOf(env, \"OPENROUTER_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_BASE_URL),\n Config.map((url) => Str.replace(API_SUFFIX, \"\")(Str.trim(url))),\n ),\n wires: wireRequestsFor,\n combine: mergeResponses,\n send,\n});\n"],"mappings":";;;;AAKA,MAAM,mBAAmB;AACzB,MAAM,aAAa;AAEnB,eAAe;CACb,WAAW,QACT,OAAO,OAAO,UAAU,KAAK,qBAAqB,CAAC,CAAC,CAAC,KACnD,OAAO,YAAY,gBAAgB,GACnC,OAAO,KAAK,QAAQA,OAAI,QAAQ,YAAY,EAAE,CAAC,CAACA,OAAI,KAAK,GAAG,CAAC,CAAC,CAChE;CACF,OAAO;CACP,SAAS;CACT;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"serve-decisions-CjlhvYm7.mjs","names":["Str","Arr","TOOL","RETRY_INITIAL_MS","RETRY_EXPONENT","ErrorBody","decodeErrorBody","Str","Arr","makeOpenRouter","Fn","fileSystem","path","Arr"],"sources":["../src/features/serve-decisions/model/openrouter-app.ts","../src/features/serve-decisions/model/workers-ai.ts","../src/features/serve-decisions/model/decisions.ts","../src/features/serve-decisions/model/cache.ts","../src/features/serve-decisions/model/services.ts","../src/features/serve-decisions/model/serve-decisions.ts"],"sourcesContent":["import {\n Array as Arr,\n Config,\n Effect,\n FileSystem,\n Option,\n Path,\n String as Str,\n pipe,\n} from \"effect\";\nimport type { PlatformError } from \"effect/PlatformError\";\n\nimport { captured } from \"#/entities/decision/index.ts\";\n\nconst GITHUB = \"https://github.com\";\nconst SELF = \"masseater/masseater.dev\";\nconst GIT_SUFFIX = /\\.git\\/?$/u;\nconst SEPARATORS = /[/:]/u;\nconst SLUG_PARTS = 2;\nconst GITDIR = /^gitdir:\\s*(?<dir>.+)$/mu;\nconst ORIGIN_URL = /\\[remote \"origin\"\\][^[]*?\\burl\\s*=\\s*(?<url>\\S+)/u;\n\nconst isSet = (name: string): Effect.Effect<boolean> =>\n Config.option(Config.NonEmptyString(name)).pipe(\n Effect.map(Option.isSome),\n Effect.orElseSucceed(() => false),\n );\n\nconst contextOf = Effect.gen(function* contextOf() {\n if (yield* isSet(\"GITHUB_ACTIONS\")) {\n return \"github-actions\";\n }\n if (yield* isSet(\"CLAUDE_CODE_REMOTE\")) {\n return \"claude-code-cloud\";\n }\n if (yield* isSet(\"CLAUDECODE\")) {\n return \"claude-code\";\n }\n return \"local\";\n});\n\nconst slugOf = (url: string): Option.Option<string> => {\n const parts = pipe(\n url,\n Str.trim,\n Str.replace(GIT_SUFFIX, \"\"),\n Str.split(SEPARATORS),\n Arr.filter((part) => Str.isNonEmpty(part)),\n );\n if (parts.length < SLUG_PARTS) {\n return Option.none();\n }\n return Option.some(pipe(Arr.takeRight(parts, SLUG_PARTS), Arr.join(\"/\")));\n};\n\nconst linkedGitDir = Effect.fn(\"linkedGitDir\")(function* linkedGitDir(dir: string, dotGit: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const text = yield* fs.readFileString(dotGit);\n return captured(Str.match(GITDIR)(text), \"dir\").pipe(\n Option.map((found) => path.resolve(dir, Str.trim(found))),\n );\n});\n\n/** @internal */\nexport type AppServices = FileSystem.FileSystem | Path.Path;\n\nconst gitDirAt = Effect.fn(\"gitDirAt\")(function* gitDirAt(dir: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const dotGit = path.join(dir, \".git\");\n const info = yield* fs.stat(dotGit).pipe(Effect.option);\n if (Option.isNone(info)) {\n return Option.none<string>();\n }\n if (info.value.type === \"Directory\") {\n return Option.some(dotGit);\n }\n return yield* linkedGitDir(dir, dotGit);\n});\n\nconst gitDirFrom = (\n dir: string,\n): Effect.Effect<Option.Option<string>, PlatformError, AppServices> =>\n Effect.gen(function* walk() {\n const path = yield* Path.Path;\n const here = yield* gitDirAt(dir);\n const parent = path.dirname(dir);\n if (Option.isSome(here) || parent === dir) {\n return here;\n }\n return yield* gitDirFrom(parent);\n });\n\nconst commonDirOf = Effect.fn(\"commonDirOf\")(function* commonDirOf(gitDir: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const common = yield* fs.readFileString(path.join(gitDir, \"commondir\")).pipe(Effect.option);\n return Option.match(common, {\n onNone: () => gitDir,\n onSome: (relative) => path.resolve(gitDir, Str.trim(relative)),\n });\n});\n\nconst remoteSlug = Effect.gen(function* remoteSlug() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const gitDir = yield* gitDirFrom(path.resolve(\".\"));\n if (Option.isNone(gitDir)) {\n return Option.none<string>();\n }\n const commonDir = yield* commonDirOf(gitDir.value);\n const config = yield* fs.readFileString(path.join(commonDir, \"config\"));\n return captured(Str.match(ORIGIN_URL)(config), \"url\").pipe(Option.flatMap(slugOf));\n}).pipe(Effect.orElseSucceed(() => Option.none<string>()));\n\nconst repoOf = Effect.gen(function* repoOf() {\n const fromActions = yield* Config.option(Config.NonEmptyString(\"GITHUB_REPOSITORY\")).pipe(\n Effect.orElseSucceed(() => Option.none<string>()),\n );\n if (Option.isSome(fromActions)) {\n return fromActions;\n }\n return yield* remoteSlug;\n});\n\n/** @internal */\nexport interface AppContext {\n readonly repo: string;\n readonly context: string;\n}\n\n/** @internal */\nexport const appContext: Effect.Effect<AppContext, never, AppServices> = Effect.gen(\n function* app() {\n const context = yield* contextOf;\n const repo = yield* repoOf;\n return { repo: Option.getOrElse(repo, () => SELF), context };\n },\n);\n\n/** @internal */\nexport type OpenRouterApp = Readonly<\n Record<\"HTTP-Referer\" | \"X-OpenRouter-Title\" | \"X-OpenRouter-App-Visibility\", string>\n>;\n\n/** @internal */\nexport const openRouterApp = (tool: string): Effect.Effect<OpenRouterApp, never, AppServices> =>\n Effect.gen(function* attribution() {\n const context = yield* contextOf;\n const repo = yield* repoOf;\n const slug = Option.getOrElse(repo, () => SELF);\n return {\n \"HTTP-Referer\": `${GITHUB}/${slug}/${tool}/${context}`,\n \"X-OpenRouter-Title\": `${Option.getOrElse(repo, () => \"unknown\")} ${context} ${tool}`,\n \"X-OpenRouter-App-Visibility\": \"hidden\",\n };\n });\n","import { Answer } from \"@effect/ai-openrouter/OpenRouterSchema\";\nimport {\n Array as Arr,\n Config,\n Effect,\n Option,\n Schedule,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\";\n\nimport { captured, envNameOf, toJson } from \"#/entities/decision/index.ts\";\nimport type { DecideInput, DecisionResponse, WireRequest } from \"#/entities/decision/index.ts\";\n\nimport { appContext } from \"./openrouter-app.ts\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst GATEWAY = \"default\";\nconst DEFAULT_API_URL = \"https://api.cloudflare.com/client/v4\";\nconst RUN_PATH = \"/ai/run\";\nconst TRAILING_SLASHES = /\\/+$/u;\nconst MODEL_NAME = /(?<name>[^/]+)$/u;\nconst FIRST_REDIRECT = 300;\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\n\nconst Decisions = Schema.Struct({\n model: Schema.String,\n answers: Schema.Record(Schema.String, Answer),\n});\n\nconst RunBody = Schema.Struct({ body: Schema.Struct({ result: Decisions }) });\n\nconst ErrorBody = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ message: Schema.String })),\n});\n\nconst decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);\n\nconst accountUrl = ({ api, account }: Readonly<{ api: string; account: string }>): string =>\n `${Str.replace(TRAILING_SLASHES, \"\")(Str.trim(api))}/accounts/${Str.trim(account)}`;\n\n/** @internal */\nexport const 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 modelNameOf = (model: string): string =>\n Option.getOrElse(captured(Str.match(MODEL_NAME)(model), \"name\"), () => model);\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 workersAiRequest = (\n endpoint: string,\n wire: WireRequest,\n): HttpClientRequest.HttpClientRequest =>\n HttpClientRequest.post(`${endpoint}${RUN_PATH}/${wire.model}`).pipe(\n HttpClientRequest.bodyJsonUnsafe({\n model: modelNameOf(wire.model),\n state: wire.state,\n questions: wire.questions,\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 app = yield* appContext;\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* workersAiRequest(endpoint, wire).pipe(\n HttpClientRequest.bearerToken(token),\n HttpClientRequest.setHeaders({\n \"cf-aig-gateway-id\": GATEWAY,\n \"cf-aig-metadata\": toJson({ tool: TOOL, ...app }),\n }),\n client.execute,\n );\n});\n\n/** @internal */\nexport const sendWorkersAi = Effect.fn(\"sendWorkersAi\")(function* sendWorkersAi(\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 run = yield* HttpClientResponse.schemaJson(RunBody)(response).pipe(\n Effect.mapError((error) => `invalid response: ${error.message}`),\n );\n return { model: wire.model, answers: run.body.result.answers } satisfies DecisionResponse;\n});\n","import { make as makeOpenRouter } from \"@effect/ai-openrouter/OpenRouterClient\";\nimport { Config, Effect, Option, Schedule, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/http\";\n\nimport { envNameOf } from \"#/entities/decision/index.ts\";\nimport type { DecideInput, WireRequest } from \"#/entities/decision/index.ts\";\n\nimport { openRouterApp } from \"./openrouter-app.ts\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst API_PATH = \"/api/v1\";\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\n\nconst attribution = openRouterApp(TOOL).pipe(Effect.cached, Effect.runSync);\n\nconst ErrorBody = Schema.Struct({ error: Schema.Struct({ message: Schema.String }) });\n\nconst decodeErrorBody = Schema.decodeOption(Schema.fromJsonString(ErrorBody));\n\ninterface HttpFailure {\n readonly response?: { readonly status: number } | undefined;\n readonly body?: string | undefined;\n}\n\ninterface FailureReason {\n readonly _tag: string;\n readonly message: string;\n readonly http?: HttpFailure | undefined;\n}\n\nconst serverMessageOf = (body: string | undefined, fallback: string): string =>\n Option.fromUndefinedOr(body).pipe(\n Option.flatMap(decodeErrorBody),\n Option.match({ onNone: () => fallback, onSome: ({ error }) => error.message }),\n );\n\nconst reasonFor = ({ _tag, message, http }: FailureReason): string =>\n Option.fromUndefinedOr(http).pipe(\n Option.flatMap(({ response, body }) =>\n Option.map(\n Option.fromUndefinedOr(response),\n ({ status }) => `http ${String(status)}: ${serverMessageOf(body, _tag)}`,\n ),\n ),\n Option.getOrElse(() => `network: ${message}`),\n );\n\n/** @internal */\nexport const send = Effect.fn(\"send\")(function* send(\n endpoint: string,\n decisionsRequest: WireRequest,\n { env }: Pick<DecideInput, \"env\">,\n) {\n const apiKey = yield* Config.Redacted(envNameOf(env, \"OPENROUTER_API_KEY\"));\n const headers = yield* attribution;\n const client = yield* makeOpenRouter({\n apiKey,\n apiUrl: `${endpoint}${API_PATH}`,\n transformClient: (http) =>\n http.pipe(\n HttpClient.mapRequest(HttpClientRequest.setHeaders(headers)),\n HttpClient.retryTransient({\n retryOn: \"response-only\",\n schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT),\n }),\n ),\n });\n const [body] = yield* client\n .createDecisions(decisionsRequest)\n .pipe(Effect.mapError(({ reason }) => reasonFor(reason)));\n return body;\n});\n","import { Clock, Effect, FileSystem, Option, Path, Schema, Function as Fn } from \"effect\";\nimport { Digest } from \"effect/crypto\";\n\nimport { AnswerSchema, parseVerdicts } from \"#/entities/decision/index.ts\";\nimport type { DecisionRequest, DecisionResponse } from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst CACHE_VERSION = 7;\n/** @internal */\nexport const CACHE_DIR = [\"node_modules\", \".cache\", \"oxlint-plugin-decision\"] as const;\n\nconst encodeJson = (value: unknown): Effect.Effect<string> =>\n Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(value).pipe(Effect.orDie);\n\n/** @internal */\nexport const cacheFile = Effect.fn(\"cacheFile\")(function* cacheFile(\n endpoint: string,\n request: DecisionRequest,\n) {\n const digest = yield* Digest.Digest;\n const path = yield* Path.Path;\n const json = yield* encodeJson({ version: CACHE_VERSION, endpoint, request });\n const payload = new TextEncoder().encode(json);\n const hash = yield* digest.digestHex(Digest.sha256, payload);\n return path.resolve(...CACHE_DIR, `${hash}.json`);\n});\n\nconst CachedResponse = Schema.Struct({\n model: Schema.NonEmptyString,\n answers: Schema.Record(Schema.String, AnswerSchema),\n});\n\nconst decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedResponse));\n\n/** @internal */\nexport const isComplete: {\n (request: DecisionRequest): (response: DecisionResponse) => boolean;\n (response: DecisionResponse, request: DecisionRequest): boolean;\n} = Fn.dual(DATA_FIRST_ARITY, (response: DecisionResponse, request: DecisionRequest): boolean =>\n Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(\n Option.getOrElse(() => false),\n ),\n);\n\n/** @internal */\nexport const readCache = Effect.fn(\"readCache\")(function* readCache(\n file: string,\n request: DecisionRequest,\n) {\n const fs = yield* FileSystem.FileSystem;\n const text = yield* fs.readFileString(file).pipe(Effect.option);\n return text.pipe(\n Option.flatMap((raw): Option.Option<DecisionResponse> => decodeCached(raw)),\n Option.filter((response) => isComplete(response, request)),\n );\n});\n\n/** @internal */\nexport const writeCache = Effect.fn(\"writeCache\")(function* writeCache(\n file: string,\n response: DecisionResponse,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const now = yield* Clock.currentTimeMillis;\n const temp = `${file}.tmp-${String(now)}`;\n const json = yield* encodeJson(response);\n yield* fs.makeDirectory(path.dirname(file), { recursive: true });\n yield* fs.writeFileString(temp, json);\n yield* fs.rename(temp, file);\n});\n\n/** @internal */\nexport type CacheServices = Digest.Digest | FileSystem.FileSystem | Path.Path;\n","import { layerDigest } from \"@effect/platform-node-shared/NodeCrypto\";\nimport { layer as fileSystem } from \"@effect/platform-node-shared/NodeFileSystem\";\nimport { layer as path } from \"@effect/platform-node-shared/NodePath\";\nimport { Layer } from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport { OtlpSerialization, OtlpTracer } from \"effect/observability\";\n\nconst tracing = OtlpTracer.layerFromConfig({\n resource: { serviceName: \"oxlint-plugin-decision\" },\n}).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));\n\n/** @internal */\nexport const workerServices: [\n typeof fileSystem,\n typeof path,\n typeof layerDigest,\n typeof FetchHttpClient.layer,\n typeof tracing,\n] = [fileSystem, path, layerDigest, FetchHttpClient.layer, tracing];\n","import { Array as Arr, Effect, Option, pipe } from \"effect\";\nimport type { Config } from \"effect\";\nimport type { HttpClient } from \"effect/http\";\nimport { runAsWorker } from \"synckit\";\n\nimport { messageOf } from \"#/entities/decision/index.ts\";\nimport type {\n DecideInput,\n DecideResult,\n DecisionRequest,\n DecisionResponse,\n WireRequest,\n} from \"#/entities/decision/index.ts\";\n\nimport { cacheFile, isComplete, readCache, writeCache } from \"./cache.ts\";\nimport type { CacheServices } from \"./cache.ts\";\nimport type { AppServices } from \"./openrouter-app.ts\";\nimport { workerServices } from \"./services.ts\";\n\n/** @internal */\nexport type Services = AppServices | CacheServices | HttpClient.HttpClient;\n\ntype Inputs = Arr.NonEmptyReadonlyArray<DecideInput>;\n\n/** @internal */\nexport interface Transport {\n readonly endpoint: (env: DecideInput[\"env\"]) => Config.Config<string>;\n readonly wires: (request: DecisionRequest) => Arr.NonEmptyReadonlyArray<WireRequest>;\n readonly combine: (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ) => DecisionResponse;\n readonly send: (\n endpoint: string,\n wire: WireRequest,\n input: Pick<DecideInput, \"env\">,\n ) => Effect.Effect<DecisionResponse, Config.ConfigError | string, Services>;\n}\n\nconst ask = Effect.fn(\"ask\")(function* ask(\n transport: Transport,\n endpoint: string,\n { request, timeoutMs, env }: DecideInput,\n) {\n const responses = yield* Effect.forEach(\n transport.wires(request),\n (wire) => transport.send(endpoint, wire, { env }),\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(\"timeout\"),\n }),\n );\n return transport.combine(request, responses);\n});\n\nconst askAndStore = Effect.fn(\"askAndStore\")(function* askAndStore(\n transport: Transport,\n { endpoint, file }: Readonly<{ endpoint: string; file: string }>,\n input: DecideInput,\n) {\n const response = yield* ask(transport, endpoint, input);\n if (isComplete(response, input.request)) {\n yield* writeCache(file, response).pipe(Effect.ignore);\n }\n return response;\n});\n\nconst decide = Effect.fn(\"decide\")(function* decide(transport: Transport, input: DecideInput) {\n yield* Effect.annotateCurrentSpan({ model: input.request.model });\n const endpoint = yield* transport.endpoint(input.env);\n const file = yield* cacheFile(endpoint, input.request);\n const cached = yield* readCache(file, input.request);\n yield* Effect.annotateCurrentSpan({ cached: Option.isSome(cached) });\n if (Option.isSome(cached)) {\n return { response: cached.value, cached: true };\n }\n return { response: yield* askAndStore(transport, { endpoint, file }, input), cached: false };\n});\n\nconst reasonOf = (error: unknown): string => {\n if (typeof error === \"string\") {\n return error;\n }\n return messageOf(error);\n};\n\nconst decideOne = (\n transport: Transport,\n input: DecideInput,\n): Effect.Effect<DecideResult, never, Services> =>\n decide(transport, input).pipe(\n Effect.match({\n onSuccess: ({ response, cached }): DecideResult => ({ ok: true, response, cached }),\n onFailure: (error): DecideResult => ({ ok: false, reason: reasonOf(error) }),\n }),\n );\n\nconst decideEach = (\n transport: Transport,\n inputs: Inputs,\n): Effect.Effect<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.all(\n pipe(\n inputs,\n Arr.map((input) => decideOne(transport, input)),\n ),\n { concurrency: \"unbounded\" },\n ).pipe(Effect.provide(workerServices));\n\n/** @internal */\nexport const serveDecisions = (transport: Transport): void => {\n runAsWorker((inputs: Inputs): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.runPromise(decideEach(transport, inputs)),\n );\n};\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,SAAS;AACf,MAAM,aAAa;AAEnB,MAAM,SAAS,SACb,OAAO,OAAO,OAAO,eAAe,IAAI,CAAC,CAAC,CAAC,KACzC,OAAO,IAAI,OAAO,MAAM,GACxB,OAAO,oBAAoB,KAAK,CAClC;AAEF,MAAM,YAAY,OAAO,IAAI,UAAU,YAAY;CACjD,IAAI,OAAO,MAAM,gBAAgB,GAC/B,OAAO;CAET,IAAI,OAAO,MAAM,oBAAoB,GACnC,OAAO;CAET,IAAI,OAAO,MAAM,YAAY,GAC3B,OAAO;CAET,OAAO;AACT,CAAC;AAED,MAAM,UAAU,QAAuC;CACrD,MAAM,QAAQ,KACZ,KACAA,SAAI,MACJA,SAAI,QAAQ,YAAY,EAAE,GAC1BA,SAAI,MAAM,UAAU,GACpBC,MAAI,QAAQ,SAASD,SAAI,WAAW,IAAI,CAAC,CAC3C;CACA,IAAI,MAAM,SAAS,YACjB,OAAO,OAAO,KAAK;CAErB,OAAO,OAAO,KAAK,KAAKC,MAAI,UAAU,OAAO,UAAU,GAAGA,MAAI,KAAK,GAAG,CAAC,CAAC;AAC1E;AAEA,MAAM,eAAe,OAAO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X,OAAO,WAAW,WAAW,WAAW,MAAM,CAAC,CACjD;AACF"}
@@ -1,55 +0,0 @@
1
- # Custom providers
2
-
3
- Read this when rules must ask a service other than Cloudflare and OpenRouter. `cloudflare/<model>` and `openrouter/<model>` are built in and need no provider code.
4
-
5
- ## Define and register a provider
6
-
7
- ```js
8
- // decision-plugin.mjs
9
- import {
10
- createDecisionPlugin,
11
- defineDecisionRule,
12
- defineProvider,
13
- } from "@r_masseater/oxlint-plugin-decision";
14
-
15
- export default createDecisionPlugin({
16
- name: "team",
17
- model: "internal/v2",
18
- rules: [
19
- defineDecisionRule({
20
- id: "no-swallowed-catch",
21
- target: "function",
22
- question: "Does this function catch an error and neither handle nor rethrow it?",
23
- cutoff: 0.8,
24
- }),
25
- ],
26
- providers: [
27
- defineProvider({
28
- name: "internal",
29
- requiredEnv: ["INTERNAL_DECIDER_KEY"],
30
- decide: ({ request, timeoutMs, env }) => {
31
- const key = process.env[env.INTERNAL_DECIDER_KEY ?? "INTERNAL_DECIDER_KEY"];
32
- return { ok: true, response: callYourDecider(request, key, timeoutMs) };
33
- },
34
- }),
35
- ],
36
- });
37
- ```
38
-
39
- A model id `internal/v2` routes to the provider named `internal` and sends `model: "v2"` in the request. An id whose provider is not registered makes the plugin throw at load time.
40
-
41
- `requiredEnv` lists the variables the provider needs. The plugin checks them before calling `decide`, after applying the `env` renames. When one is missing, it warns once and reports nothing for that model. In CI with `ci: "fail"`, it fails the run instead.
42
-
43
- `env` in the `decide` input is the rename map from settings, not the values. Read `process.env[env[name] ?? name]` yourself.
44
-
45
- ## The `decide` contract
46
-
47
- `decide` is synchronous because oxlint rules are. A provider that calls a network service must block on a worker thread. The built-in provider does that with [synckit](https://github.com/un-ts/synckit). Returning a Promise is not supported.
48
-
49
- The input is `{ request, timeoutMs, env }`. `request` is an OpenRouter Decisions request with `model`, `state` and `questions`. `state` holds `snippets` keyed by match id and optional `contexts`. Each question is `{ type: "noul", instructions }` or `{ type: "choice", instructions, criteria }`.
50
-
51
- The output is `{ ok: true, response }` with a Decisions response body, or `{ ok: false, reason }`. A failure is a warning (or a CI failure), never an exception. Do not throw from `decide`. Respect `timeoutMs`, which is the remaining per-file budget.
52
-
53
- Optional `decideAll(inputs)` gets every model of one file for this provider at once. It returns one result per input, in the same order. Send them concurrently there. Without it, the plugin calls `decide` once per model, one after another. A result count that differs from the input count fails every input of that call.
54
-
55
- To check the provider, run oxlint with `OXLINT_DECISION_EXPLAIN=1`. Each match should show your model id and a probability, not an `error` line.