@r_masseater/oxlint-plugin-decision 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -407,7 +407,7 @@ Types for all of this are exported. The rule types include `DecisionRule`, `Deci
407
407
 
408
408
  ## How it works
409
409
 
410
- Each file gets one request per model, with every match for that model in it. Cloudflare and Respan models get one request per question instead. Each of their choice questions becomes yes/no questions. A file rule with `location` adds numbered source and a choice question. Above 254 nonblank lines the model selects a range and refines it in follow-up requests with the same context. All requests share the per-file `timeoutMs` budget.
410
+ Each file gets one request per model, with every match for that model in it. Respan models get one request per match instead. Cloudflare and Respan models split each choice question into yes/no questions. A file rule with `location` adds numbered source and a choice question. Above 254 nonblank lines the model selects a range and refines it in follow-up requests with the same context. All requests share the per-file `timeoutMs` budget.
411
411
 
412
412
  Answers are cached under `node_modules/.cache/oxlint-plugin-decision`, keyed by the endpoint and the request. Changing a snippet, its context, a question or an answer kind re-asks that file. Changing a cutoff or an `id` does not. Malformed answers are never cached, and malformed entries already on disk are asked again. See [Cost and caching](#cost-and-caching) for how to keep the cost down.
413
413
 
@@ -1,7 +1,7 @@
1
1
  import { appContext } from "./openrouter-app.mjs";
2
2
  import { c as toJson, n as envNameOf, t as captured } from "./runtime-CICpEidL.mjs";
3
- import { t as serveDecisions } from "./serve-decisions-pOSYU_8a.mjs";
4
- import { i as yesNoRequestsFor, n as mergeYesNo } from "./wire-BbVK3Q_K.mjs";
3
+ import { t as serveDecisions } from "./serve-decisions-cQpGj_Fq.mjs";
4
+ import { i as yesNoRequestFor, n as mergeYesNo } from "./wire-CRD1mSAo.mjs";
5
5
  import { Array, Boolean, Config, Effect, Number as Number$1, Option, Record, Schedule, Schema, String as String$1, pipe } from "effect";
6
6
  import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
7
7
  // src/cloudflare-chat.ts
@@ -176,7 +176,7 @@ const sendChat = Effect.fn("sendChat")(function* sendChat(endpoint, wire, input)
176
176
  // src/cloudflare-worker.ts
177
177
  serveDecisions({
178
178
  endpoint: endpointOf,
179
- wires: yesNoRequestsFor,
179
+ wires: yesNoRequestFor,
180
180
  combine: mergeYesNo,
181
181
  send: sendChat
182
182
  });
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-worker.mjs","names":["Arr","Num","Str","Bool","Rec"],"sources":["../src/cloudflare-chat.ts","../src/cloudflare-worker.ts"],"sourcesContent":["import {\n Array as Arr,\n Boolean as Bool,\n Config,\n Effect,\n Number as Num,\n Option,\n Record as Rec,\n Schedule,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\";\n\nimport { appContext } from \"./openrouter-app.ts\";\nimport { captured, envNameOf, toJson } from \"./runtime.ts\";\nimport type { Answers, DecideInput, DecisionResponse, Question } from \"./types.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst DEFAULT_API_URL = \"https://api.cloudflare.com/client/v4\";\nconst DEFAULT_GATEWAY = \"default\";\nconst CHAT_PATH = \"/ai/v1/chat/completions\";\nconst TRAILING_SLASHES = /\\/+$/u;\nconst WORKERS_AI = \"@cf/\";\nconst TOP_LOGPROBS = 10;\nconst TOKENS_PER_ANSWER = 8;\nconst SPARE_TOKENS = 16;\nconst FIRST_LABEL = 1;\nconst NONE = 0;\nconst CERTAIN = 1;\nconst FIRST_REDIRECT = 300;\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\nconst LEADING_JUNK = /^(?<lead>[\\s::*]*)(?<word>[\\s\\S]*)$/u;\nconst LABEL_BEFORE = /(?:^|\\n)[\\s*]*q(?<index>\\d+)[\\s*]*[::]\\s*$/u;\nconst ANSWER_WORD = /^(?<word>yes|no)[\\s.,!*]*$/iu;\n\nconst SYSTEM = Arr.join(\n [\n \"You answer yes-or-no questions about the material the user gives you.\",\n \"Answer every question on its own line in the form `q<number>: yes` or `q<number>: no`, in the order asked.\",\n \"Write nothing else.\",\n ],\n \" \",\n);\n\nconst TopLogprob = Schema.Struct({ token: Schema.String, logprob: Schema.Finite });\n\nconst TokenLogprob = Schema.Struct({\n token: Schema.String,\n logprob: Schema.Finite,\n top_logprobs: Schema.optional(Schema.Array(TopLogprob)),\n});\n\nconst Logprobs = Schema.Struct({ content: Schema.NullOr(Schema.Array(TokenLogprob)) });\n\nconst OptionalLogprobs = Schema.optional(Schema.NullOr(Logprobs));\n\nconst Choice = Schema.Struct({ logprobs: OptionalLogprobs });\n\nconst ChatResponse = Schema.Struct({\n model: Schema.optional(Schema.String),\n choices: Schema.NonEmptyArray(Choice),\n});\n\nconst ChatBody = Schema.Struct({ body: ChatResponse });\n\nconst ErrorBody = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ message: Schema.String })),\n});\n\nconst decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);\n\ntype Token = typeof TokenLogprob.Type;\n\ntype YesNo = \"yes\" | \"no\";\n\ntype Mass = Readonly<Record<YesNo, number>>;\n\ntype Asked = readonly (readonly [string, Question])[];\n\ninterface Split {\n readonly lead: string;\n readonly word: string;\n}\n\nconst labelOf = (index: number): string => `q${String(Num.sum(index, FIRST_LABEL))}`;\n\nconst accountUrl = ({ api, account }: Readonly<{ api: string; account: string }>): string =>\n `${Str.replace(TRAILING_SLASHES, \"\")(Str.trim(api))}/accounts/${Str.trim(account)}`;\n\nconst endpointOf = (env: DecideInput[\"env\"]): Config.Config<string> =>\n Config.all({\n api: Config.String(envNameOf(env, \"CLOUDFLARE_API_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_API_URL),\n ),\n account: Config.NonEmptyString(envNameOf(env, \"CLOUDFLARE_ACCOUNT_ID\")),\n }).pipe(Config.map(accountUrl));\n\nconst yesNoOf = (word: string): YesNo =>\n Bool.match(Str.toLowerCase(word) === \"yes\", { onTrue: () => \"yes\", onFalse: () => \"no\" });\n\nconst answerOf = (text: string): Option.Option<YesNo> =>\n captured(Str.match(ANSWER_WORD)(text), \"word\").pipe(Option.map(yesNoOf));\n\nconst splitToken = (token: string): Split => {\n const match = Str.match(LEADING_JUNK)(token);\n return {\n lead: Option.getOrElse(captured(match, \"lead\"), () => \"\"),\n word: Option.getOrElse(captured(match, \"word\"), () => token),\n };\n};\n\nconst massOf = (token: Token): Mass => {\n const mass = { yes: NONE, no: NONE };\n for (const alternative of token.top_logprobs ?? [token]) {\n const answer = answerOf(splitToken(alternative.token).word);\n if (Option.isSome(answer)) {\n mass[answer.value] += Math.exp(alternative.logprob);\n }\n }\n return mass;\n};\n\nconst yesOf = (token: Token, answer: YesNo): number => {\n const mass = massOf(token);\n const total = Num.sum(mass.yes, mass.no);\n if (total > NONE) {\n return mass.yes / total;\n }\n return Bool.match(answer === \"yes\", { onTrue: () => CERTAIN, onFalse: () => NONE });\n};\n\nconst labelIndexOf = (text: string): Option.Option<number> =>\n captured(Str.match(LABEL_BEFORE)(text), \"index\").pipe(\n Option.map((index) => Num.subtract(Number(index), FIRST_LABEL)),\n );\n\nconst yesByLabel = (tokens: readonly Token[]): ReadonlyMap<number, number> => {\n const found = new Map<number, number>();\n let text = \"\";\n for (const token of tokens) {\n const { lead, word } = splitToken(token.token);\n const answer = answerOf(word);\n const index = labelIndexOf(`${text}${lead}`);\n if (Option.isSome(answer) && Option.isSome(index) && !found.has(index.value)) {\n found.set(index.value, yesOf(token, answer.value));\n }\n text = `${text}${token.token}`;\n }\n return found;\n};\n\nconst stateText = (state: WireRequest[\"state\"]): string => {\n if (typeof state === \"string\") {\n return state;\n }\n return toJson(state);\n};\n\nconst promptOf = (wire: WireRequest, questions: Asked): string => {\n const asked = pipe(\n questions,\n Arr.map(([, question], index) => `${labelOf(index)}: ${question.instructions}`),\n Arr.join(\"\\n\"),\n );\n return `${stateText(wire.state)}\\n\\nQuestions:\\n${asked}`;\n};\n\nconst templateOf = (model: string): Readonly<Record<string, unknown>> => {\n if (Str.startsWith(WORKERS_AI)(model)) {\n return { chat_template_kwargs: { enable_thinking: false, thinking: false } };\n }\n return {};\n};\n\nconst bodyOf = (wire: WireRequest, questions: Asked): Readonly<Record<string, unknown>> => ({\n model: wire.model,\n temperature: NONE,\n logprobs: true,\n top_logprobs: TOP_LOGPROBS,\n max_tokens: Num.sum(Num.multiply(questions.length, TOKENS_PER_ANSWER), SPARE_TOKENS),\n messages: [\n { role: \"system\", content: SYSTEM },\n { role: \"user\", content: promptOf(wire, questions) },\n ],\n ...templateOf(wire.model),\n});\n\nconst messageOfBody = (body: unknown): string =>\n Option.match(decodeErrorBody(body), {\n onNone: () => \"request failed\",\n onSome: ({ errors }) =>\n pipe(\n errors,\n Arr.map(({ message }) => message),\n Arr.join(\"; \"),\n ),\n });\n\nconst failureOf = (response: HttpClientResponse.HttpClientResponse): Effect.Effect<never, string> =>\n response.json.pipe(\n Effect.option,\n Effect.flatMap((body) =>\n Effect.fail(`http ${String(response.status)}: ${messageOfBody(Option.getOrUndefined(body))}`),\n ),\n );\n\nconst answersOf = (questions: Asked, tokens: readonly Token[]): Effect.Effect<Answers, string> => {\n const byLabel = yesByLabel(tokens);\n const answered = pipe(\n questions,\n Arr.flatMap(([id], index) =>\n pipe(\n Option.fromUndefinedOr(byLabel.get(index)),\n Option.map((noul) => [id, { type: \"noul\", noul }] as const),\n Option.toArray,\n ),\n ),\n );\n if (answered.length < questions.length) {\n return Effect.fail(\"the model did not answer every question with yes or no\");\n }\n return Effect.succeed(Rec.fromEntries(answered));\n};\n\nconst tokensOf = ({ body }: typeof ChatBody.Type): readonly Token[] => {\n const [{ logprobs }] = body.choices;\n return Option.fromNullishOr(logprobs).pipe(\n Option.flatMap(({ content }) => Option.fromNullishOr(content)),\n Option.getOrElse((): readonly Token[] => []),\n );\n};\n\nconst post = Effect.fn(\"post\")(function* post(\n endpoint: string,\n wire: WireRequest,\n { env }: Pick<DecideInput, \"env\">,\n) {\n const token = yield* Config.Redacted(envNameOf(env, \"CLOUDFLARE_API_TOKEN\"));\n const gateway = yield* Config.String(envNameOf(env, \"CLOUDFLARE_AI_GATEWAY_ID\")).pipe(\n Config.withDefault(DEFAULT_GATEWAY),\n );\n const app = yield* appContext;\n const body = bodyOf(wire, Rec.toEntries(wire.questions));\n const client = (yield* HttpClient.HttpClient).pipe(\n HttpClient.retryTransient({\n retryOn: \"response-only\",\n schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT),\n }),\n );\n return yield* HttpClientRequest.post(`${endpoint}${CHAT_PATH}`).pipe(\n HttpClientRequest.bearerToken(token),\n HttpClientRequest.setHeaders({\n \"cf-aig-gateway-id\": gateway,\n \"cf-aig-metadata\": toJson({ tool: TOOL, ...app }),\n }),\n HttpClientRequest.bodyJsonUnsafe(body),\n client.execute,\n );\n});\n\nconst sendChat = Effect.fn(\"sendChat\")(function* sendChat(\n endpoint: string,\n wire: WireRequest,\n input: Pick<DecideInput, \"env\">,\n) {\n const response = yield* post(endpoint, wire, input).pipe(\n Effect.mapError((error) => `network: ${error.message}`),\n );\n if (response.status >= FIRST_REDIRECT) {\n return yield* failureOf(response);\n }\n const chat = yield* HttpClientResponse.schemaJson(ChatBody)(response).pipe(\n Effect.mapError((error) => `invalid response: ${error.message}`),\n );\n const answers = yield* answersOf(Rec.toEntries(wire.questions), tokensOf(chat));\n return { model: chat.body.model ?? wire.model, answers } satisfies DecisionResponse;\n});\n\n/** @internal */\nexport { endpointOf, sendChat, yesByLabel };\n/** @internal */\nexport type { Token, YesNo };\n","import { endpointOf, sendChat } from \"./cloudflare-chat.ts\";\nimport { serveDecisions } from \"./serve-decisions.ts\";\nimport { mergeYesNo, yesNoRequestsFor } from \"./wire.ts\";\n\nserveDecisions({\n endpoint: endpointOf,\n wires: yesNoRequestsFor,\n combine: mergeYesNo,\n send: sendChat,\n});\n"],"mappings":";;;;;;;AAoBA,MAAM,OAAO;AACb,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,mBAAmB;AACzB,M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,OAAO,OAAO,OAAO,UAAU,KAAK,0BAA0B,CAAC,CAAC,CAAC,KAC/E,OAAO,YAAY,eAAe,CACpC;CACA,MAAM,MAAM,OAAO;CACnB,MAAM,OAAO,OAAO,MAAMA,OAAI,UAAU,KAAK,SAAS,CAAC;CACvD,MAAM,UAAU,OAAO,WAAW,WAAA,CAAY,KAC5C,WAAW,eAAe;EACxB,SAAS;EACT,UAAU,SAAS,YAAY,kBAAkB,cAAc;CACjE,CAAC,CACH;CACA,OAAO,OAAO,kBAAkB,KAAK,GAAG,WAAW,WAAW,CAAC,CAAC,KAC9D,kBAAkB,YAAY,KAAK,GACnC,kBAAkB,WAAW;EAC3B,qBAAqB;EACrB,mBAAmB,OAAO;GAAE,MAAM;GAAM,GAAG;EAAI,CAAC;CAClD,CAAC,GACD,kBAAkB,eAAe,IAAI,GACrC,OAAO,OACT;AACF,CAAC;AAED,MAAM,WAAW,OAAO,GAAG,UAAU,CAAC,CAAC,UAAU,SAC/C,UACA,MACA,OACA;CACA,MAAM,WAAW,OAAO,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,KAClD,OAAO,UAAU,UAAU,YAAY,MAAM,SAAS,CACxD;CACA,IAAI,SAAS,UAAU,gBACrB,OAAO,OAAO,UAAU,QAAQ;CAElC,MAAM,OAAO,OAAO,mBAAmB,WAAW,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,KACpE,OAAO,UAAU,UAAU,qBAAqB,MAAM,SAAS,CACjE;CACA,MAAM,UAAU,OAAO,UAAUA,OAAI,UAAU,KAAK,SAAS,GAAG,SAAS,IAAI,CAAC;CAC9E,OAAO;EAAE,OAAO,KAAK,KAAK,SAAS,KAAK;EAAO;CAAQ;AACzD,CAAC;;ACpRD,eAAe;CACb,UAAU;CACV,OAAO;CACP,SAAS;CACT,MAAM;AACR,CAAC"}
1
+ {"version":3,"file":"cloudflare-worker.mjs","names":["Arr","Num","Str","Bool","Rec"],"sources":["../src/cloudflare-chat.ts","../src/cloudflare-worker.ts"],"sourcesContent":["import {\n Array as Arr,\n Boolean as Bool,\n Config,\n Effect,\n Number as Num,\n Option,\n Record as Rec,\n Schedule,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\";\n\nimport { appContext } from \"./openrouter-app.ts\";\nimport { captured, envNameOf, toJson } from \"./runtime.ts\";\nimport type { Answers, DecideInput, DecisionResponse, Question } from \"./types.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst DEFAULT_API_URL = \"https://api.cloudflare.com/client/v4\";\nconst DEFAULT_GATEWAY = \"default\";\nconst CHAT_PATH = \"/ai/v1/chat/completions\";\nconst TRAILING_SLASHES = /\\/+$/u;\nconst WORKERS_AI = \"@cf/\";\nconst TOP_LOGPROBS = 10;\nconst TOKENS_PER_ANSWER = 8;\nconst SPARE_TOKENS = 16;\nconst FIRST_LABEL = 1;\nconst NONE = 0;\nconst CERTAIN = 1;\nconst FIRST_REDIRECT = 300;\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\nconst LEADING_JUNK = /^(?<lead>[\\s::*]*)(?<word>[\\s\\S]*)$/u;\nconst LABEL_BEFORE = /(?:^|\\n)[\\s*]*q(?<index>\\d+)[\\s*]*[::]\\s*$/u;\nconst ANSWER_WORD = /^(?<word>yes|no)[\\s.,!*]*$/iu;\n\nconst SYSTEM = Arr.join(\n [\n \"You answer yes-or-no questions about the material the user gives you.\",\n \"Answer every question on its own line in the form `q<number>: yes` or `q<number>: no`, in the order asked.\",\n \"Write nothing else.\",\n ],\n \" \",\n);\n\nconst TopLogprob = Schema.Struct({ token: Schema.String, logprob: Schema.Finite });\n\nconst TokenLogprob = Schema.Struct({\n token: Schema.String,\n logprob: Schema.Finite,\n top_logprobs: Schema.optional(Schema.Array(TopLogprob)),\n});\n\nconst Logprobs = Schema.Struct({ content: Schema.NullOr(Schema.Array(TokenLogprob)) });\n\nconst OptionalLogprobs = Schema.optional(Schema.NullOr(Logprobs));\n\nconst Choice = Schema.Struct({ logprobs: OptionalLogprobs });\n\nconst ChatResponse = Schema.Struct({\n model: Schema.optional(Schema.String),\n choices: Schema.NonEmptyArray(Choice),\n});\n\nconst ChatBody = Schema.Struct({ body: ChatResponse });\n\nconst ErrorBody = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ message: Schema.String })),\n});\n\nconst decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);\n\ntype Token = typeof TokenLogprob.Type;\n\ntype YesNo = \"yes\" | \"no\";\n\ntype Mass = Readonly<Record<YesNo, number>>;\n\ntype Asked = readonly (readonly [string, Question])[];\n\ninterface Split {\n readonly lead: string;\n readonly word: string;\n}\n\nconst labelOf = (index: number): string => `q${String(Num.sum(index, FIRST_LABEL))}`;\n\nconst accountUrl = ({ api, account }: Readonly<{ api: string; account: string }>): string =>\n `${Str.replace(TRAILING_SLASHES, \"\")(Str.trim(api))}/accounts/${Str.trim(account)}`;\n\nconst endpointOf = (env: DecideInput[\"env\"]): Config.Config<string> =>\n Config.all({\n api: Config.String(envNameOf(env, \"CLOUDFLARE_API_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_API_URL),\n ),\n account: Config.NonEmptyString(envNameOf(env, \"CLOUDFLARE_ACCOUNT_ID\")),\n }).pipe(Config.map(accountUrl));\n\nconst yesNoOf = (word: string): YesNo =>\n Bool.match(Str.toLowerCase(word) === \"yes\", { onTrue: () => \"yes\", onFalse: () => \"no\" });\n\nconst answerOf = (text: string): Option.Option<YesNo> =>\n captured(Str.match(ANSWER_WORD)(text), \"word\").pipe(Option.map(yesNoOf));\n\nconst splitToken = (token: string): Split => {\n const match = Str.match(LEADING_JUNK)(token);\n return {\n lead: Option.getOrElse(captured(match, \"lead\"), () => \"\"),\n word: Option.getOrElse(captured(match, \"word\"), () => token),\n };\n};\n\nconst massOf = (token: Token): Mass => {\n const mass = { yes: NONE, no: NONE };\n for (const alternative of token.top_logprobs ?? [token]) {\n const answer = answerOf(splitToken(alternative.token).word);\n if (Option.isSome(answer)) {\n mass[answer.value] += Math.exp(alternative.logprob);\n }\n }\n return mass;\n};\n\nconst yesOf = (token: Token, answer: YesNo): number => {\n const mass = massOf(token);\n const total = Num.sum(mass.yes, mass.no);\n if (total > NONE) {\n return mass.yes / total;\n }\n return Bool.match(answer === \"yes\", { onTrue: () => CERTAIN, onFalse: () => NONE });\n};\n\nconst labelIndexOf = (text: string): Option.Option<number> =>\n captured(Str.match(LABEL_BEFORE)(text), \"index\").pipe(\n Option.map((index) => Num.subtract(Number(index), FIRST_LABEL)),\n );\n\nconst yesByLabel = (tokens: readonly Token[]): ReadonlyMap<number, number> => {\n const found = new Map<number, number>();\n let text = \"\";\n for (const token of tokens) {\n const { lead, word } = splitToken(token.token);\n const answer = answerOf(word);\n const index = labelIndexOf(`${text}${lead}`);\n if (Option.isSome(answer) && Option.isSome(index) && !found.has(index.value)) {\n found.set(index.value, yesOf(token, answer.value));\n }\n text = `${text}${token.token}`;\n }\n return found;\n};\n\nconst stateText = (state: WireRequest[\"state\"]): string => {\n if (typeof state === \"string\") {\n return state;\n }\n return toJson(state);\n};\n\nconst promptOf = (wire: WireRequest, questions: Asked): string => {\n const asked = pipe(\n questions,\n Arr.map(([, question], index) => `${labelOf(index)}: ${question.instructions}`),\n Arr.join(\"\\n\"),\n );\n return `${stateText(wire.state)}\\n\\nQuestions:\\n${asked}`;\n};\n\nconst templateOf = (model: string): Readonly<Record<string, unknown>> => {\n if (Str.startsWith(WORKERS_AI)(model)) {\n return { chat_template_kwargs: { enable_thinking: false, thinking: false } };\n }\n return {};\n};\n\nconst bodyOf = (wire: WireRequest, questions: Asked): Readonly<Record<string, unknown>> => ({\n model: wire.model,\n temperature: NONE,\n logprobs: true,\n top_logprobs: TOP_LOGPROBS,\n max_tokens: Num.sum(Num.multiply(questions.length, TOKENS_PER_ANSWER), SPARE_TOKENS),\n messages: [\n { role: \"system\", content: SYSTEM },\n { role: \"user\", content: promptOf(wire, questions) },\n ],\n ...templateOf(wire.model),\n});\n\nconst messageOfBody = (body: unknown): string =>\n Option.match(decodeErrorBody(body), {\n onNone: () => \"request failed\",\n onSome: ({ errors }) =>\n pipe(\n errors,\n Arr.map(({ message }) => message),\n Arr.join(\"; \"),\n ),\n });\n\nconst failureOf = (response: HttpClientResponse.HttpClientResponse): Effect.Effect<never, string> =>\n response.json.pipe(\n Effect.option,\n Effect.flatMap((body) =>\n Effect.fail(`http ${String(response.status)}: ${messageOfBody(Option.getOrUndefined(body))}`),\n ),\n );\n\nconst answersOf = (questions: Asked, tokens: readonly Token[]): Effect.Effect<Answers, string> => {\n const byLabel = yesByLabel(tokens);\n const answered = pipe(\n questions,\n Arr.flatMap(([id], index) =>\n pipe(\n Option.fromUndefinedOr(byLabel.get(index)),\n Option.map((noul) => [id, { type: \"noul\", noul }] as const),\n Option.toArray,\n ),\n ),\n );\n if (answered.length < questions.length) {\n return Effect.fail(\"the model did not answer every question with yes or no\");\n }\n return Effect.succeed(Rec.fromEntries(answered));\n};\n\nconst tokensOf = ({ body }: typeof ChatBody.Type): readonly Token[] => {\n const [{ logprobs }] = body.choices;\n return Option.fromNullishOr(logprobs).pipe(\n Option.flatMap(({ content }) => Option.fromNullishOr(content)),\n Option.getOrElse((): readonly Token[] => []),\n );\n};\n\nconst post = Effect.fn(\"post\")(function* post(\n endpoint: string,\n wire: WireRequest,\n { env }: Pick<DecideInput, \"env\">,\n) {\n const token = yield* Config.Redacted(envNameOf(env, \"CLOUDFLARE_API_TOKEN\"));\n const gateway = yield* Config.String(envNameOf(env, \"CLOUDFLARE_AI_GATEWAY_ID\")).pipe(\n Config.withDefault(DEFAULT_GATEWAY),\n );\n const app = yield* appContext;\n const body = bodyOf(wire, Rec.toEntries(wire.questions));\n const client = (yield* HttpClient.HttpClient).pipe(\n HttpClient.retryTransient({\n retryOn: \"response-only\",\n schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT),\n }),\n );\n return yield* HttpClientRequest.post(`${endpoint}${CHAT_PATH}`).pipe(\n HttpClientRequest.bearerToken(token),\n HttpClientRequest.setHeaders({\n \"cf-aig-gateway-id\": gateway,\n \"cf-aig-metadata\": toJson({ tool: TOOL, ...app }),\n }),\n HttpClientRequest.bodyJsonUnsafe(body),\n client.execute,\n );\n});\n\nconst sendChat = Effect.fn(\"sendChat\")(function* sendChat(\n endpoint: string,\n wire: WireRequest,\n input: Pick<DecideInput, \"env\">,\n) {\n const response = yield* post(endpoint, wire, input).pipe(\n Effect.mapError((error) => `network: ${error.message}`),\n );\n if (response.status >= FIRST_REDIRECT) {\n return yield* failureOf(response);\n }\n const chat = yield* HttpClientResponse.schemaJson(ChatBody)(response).pipe(\n Effect.mapError((error) => `invalid response: ${error.message}`),\n );\n const answers = yield* answersOf(Rec.toEntries(wire.questions), tokensOf(chat));\n return { model: chat.body.model ?? wire.model, answers } satisfies DecisionResponse;\n});\n\n/** @internal */\nexport { endpointOf, sendChat, yesByLabel };\n/** @internal */\nexport type { Token, YesNo };\n","import { endpointOf, sendChat } from \"./cloudflare-chat.ts\";\nimport { serveDecisions } from \"./serve-decisions.ts\";\nimport { mergeYesNo, yesNoRequestFor } from \"./wire.ts\";\n\nserveDecisions({\n endpoint: endpointOf,\n wires: yesNoRequestFor,\n combine: mergeYesNo,\n send: sendChat,\n});\n"],"mappings":";;;;;;;AAoBA,MAAM,OAAO;AACb,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,mBAAmB;AACzB,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,cAAc;AAEpB,MAAM,SAASA,MAAI,KACjB;CACE;C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kB,cAAc;CACjE,CAAC,CACH;CACA,OAAO,OAAO,kBAAkB,KAAK,GAAG,WAAW,WAAW,CAAC,CAAC,KAC9D,kBAAkB,YAAY,KAAK,GACnC,kBAAkB,WAAW;EAC3B,qBAAqB;EACrB,mBAAmB,OAAO;GAAE,MAAM;GAAM,GAAG;EAAI,CAAC;CAClD,CAAC,GACD,kBAAkB,eAAe,IAAI,GACrC,OAAO,OACT;AACF,CAAC;AAED,MAAM,WAAW,OAAO,GAAG,UAAU,CAAC,CAAC,UAAU,SAC/C,UACA,MACA,OACA;CACA,MAAM,WAAW,OAAO,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,KAClD,OAAO,UAAU,UAAU,YAAY,MAAM,SAAS,CACxD;CACA,IAAI,SAAS,UAAU,gBACrB,OAAO,OAAO,UAAU,QAAQ;CAElC,MAAM,OAAO,OAAO,mBAAmB,WAAW,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,KACpE,OAAO,UAAU,UAAU,qBAAqB,MAAM,SAAS,CACjE;CACA,MAAM,UAAU,OAAO,UAAUA,OAAI,UAAU,KAAK,SAAS,GAAG,SAAS,IAAI,CAAC;CAC9E,OAAO;EAAE,OAAO,KAAK,KAAK,SAAS,KAAK;EAAO;CAAQ;AACzD,CAAC;;ACpRD,eAAe;CACb,UAAU;CACV,OAAO;CACP,SAAS;CACT,MAAM;AACR,CAAC"}
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { S as isReported, _ as resolveModel, a as messageOf, c as toJson, d as PREFIX, f as STRICT, g as optionsError, h as modelIdsOf, i as failsInCi, l as warnOnce, m as checked, n as envNameOf, o as nowMs, p as checkRules, r as envOf, s as runOrElse, u as ModelSpecSchema, v as resolveOptions } from "./runtime-CICpEidL.mjs";
2
- import { a as buildRequest, c as refAt, d as locates, f as locationCandidates, g as sourceLines, h as selectedLocation, i as yesNoRequestsFor, l as truncateSnippet, m as locationQuestion, o as locationRefOf, p as locationOfLine, r as wireRequestsFor, s as parseVerdicts, u as EVERY_LINE } from "./wire-BbVK3Q_K.mjs";
2
+ import { _ as sourceLines, a as yesNoRequestsFor, c as parseVerdicts, d as EVERY_LINE, f as locates, g as selectedLocation, h as locationQuestion, l as refAt, m as locationOfLine, o as buildRequest, p as locationCandidates, r as wireRequestsFor, s as locationRefOf, u as truncateSnippet } from "./wire-CRD1mSAo.mjs";
3
3
  import { Array, Boolean, Console, Effect, Function, Match, Option, Predicate, Record, Schema, String as String$1, Struct, pipe } from "effect";
4
4
  import { createSyncFn } from "synckit";
5
5
  // src/define.ts
@@ -1,7 +1,7 @@
1
1
  import { openRouterApp } from "./openrouter-app.mjs";
2
2
  import { n as envNameOf } from "./runtime-CICpEidL.mjs";
3
- import { t as serveDecisions } from "./serve-decisions-pOSYU_8a.mjs";
4
- import { r as wireRequestsFor, t as mergeResponses } from "./wire-BbVK3Q_K.mjs";
3
+ import { t as serveDecisions } from "./serve-decisions-cQpGj_Fq.mjs";
4
+ import { r as wireRequestsFor, t as mergeResponses } from "./wire-CRD1mSAo.mjs";
5
5
  import { Config, Effect, Option, Schedule, Schema, String as String$1 } from "effect";
6
6
  import { make } from "@effect/ai-openrouter/OpenRouterClient";
7
7
  import { HttpClient, HttpClientRequest } from "effect/http";
@@ -1,5 +1,5 @@
1
1
  import { a as messageOf, y as AnswerSchema } from "./runtime-CICpEidL.mjs";
2
- import { s as parseVerdicts } from "./wire-BbVK3Q_K.mjs";
2
+ import { c as parseVerdicts } from "./wire-CRD1mSAo.mjs";
3
3
  import { Array, Clock, Effect, FileSystem, Function, Layer, Option, Path, Schema, pipe } from "effect";
4
4
  import { runAsWorker } from "synckit";
5
5
  import { FetchHttpClient } from "effect/http";
@@ -109,4 +109,4 @@ const serveDecisions = (transport) => {
109
109
  };
110
110
  export { serveDecisions as t };
111
111
 
112
- //# sourceMappingURL=serve-decisions-pOSYU_8a.mjs.map
112
+ //# sourceMappingURL=serve-decisions-cQpGj_Fq.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve-decisions-pOSYU_8a.mjs","names":["Fn","fileSystem","path","Arr"],"sources":["../src/cache.ts","../src/services.ts","../src/serve-decisions.ts"],"sourcesContent":["import { Clock, Effect, FileSystem, Option, Path, Schema, Function as Fn } from \"effect\";\nimport { Digest } from \"effect/crypto\";\n\nimport { AnswerSchema } from \"./answer.ts\";\nimport { parseVerdicts } from \"./request.ts\";\nimport type { DecisionRequest, DecisionResponse } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst CACHE_VERSION = 7;\nconst 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\nconst 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\nconst 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\nconst 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\nconst 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\ntype CacheServices = Digest.Digest | FileSystem.FileSystem | Path.Path;\n\n/** @internal */\nexport { CACHE_DIR, cacheFile, isComplete, readCache, writeCache };\n/** @internal */\nexport type { CacheServices };\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\nconst 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\n/** @internal */\nexport { workerServices };\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 { cacheFile, isComplete, readCache, writeCache } from \"./cache.ts\";\nimport type { CacheServices } from \"./cache.ts\";\nimport type { AppServices } from \"./openrouter-app.ts\";\nimport { messageOf } from \"./runtime.ts\";\nimport { workerServices } from \"./services.ts\";\nimport type { DecideInput, DecideResult, DecisionRequest, DecisionResponse } from \"./types.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\ntype Services = AppServices | CacheServices | HttpClient.HttpClient;\n\ntype Inputs = Arr.NonEmptyReadonlyArray<DecideInput>;\n\ninterface 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\nconst serveDecisions = (transport: Transport): void => {\n runAsWorker((inputs: Inputs): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.runPromise(decideEach(transport, inputs)),\n );\n};\n\n/** @internal */\nexport { serveDecisions };\n/** @internal */\nexport type { Services, Transport };\n"],"mappings":";;;;;;;;;;;AAOA,MAAM,mBAAmB;AAEzB,MAAM,gBAAgB;AACtB,MAAM,YAAY;CAAC;CAAgB;CAAU;AAAwB;AAErE,MAAM,cAAc,UAClB,OAAO,oBAAoB,OAAO,eAAe,OAAO,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,OAAO,KAAK;AAE5F,MAAM,YAAY,OAAO,GAAG,WAAW,CAAC,CAAC,UAAU,UACjD,UACA,SACA;CACA,MAAM,SAAS,OAAO,OAAO;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,OAAO,OAAO,WAAW;EAAE,SAAS;EAAe;EAAU;CAAQ,CAAC;CAC5E,MAAM,UAAU,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI;CAC7C,MAAM,OAAO,OAAO,OAAO,UAAU,OAAO,QAAQ,OAAO;CAC3D,OAAO,KAAK,QAAQ,GAAG,WAAW,GAAG,KAAK,MAAM;AAClD,CAAC;AAED,MAAM,iBAAiB,OAAO,OAAO;CACnC,OAAO,OAAO;CACd,SAAS,OAAO,OAAO,OAA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C,CAAC,KACvB,OAAO,MAAM;CACX,YAAY,EAAE,UAAU,cAA4B;EAAE,IAAI;EAAM;EAAU;CAAO;CACjF,YAAY,WAAyB;EAAE,IAAI;EAAO,QAAQ,SAAS,KAAK;CAAE;AAC5E,CAAC,CACH;AAEF,MAAM,cACJ,WACA,WAEA,OAAO,IACL,KACE,QACAC,MAAI,KAAK,UAAU,UAAU,WAAW,KAAK,CAAC,CAChD,GACA,EAAE,aAAa,YAAY,CAC7B,CAAC,CAAC,KAAK,OAAO,QAAQ,cAAc,CAAC;AAEvC,MAAM,kBAAkB,cAA+B;CACrD,aAAa,WACX,OAAO,WAAW,WAAW,WAAW,MAAM,CAAC,CACjD;AACF"}
1
+ {"version":3,"file":"serve-decisions-cQpGj_Fq.mjs","names":["Fn","fileSystem","path","Arr"],"sources":["../src/cache.ts","../src/services.ts","../src/serve-decisions.ts"],"sourcesContent":["import { Clock, Effect, FileSystem, Option, Path, Schema, Function as Fn } from \"effect\";\nimport { Digest } from \"effect/crypto\";\n\nimport { AnswerSchema } from \"./answer.ts\";\nimport { parseVerdicts } from \"./request.ts\";\nimport type { DecisionRequest, DecisionResponse } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst CACHE_VERSION = 7;\nconst 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\nconst 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\nconst 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\nconst 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\nconst 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\ntype CacheServices = Digest.Digest | FileSystem.FileSystem | Path.Path;\n\n/** @internal */\nexport { CACHE_DIR, cacheFile, isComplete, readCache, writeCache };\n/** @internal */\nexport type { CacheServices };\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\nconst 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\n/** @internal */\nexport { workerServices };\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 { cacheFile, isComplete, readCache, writeCache } from \"./cache.ts\";\nimport type { CacheServices } from \"./cache.ts\";\nimport type { AppServices } from \"./openrouter-app.ts\";\nimport { messageOf } from \"./runtime.ts\";\nimport { workerServices } from \"./services.ts\";\nimport type { DecideInput, DecideResult, DecisionRequest, DecisionResponse } from \"./types.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\ntype Services = AppServices | CacheServices | HttpClient.HttpClient;\n\ntype Inputs = Arr.NonEmptyReadonlyArray<DecideInput>;\n\ninterface 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\nconst serveDecisions = (transport: Transport): void => {\n runAsWorker((inputs: Inputs): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.runPromise(decideEach(transport, inputs)),\n );\n};\n\n/** @internal */\nexport { serveDecisions };\n/** @internal */\nexport type { Services, Transport };\n"],"mappings":";;;;;;;;;;;AAOA,MAAM,mBAAmB;AAEzB,MAAM,gBAAgB;AACtB,MAAM,YAAY;CAAC;CAAgB;CAAU;AAAwB;AAErE,MAAM,cAAc,UAClB,OAAO,oBAAoB,OAAO,eAAe,OAAO,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,OAAO,KAAK;AAE5F,MA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;CACrD,MAAM,SAAS,OAAO,UAAU,MAAM,MAAM,OAAO;CACnD,OAAO,OAAO,oBAAoB,EAAE,QAAQ,OAAO,OAAO,MAAM,EAAE,CAAC;CACnE,IAAI,OAAO,OAAO,MAAM,GACtB,OAAO;EAAE,UAAU,OAAO;EAAO,QAAQ;CAAK;CAEhD,OAAO;EAAE,UAAU,OAAO,YAAY,WAAW;GAAE;GAAU;EAAK,GAAG,KAAK;EAAG,QAAQ;CAAM;AAC7F,CAAC;AAED,MAAM,YAAY,UAA2B;CAC3C,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,OAAO,UAAU,KAAK;AACxB;AAEA,MAAM,aACJ,WACA,UAEA,OAAO,WAAW,KAAK,CAAC,CAAC,KACvB,OAAO,MAAM;CACX,YAAY,EAAE,UAAU,cAA4B;EAAE,IAAI;EAAM;EAAU;CAAO;CACjF,YAAY,WAAyB;EAAE,IAAI;EAAO,QAAQ,SAAS,KAAK;CAAE;AAC5E,CAAC,CACH;AAEF,MAAM,cACJ,WACA,WAEA,OAAO,IACL,KACE,QACAC,MAAI,KAAK,UAAU,UAAU,WAAW,KAAK,CAAC,CAChD,GACA,EAAE,aAAa,YAAY,CAC7B,CAAC,CAAC,KAAK,OAAO,QAAQ,cAAc,CAAC;AAEvC,MAAM,kBAAkB,cAA+B;CACrD,aAAa,WACX,OAAO,WAAW,WAAW,WAAW,MAAM,CAAC,CACjD;AACF"}
@@ -231,6 +231,11 @@ const yesNoRequestsFor = (request) => {
231
231
  if (Array.isReadonlyArrayNonEmpty(wires)) return wires;
232
232
  return [request];
233
233
  };
234
+ const yesNoRequestFor = (request) => [{
235
+ model: request.model,
236
+ state: stateAsText(request.state),
237
+ questions: Record.fromEntries(pipe(Record.toEntries(request.questions), Array.flatMap((entry) => asYesNo(entry))))
238
+ }];
234
239
  const wireRequestsFor = (request) => {
235
240
  if (isRespan(request.model)) return yesNoRequestsFor(request);
236
241
  return [request];
@@ -241,6 +246,6 @@ const merging = (collapse) => (request, responses) => ({
241
246
  });
242
247
  const mergeResponses = Function.dual(DATA_FIRST_ARITY, merging(withChoices));
243
248
  const mergeYesNo = Function.dual(DATA_FIRST_ARITY, merging(collapseChoices));
244
- export { buildRequest as a, refAt as c, locates as d, locationCandidates as f, sourceLines as g, selectedLocation as h, yesNoRequestsFor as i, truncateSnippet as l, locationQuestion as m, mergeYesNo as n, locationRefOf as o, locationOfLine as p, wireRequestsFor as r, parseVerdicts as s, mergeResponses as t, EVERY_LINE as u };
249
+ export { sourceLines as _, yesNoRequestsFor as a, parseVerdicts as c, EVERY_LINE as d, locates as f, selectedLocation as g, locationQuestion as h, yesNoRequestFor as i, refAt as l, locationOfLine as m, mergeYesNo as n, buildRequest as o, locationCandidates as p, wireRequestsFor as r, locationRefOf as s, mergeResponses as t, truncateSnippet as u };
245
250
 
246
- //# sourceMappingURL=wire-BbVK3Q_K.mjs.map
251
+ //# sourceMappingURL=wire-CRD1mSAo.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"wire-BbVK3Q_K.mjs","names":["DATA_FIRST_ARITY","FIRST_LINE","Str","Num","Bool","Arr","Fn","Rec","DATA_FIRST_ARITY","Bool","Str","Num","Fn","Arr","Rec","choiceQuestionsOf","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","Num","Bool","Rec","Arr","Fn"],"sources":["../src/location.ts","../src/request.ts","../src/wire-choice.ts","../src/wire.ts"],"sourcesContent":["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\nconst sourceLines = (text: string): readonly string[] =>\n Str.split(text, /\\r\\n|[\\n\\r\\u2028\\u2029]/u);\n\ntype LocatedMatch = RequestMatch & {\n readonly rule: { readonly question: string; readonly location: RuleLocation };\n};\n\nconst locates = (match: RequestMatch): match is LocatedMatch =>\n Predicate.isNotUndefined(match.rule.location) && !match.truncated;\n\ninterface NumberedLine {\n readonly text: string;\n readonly line: number;\n}\n\nconst 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\nconst numberedLines = (snippet: string): readonly NumberedLine[] =>\n pipe(\n sourceLines(snippet),\n Arr.map((text, index) => ({ text, line: Num.sum(index, FIRST_LINE) })),\n );\n\nconst 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\nconst 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\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst 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\nconst 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\nconst 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\nexport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationOfLine,\n locationQuestion,\n numberedLines,\n selectedLocation,\n sourceLines,\n validChoice,\n};\nexport type { ChoiceCriteria, LocatedMatch, NumberedLine };\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\nconst refAt = (index: number): string => `s${String(index)}`;\n\nconst locationRefOf = (ref: string): string => `${ref}${LOCATION_SUFFIX}`;\n\nconst 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\nconst 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\nconst 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\nconst 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\nexport { buildRequest, locationRefOf, parseVerdicts, refAt, snippetRefOf, truncateSnippet };\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\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst RESPAN_MODELS = [\"respan/\"] as const;\nconst OPTION_SEPARATOR = \"__\";\nconst CERTAIN = 1;\nconst NO_SEVERITY = \"none\";\n\nconst isRespan = (model: string): boolean =>\n pipe(\n RESPAN_MODELS,\n Arr.some((prefix) => Str.startsWith(prefix)(model)),\n );\n\nconst 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\nconst isSeverityScale = (criteria: ChoiceCriteria): boolean =>\n pipe(Rec.keys(criteria), Arr.join(\",\")) === pipe(SEVERITY_ORDER, Arr.join(\",\"));\n\nconst levelsAboveNone = (criteria: ChoiceCriteria): 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\nconst 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\nconst 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\nexport { collapseChoices, isRespan, isSeverityScale, levelsAboveNone, optionIdOf, withChoices };\nexport type { ChoiceCriteria };\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 collapseChoices,\n isRespan,\n withChoices,\n isSeverityScale,\n levelsAboveNone,\n optionIdOf,\n} from \"./wire-choice.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\ntype State = DecisionRequest[\"state\"];\n\ninterface 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\nconst yesNoRequestsFor = (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => {\n const bySnippet = Arr.groupBy(Rec.toEntries(request.questions), ([id]) => snippetRefOf(id));\n const wires = pipe(\n Rec.values(bySnippet),\n Arr.map((questions): WireRequest => {\n const [[id]] = questions;\n return {\n model: request.model,\n state: stateAsText(stateOf(request.state, snippetRefOf(id))),\n questions: Rec.fromEntries(\n pipe(\n questions,\n Arr.flatMap((entry) => asYesNo(entry)),\n ),\n ),\n };\n }),\n );\n if (Arr.isReadonlyArrayNonEmpty(wires)) {\n return wires;\n }\n return [request];\n};\n\nconst wireRequestsFor = (request: DecisionRequest): 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\ninterface Merge {\n (\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): (request: DecisionRequest) => DecisionResponse;\n (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): DecisionResponse;\n}\n\nconst mergeResponses: Merge = Fn.dual(DATA_FIRST_ARITY, merging(withChoices));\n\nconst mergeYesNo: Merge = Fn.dual(DATA_FIRST_ARITY, merging(collapseChoices));\n\nexport { mergeResponses, mergeYesNo, wireRequestsFor, yesNoRequestsFor };\nexport type { Merge, WireRequest };\n"],"mappings":";;;AAgBA,MAAMA,qBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAMC,eAAa;AACnB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AAEvB,MAAM,eAAe,SACnBC,SAAI,MAAM,MAAM,0BAA0B;AAM5C,MAAM,WAAW,UACf,UAAU,eAAe,MAAM,KAAK,QAAQ,KAAK,CAAC,MAAM;AAO1D,MAAM,aA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H;CACA,IAAIA,MAAI,wBAAwB,KAAK,GACnC,OAAO;CAET,OAAO,CAAC,OAAO;AACjB;AAEA,MAAM,mBAAmB,YAAqE;CAC5F,IAAI,SAAS,QAAQ,KAAK,GACxB,OAAO,iBAAiB,OAAO;CAEjC,OAAO,CAAC,OAAO;AACjB;AAOA,MAAM,WACH,cAEC,SACA,eACsB;CACtB,GAAGA,MAAI,aAAa,SAAS;CAC7B,SAAS,SACP,SACA,KACE,WACAA,MAAI,SAAS,EAAE,cAAcD,OAAI,UAAU,OAAO,CAAC,GACnDA,OAAI,WACN,CACF;AACF;AAYF,MAAM,iBAAwBE,SAAG,KAAK,kBAAkB,QAAQ,WAAW,CAAC;AAE5E,MAAM,aAAoBA,SAAG,KAAK,kBAAkB,QAAQ,eAAe,CAAC"}
1
+ {"version":3,"file":"wire-CRD1mSAo.mjs","names":["DATA_FIRST_ARITY","FIRST_LINE","Str","Num","Bool","Arr","Fn","Rec","DATA_FIRST_ARITY","Bool","Str","Num","Fn","Arr","Rec","choiceQuestionsOf","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","Num","Bool","Rec","Arr","Fn"],"sources":["../src/location.ts","../src/request.ts","../src/wire-choice.ts","../src/wire.ts"],"sourcesContent":["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\nconst sourceLines = (text: string): readonly string[] =>\n Str.split(text, /\\r\\n|[\\n\\r\\u2028\\u2029]/u);\n\ntype LocatedMatch = RequestMatch & {\n readonly rule: { readonly question: string; readonly location: RuleLocation };\n};\n\nconst locates = (match: RequestMatch): match is LocatedMatch =>\n Predicate.isNotUndefined(match.rule.location) && !match.truncated;\n\ninterface NumberedLine {\n readonly text: string;\n readonly line: number;\n}\n\nconst 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\nconst numberedLines = (snippet: string): readonly NumberedLine[] =>\n pipe(\n sourceLines(snippet),\n Arr.map((text, index) => ({ text, line: Num.sum(index, FIRST_LINE) })),\n );\n\nconst 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\nconst 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\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst 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\nconst 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\nconst 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\nexport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationOfLine,\n locationQuestion,\n numberedLines,\n selectedLocation,\n sourceLines,\n validChoice,\n};\nexport type { ChoiceCriteria, LocatedMatch, NumberedLine };\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\nconst refAt = (index: number): string => `s${String(index)}`;\n\nconst locationRefOf = (ref: string): string => `${ref}${LOCATION_SUFFIX}`;\n\nconst 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\nconst 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\nconst 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\nconst 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\nexport { buildRequest, locationRefOf, parseVerdicts, refAt, snippetRefOf, truncateSnippet };\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\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst RESPAN_MODELS = [\"respan/\"] as const;\nconst OPTION_SEPARATOR = \"__\";\nconst CERTAIN = 1;\nconst NO_SEVERITY = \"none\";\n\nconst isRespan = (model: string): boolean =>\n pipe(\n RESPAN_MODELS,\n Arr.some((prefix) => Str.startsWith(prefix)(model)),\n );\n\nconst 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\nconst isSeverityScale = (criteria: ChoiceCriteria): boolean =>\n pipe(Rec.keys(criteria), Arr.join(\",\")) === pipe(SEVERITY_ORDER, Arr.join(\",\"));\n\nconst levelsAboveNone = (criteria: ChoiceCriteria): 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\nconst 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\nconst 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\nexport { collapseChoices, isRespan, isSeverityScale, levelsAboveNone, optionIdOf, withChoices };\nexport type { ChoiceCriteria };\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 collapseChoices,\n isRespan,\n withChoices,\n isSeverityScale,\n levelsAboveNone,\n optionIdOf,\n} from \"./wire-choice.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\ntype State = DecisionRequest[\"state\"];\n\ninterface 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\nconst yesNoRequestsFor = (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => {\n const bySnippet = Arr.groupBy(Rec.toEntries(request.questions), ([id]) => snippetRefOf(id));\n const wires = pipe(\n Rec.values(bySnippet),\n Arr.map((questions): WireRequest => {\n const [[id]] = questions;\n return {\n model: request.model,\n state: stateAsText(stateOf(request.state, snippetRefOf(id))),\n questions: Rec.fromEntries(\n pipe(\n questions,\n Arr.flatMap((entry) => asYesNo(entry)),\n ),\n ),\n };\n }),\n );\n if (Arr.isReadonlyArrayNonEmpty(wires)) {\n return wires;\n }\n return [request];\n};\n\nconst yesNoRequestFor = (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => [\n {\n model: request.model,\n state: stateAsText(request.state),\n questions: Rec.fromEntries(\n pipe(\n Rec.toEntries(request.questions),\n Arr.flatMap((entry) => asYesNo(entry)),\n ),\n ),\n },\n];\n\nconst wireRequestsFor = (request: DecisionRequest): 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\ninterface Merge {\n (\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): (request: DecisionRequest) => DecisionResponse;\n (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): DecisionResponse;\n}\n\nconst mergeResponses: Merge = Fn.dual(DATA_FIRST_ARITY, merging(withChoices));\n\nconst mergeYesNo: Merge = Fn.dual(DATA_FIRST_ARITY, merging(collapseChoices));\n\nexport { mergeResponses, mergeYesNo, wireRequestsFor, yesNoRequestFor, yesNoRequestsFor };\nexport type { Merge, WireRequest };\n"],"mappings":";;;AAgBA,MAAMA,qBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAMC,eAAa;AACnB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AAEvB,MAAM,eAAe,SACnBC,SAAI,MAAM,MAAM,0BAA0B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D,OAAI,YACb,KACE,WACAC,MAAI,SAAS,UAAU,QAAQ,KAAK,CAAC,CACvC,CACF;EACF;CACF,CAAC,CACH;CACA,IAAIA,MAAI,wBAAwB,KAAK,GACnC,OAAO;CAET,OAAO,CAAC,OAAO;AACjB;AAEA,MAAM,mBAAmB,YAAqE,CAC5F;CACE,OAAO,QAAQ;CACf,OAAO,YAAY,QAAQ,KAAK;CAChC,WAAWD,OAAI,YACb,KACEA,OAAI,UAAU,QAAQ,SAAS,GAC/BC,MAAI,SAAS,UAAU,QAAQ,KAAK,CAAC,CACvC,CACF;AACF,CACF;AAEA,MAAM,mBAAmB,YAAqE;CAC5F,IAAI,SAAS,QAAQ,KAAK,GACxB,OAAO,iBAAiB,OAAO;CAEjC,OAAO,CAAC,OAAO;AACjB;AAOA,MAAM,WACH,cAEC,SACA,eACsB;CACtB,GAAGA,MAAI,aAAa,SAAS;CAC7B,SAAS,SACP,SACA,KACE,WACAA,MAAI,SAAS,EAAE,cAAcD,OAAI,UAAU,OAAO,CAAC,GACnDA,OAAI,WACN,CACF;AACF;AAYF,MAAM,iBAAwBE,SAAG,KAAK,kBAAkB,QAAQ,WAAW,CAAC;AAE5E,MAAM,aAAoBA,SAAG,KAAK,kBAAkB,QAAQ,eAAe,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@r_masseater/oxlint-plugin-decision",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Oxlint JS plugin that lints code with plain-English rules answered by models on Cloudflare AI Gateway or decision models on OpenRouter.",
5
5
  "keywords": [
6
6
  "ai-gateway",