@r_masseater/oxlint-plugin-decision 0.3.0 → 0.4.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.
@@ -1,28 +1,32 @@
1
- import { M as AnswerSchema, _ as messageOf, l as parseVerdicts, m as envNameOf, n as wireRequestsFor, t as mergeResponses } from "./wire-XOgoBBuu.mjs";
2
- import { Array, Config, Effect, FileSystem, Layer, Option, Path, Redacted, Schema, String as String$1, pipe } from "effect";
1
+ import { M as AnswerSchema, a as parseVerdicts, h as envNameOf, n as wireRequestsFor, t as mergeResponses, v as messageOf } from "./wire-XbLEwd0i.mjs";
2
+ import { openRouterApp } from "./openrouter-app.mjs";
3
+ import { Array, Clock, Config, Effect, FileSystem, Function, Layer, Option, Path, Schedule, Schema, String as String$1, pipe } from "effect";
3
4
  import { runAsWorker } from "synckit";
4
- import { OpenRouterError } from "@openrouter/sdk/models/errors";
5
5
  import { Digest } from "effect/crypto";
6
- import { OpenRouter } from "@openrouter/sdk";
7
- import { HTTPClient } from "@openrouter/sdk/lib/http.js";
8
- import { NodeCrypto, NodeServices } from "@effect/platform-node";
9
- import { FetchHttpClient } from "effect/http";
6
+ import { make } from "@effect/ai-openrouter/OpenRouterClient";
7
+ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
8
+ import { layerDigest } from "@effect/platform-node-shared/NodeCrypto";
9
+ import { layer } from "@effect/platform-node-shared/NodeFileSystem";
10
+ import { layer as layer$1 } from "@effect/platform-node-shared/NodePath";
10
11
  import { OtlpSerialization, OtlpTracer } from "effect/observability";
11
12
  // src/cache.ts
13
+ const DATA_FIRST_ARITY = 2;
12
14
  const CACHE_VERSION = 7;
13
15
  const CACHE_DIR = [
14
16
  "node_modules",
15
17
  ".cache",
16
18
  "oxlint-plugin-decision"
17
19
  ];
20
+ const encodeJson = (value) => Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(value).pipe(Effect.orDie);
18
21
  const cacheFile = Effect.fn("cacheFile")(function* cacheFile(endpoint, request) {
19
22
  const digest = yield* Digest.Digest;
20
23
  const path = yield* Path.Path;
21
- const payload = new TextEncoder().encode(JSON.stringify({
24
+ const json = yield* encodeJson({
22
25
  version: CACHE_VERSION,
23
26
  endpoint,
24
27
  request
25
- }));
28
+ });
29
+ const payload = new TextEncoder().encode(json);
26
30
  const hash = yield* digest.digestHex(Digest.sha256, payload);
27
31
  return path.resolve(...CACHE_DIR, `${hash}.json`);
28
32
  });
@@ -31,144 +35,61 @@ const CachedResponse = Schema.Struct({
31
35
  answers: Schema.Record(Schema.String, AnswerSchema)
32
36
  });
33
37
  const decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedResponse));
34
- const isComplete = (response, request) => Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(Option.getOrElse(() => false));
38
+ const isComplete = Function.dual(DATA_FIRST_ARITY, (response, request) => Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(Option.getOrElse(() => false)));
35
39
  const readCache = Effect.fn("readCache")(function* readCache(file, request) {
36
40
  return (yield* (yield* FileSystem.FileSystem).readFileString(file).pipe(Effect.option)).pipe(Option.flatMap((raw) => decodeCached(raw)), Option.filter((response) => isComplete(response, request)));
37
41
  });
38
42
  const writeCache = Effect.fn("writeCache")(function* writeCache(file, response) {
39
43
  const fs = yield* FileSystem.FileSystem;
40
44
  const path = yield* Path.Path;
41
- const temp = `${file}.tmp-${String(Date.now())}`;
45
+ const now = yield* Clock.currentTimeMillis;
46
+ const temp = `${file}.tmp-${String(now)}`;
47
+ const json = yield* encodeJson(response);
42
48
  yield* fs.makeDirectory(path.dirname(file), { recursive: true });
43
- yield* fs.writeFileString(temp, JSON.stringify(response));
49
+ yield* fs.writeFileString(temp, json);
44
50
  yield* fs.rename(temp, file);
45
51
  });
46
- // src/client.ts
52
+ // src/decisions.ts
47
53
  const TOOL = "oxlint-plugin-decision";
48
- const GITHUB = "https://github.com";
49
- const SELF = "masseater/lint-kit";
50
- const GIT_SUFFIX = /\.git\/?$/u;
51
- const SEPARATORS = /[/:]/u;
52
- const SLUG_PARTS = 2;
53
- const GITDIR = /^gitdir:\s*(?<dir>.+)$/mu;
54
- const ORIGIN_URL = /\[remote "origin"\][^[]*?\burl\s*=\s*(?<url>\S+)/u;
55
- const hiddenApp = () => new HTTPClient().addHook("beforeRequest", (request) => {
56
- request.headers.set("X-OpenRouter-App-Visibility", "hidden");
57
- });
58
- const isSet = (name) => Config.option(Config.NonEmptyString(name)).pipe(Effect.map(Option.isSome), Effect.orElseSucceed(() => false));
59
- const contextOf = Effect.gen(function* contextOf() {
60
- if (yield* isSet("GITHUB_ACTIONS")) return "github-actions";
61
- if (yield* isSet("CLAUDE_CODE_REMOTE")) return "claude-code-cloud";
62
- if (yield* isSet("CLAUDECODE")) return "claude-code";
63
- return "local";
64
- });
65
- const slugOf = (url) => {
66
- const parts = url.trim().replace(GIT_SUFFIX, "").split(SEPARATORS).filter((part) => String$1.isNonEmpty(part));
67
- if (parts.length < SLUG_PARTS) return Option.none();
68
- return Option.some(Array.takeRight(parts, SLUG_PARTS).join("/"));
69
- };
70
- const captured = (match, name) => match.pipe(Option.flatMap((found) => Option.fromNullishOr(found.groups)), Option.flatMap((groups) => Option.fromNullishOr(groups[name])));
71
- const linkedGitDir = Effect.fn("linkedGitDir")(function* linkedGitDir(dir, dotGit) {
72
- const fs = yield* FileSystem.FileSystem;
73
- const path = yield* Path.Path;
74
- const text = yield* fs.readFileString(dotGit);
75
- return captured(String$1.match(GITDIR)(text), "dir").pipe(Option.map((found) => path.resolve(dir, found.trim())));
76
- });
77
- const gitDirAt = Effect.fn("gitDirAt")(function* gitDirAt(dir) {
78
- const fs = yield* FileSystem.FileSystem;
79
- const dotGit = (yield* Path.Path).join(dir, ".git");
80
- const info = yield* fs.stat(dotGit).pipe(Effect.option);
81
- if (Option.isNone(info)) return Option.none();
82
- if (info.value.type === "Directory") return Option.some(dotGit);
83
- return yield* linkedGitDir(dir, dotGit);
84
- });
85
- const gitDirFrom = (dir) => Effect.gen(function* walk() {
86
- const path = yield* Path.Path;
87
- const here = yield* gitDirAt(dir);
88
- const parent = path.dirname(dir);
89
- if (Option.isSome(here) || parent === dir) return here;
90
- return yield* gitDirFrom(parent);
91
- });
92
- const commonDirOf = Effect.fn("commonDirOf")(function* commonDirOf(gitDir) {
93
- const fs = yield* FileSystem.FileSystem;
94
- const path = yield* Path.Path;
95
- const common = yield* fs.readFileString(path.join(gitDir, "commondir")).pipe(Effect.option);
96
- return Option.match(common, {
97
- onNone: () => gitDir,
98
- onSome: (relative) => path.resolve(gitDir, relative.trim())
99
- });
100
- });
101
- const remoteSlug = Effect.gen(function* remoteSlug() {
102
- const fs = yield* FileSystem.FileSystem;
103
- const path = yield* Path.Path;
104
- const gitDir = yield* gitDirFrom(path.resolve("."));
105
- if (Option.isNone(gitDir)) return Option.none();
106
- const config = yield* fs.readFileString(path.join(yield* commonDirOf(gitDir.value), "config"));
107
- return captured(String$1.match(ORIGIN_URL)(config), "url").pipe(Option.flatMap(slugOf));
108
- }).pipe(Effect.orElseSucceed(() => Option.none()));
109
- const repoOf = Effect.gen(function* repoOf() {
110
- const fromActions = yield* Config.option(Config.NonEmptyString("GITHUB_REPOSITORY")).pipe(Effect.orElseSucceed(() => Option.none()));
111
- if (Option.isSome(fromActions)) return fromActions;
112
- return yield* remoteSlug;
54
+ const API_PATH = "/api/v1";
55
+ const RETRY_INITIAL_MS = 10;
56
+ const RETRY_EXPONENT = 2;
57
+ const attribution = openRouterApp(TOOL).pipe(Effect.cached, Effect.runSync);
58
+ const ErrorBody = Schema.Struct({ error: Schema.Struct({ message: Schema.String }) });
59
+ const decodeErrorBody = Schema.decodeOption(Schema.fromJsonString(ErrorBody));
60
+ const serverMessageOf = (body, fallback) => Option.fromUndefinedOr(body).pipe(Option.flatMap(decodeErrorBody), Option.match({
61
+ onNone: () => fallback,
62
+ onSome: ({ error }) => error.message
63
+ }));
64
+ const reasonFor = ({ _tag, message, http }) => Option.fromUndefinedOr(http).pipe(Option.flatMap(({ response, body }) => Option.map(Option.fromUndefinedOr(response), ({ status }) => `http ${String(status)}: ${serverMessageOf(body, _tag)}`)), Option.getOrElse(() => `network: ${message}`));
65
+ const send = Effect.fn("send")(function* send(endpoint, decisionsRequest, { env }) {
66
+ const apiKey = yield* Config.Redacted(envNameOf(env, "OPENROUTER_API_KEY"));
67
+ const headers = yield* attribution;
68
+ const [body] = yield* (yield* make({
69
+ apiKey,
70
+ apiUrl: `${endpoint}${API_PATH}`,
71
+ transformClient: (http) => http.pipe(HttpClient.mapRequest(HttpClientRequest.setHeaders(headers)), HttpClient.retryTransient({
72
+ retryOn: "response-only",
73
+ schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT)
74
+ }))
75
+ })).createDecisions(decisionsRequest).pipe(Effect.mapError(({ reason }) => reasonFor(reason)));
76
+ return body;
113
77
  });
114
- const attribution = Effect.gen(function* attribution() {
115
- const context = yield* contextOf;
116
- const repo = yield* repoOf;
117
- const slug = Option.getOrElse(repo, () => SELF);
118
- return {
119
- httpReferer: `${GITHUB}/${slug}/${TOOL}/${context}`,
120
- appTitle: `${Option.getOrElse(repo, () => "unknown")} ${context} ${TOOL}`,
121
- httpClient: hiddenApp()
122
- };
123
- }).pipe(Effect.cached, Effect.runSync);
124
- const clientFor = (apiKey) => attribution.pipe(Effect.map((app) => new OpenRouter({
125
- apiKey,
126
- ...app
127
- })));
128
78
  // src/services.ts
129
79
  const tracing = OtlpTracer.layerFromConfig({ resource: { serviceName: "oxlint-plugin-decision" } }).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));
130
80
  const workerServices = [
131
- NodeServices.layer,
132
- NodeCrypto.layerDigest,
81
+ layer,
82
+ layer$1,
83
+ layerDigest,
84
+ FetchHttpClient.layer,
133
85
  tracing
134
86
  ];
135
87
  // src/openrouter-worker.ts
136
- const RETRY_INITIAL_MS = 10;
137
- const RETRY_EXPONENT = 2;
138
88
  const DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
139
89
  const API_SUFFIX = /\/api\/v1\/*$|\/+$/u;
140
- const reasonFor = (error) => {
141
- if (error instanceof OpenRouterError) return `http ${String(error.statusCode)}: ${error.message}`;
142
- return `network: ${messageOf(error)}`;
143
- };
144
- const serverUrlOf = (env) => Config.String(envNameOf(env, "OPENROUTER_BASE_URL")).pipe(Config.withDefault(DEFAULT_BASE_URL), Config.map((url) => url.trim().replace(API_SUFFIX, "")));
145
- const send = Effect.fn("send")(function* send(endpoint, decisionsRequest, { timeoutMs, env }) {
146
- const apiKey = yield* Config.Redacted(envNameOf(env, "OPENROUTER_API_KEY"));
147
- const client = yield* clientFor(Redacted.value(apiKey));
148
- return yield* Effect.tryPromise({
149
- try: (signal) => client.alpha.decisions.create({ decisionsRequest }, {
150
- serverURL: endpoint,
151
- retries: {
152
- strategy: "backoff",
153
- backoff: {
154
- initialInterval: RETRY_INITIAL_MS,
155
- maxInterval: timeoutMs,
156
- exponent: RETRY_EXPONENT,
157
- maxElapsedTime: timeoutMs
158
- },
159
- retryConnectionErrors: false
160
- },
161
- retryCodes: ["429", "5XX"],
162
- signal
163
- }),
164
- catch: reasonFor
165
- });
166
- });
90
+ const serverUrlOf = (env) => Config.String(envNameOf(env, "OPENROUTER_BASE_URL")).pipe(Config.withDefault(DEFAULT_BASE_URL), Config.map((url) => String$1.replace(API_SUFFIX, "")(String$1.trim(url))));
167
91
  const ask = Effect.fn("ask")(function* ask(endpoint, { request, timeoutMs, env }) {
168
- const responses = yield* Effect.forEach(wireRequestsFor(request), (wire) => send(endpoint, wire, {
169
- timeoutMs,
170
- env
171
- }), { concurrency: "unbounded" }).pipe(Effect.timeoutOrElse({
92
+ const responses = yield* Effect.forEach(wireRequestsFor(request), (wire) => send(endpoint, wire, { env }), { concurrency: "unbounded" }).pipe(Effect.timeoutOrElse({
172
93
  duration: timeoutMs,
173
94
  orElse: () => Effect.fail("timeout")
174
95
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"openrouter-worker.mjs","names":["Str","Arr","Arr"],"sources":["../src/cache.ts","../src/client.ts","../src/services.ts","../src/openrouter-worker.ts"],"sourcesContent":["import { Effect, FileSystem, Option, Path, Schema } 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 CACHE_VERSION = 7;\nconst CACHE_DIR = [\"node_modules\", \".cache\", \"oxlint-plugin-decision\"] as const;\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 payload = new TextEncoder().encode(\n JSON.stringify({ version: CACHE_VERSION, endpoint, request }),\n );\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 = (response: DecisionResponse, request: DecisionRequest): boolean =>\n Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(\n Option.getOrElse(() => false),\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 temp = `${file}.tmp-${String(Date.now())}`;\n yield* fs.makeDirectory(path.dirname(file), { recursive: true });\n yield* fs.writeFileString(temp, JSON.stringify(response));\n yield* fs.rename(temp, file);\n});\n\ntype CacheServices = Digest.Digest | FileSystem.FileSystem | Path.Path;\n\nexport { cacheFile, isComplete, readCache, writeCache };\nexport type { CacheServices };\n","import { OpenRouter } from \"@openrouter/sdk\";\nimport { HTTPClient } from \"@openrouter/sdk/lib/http.js\";\nimport { Array as Arr, Config, Effect, FileSystem, Option, Path, String as Str } from \"effect\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst GITHUB = \"https://github.com\";\nconst SELF = \"masseater/lint-kit\";\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 hiddenApp = (): HTTPClient =>\n new HTTPClient().addHook(\"beforeRequest\", (request) => {\n request.headers.set(\"X-OpenRouter-App-Visibility\", \"hidden\");\n });\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 = url\n .trim()\n .replace(GIT_SUFFIX, \"\")\n .split(SEPARATORS)\n .filter((part) => Str.isNonEmpty(part));\n if (parts.length < SLUG_PARTS) {\n return Option.none();\n }\n return Option.some(Arr.takeRight(parts, SLUG_PARTS).join(\"/\"));\n};\n\nconst captured = (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\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, found.trim())),\n );\n});\n\ntype ClientServices = 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 = (dir: string): Effect.Effect<Option.Option<string>, unknown, ClientServices> =>\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, relative.trim()),\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 config = yield* fs.readFileString(path.join(yield* commonDirOf(gitDir.value), \"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\nconst attribution = Effect.gen(function* attribution() {\n const context = yield* contextOf;\n const repo = yield* repoOf;\n const slug = Option.getOrElse(repo, () => SELF);\n return {\n httpReferer: `${GITHUB}/${slug}/${TOOL}/${context}`,\n appTitle: `${Option.getOrElse(repo, () => \"unknown\")} ${context} ${TOOL}`,\n httpClient: hiddenApp(),\n };\n}).pipe(Effect.cached, Effect.runSync);\n\nconst clientFor = (apiKey: string): Effect.Effect<OpenRouter, never, ClientServices> =>\n attribution.pipe(Effect.map((app) => new OpenRouter({ apiKey, ...app })));\n\nexport { clientFor };\nexport type { ClientServices };\n","import { NodeCrypto, NodeServices } from \"@effect/platform-node\";\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: [typeof NodeServices.layer, typeof NodeCrypto.layerDigest, typeof tracing] = [\n NodeServices.layer,\n NodeCrypto.layerDigest,\n tracing,\n];\n\nexport { workerServices };\n","import { OpenRouterError } from \"@openrouter/sdk/models/errors\";\nimport { Array as Arr, Config, Effect, Option, Redacted, pipe } from \"effect\";\nimport { runAsWorker } from \"synckit\";\n\nimport { cacheFile, isComplete, readCache, writeCache } from \"./cache.ts\";\nimport type { CacheServices } from \"./cache.ts\";\nimport { clientFor } from \"./client.ts\";\nimport type { ClientServices } from \"./client.ts\";\nimport { envNameOf, messageOf } from \"./runtime.ts\";\nimport { workerServices } from \"./services.ts\";\nimport type { DecideInput, DecideResult } from \"./types.ts\";\nimport { mergeResponses, wireRequestsFor } from \"./wire.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\nconst DEFAULT_BASE_URL = \"https://openrouter.ai/api/v1\";\nconst API_SUFFIX = /\\/api\\/v1\\/*$|\\/+$/u;\n\nconst reasonFor = (error: unknown): string => {\n if (error instanceof OpenRouterError) {\n return `http ${String(error.statusCode)}: ${error.message}`;\n }\n return `network: ${messageOf(error)}`;\n};\n\nconst serverUrlOf = (env: Readonly<Record<string, string>>): Config.Config<string> =>\n Config.String(envNameOf(env, \"OPENROUTER_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_BASE_URL),\n Config.map((url) => url.trim().replace(API_SUFFIX, \"\")),\n );\n\nconst send = Effect.fn(\"send\")(function* send(\n endpoint: string,\n decisionsRequest: WireRequest,\n { timeoutMs, env }: Pick<DecideInput, \"timeoutMs\" | \"env\">,\n) {\n const apiKey = yield* Config.Redacted(envNameOf(env, \"OPENROUTER_API_KEY\"));\n const client = yield* clientFor(Redacted.value(apiKey));\n return yield* Effect.tryPromise({\n try: (signal) =>\n client.alpha.decisions.create(\n { decisionsRequest },\n {\n serverURL: endpoint,\n retries: {\n strategy: \"backoff\",\n backoff: {\n initialInterval: RETRY_INITIAL_MS,\n maxInterval: timeoutMs,\n exponent: RETRY_EXPONENT,\n maxElapsedTime: timeoutMs,\n },\n retryConnectionErrors: false,\n },\n retryCodes: [\"429\", \"5XX\"],\n signal,\n },\n ),\n catch: reasonFor,\n });\n});\n\nconst ask = Effect.fn(\"ask\")(function* ask(\n endpoint: string,\n { request, timeoutMs, env }: DecideInput,\n) {\n const responses = yield* Effect.forEach(\n wireRequestsFor(request),\n (wire) => send(endpoint, wire, { timeoutMs, env }),\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(\"timeout\"),\n }),\n );\n return mergeResponses(request, responses);\n});\n\nconst askAndStore = Effect.fn(\"askAndStore\")(function* askAndStore(\n endpoint: string,\n file: string,\n input: DecideInput,\n) {\n const response = yield* ask(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(input: DecideInput) {\n yield* Effect.annotateCurrentSpan({ model: input.request.model });\n const endpoint = yield* serverUrlOf(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(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 input: DecideInput,\n): Effect.Effect<DecideResult, never, ClientServices | CacheServices> =>\n decide(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 inputs: Arr.NonEmptyReadonlyArray<DecideInput>,\n): Effect.Effect<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.all(\n pipe(\n inputs,\n Arr.map((input) => decideOne(input)),\n ),\n { concurrency: \"unbounded\" },\n ).pipe(Effect.provide(workerServices));\n\nconst run = (\n inputs: Arr.NonEmptyReadonlyArray<DecideInput>,\n): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> => Effect.runPromise(decideEach(inputs));\n\nrunAsWorker(run);\n"],"mappings":";;;;;;;;;;;AAOA,MAAM,gBAAgB;AACtB,MAAM,YAAY;CAAC;CAAgB;CAAU;AAAwB;AAErE,MAAM,YAAY,OAAO,GAAG,WAAW,CAAC,CAAC,UAAU,UACjD,UACA,SACA;CACA,MAAM,SAAS,OAAO,OAAO;CAC7B,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QAAQ,cAAc,CAAC;AAEvC,MAAM,OACJ,WACqD,OAAO,WAAW,WAAW,MAAM,CAAC;AAE3F,YAAY,GAAG"}
1
+ {"version":3,"file":"openrouter-worker.mjs","names":["Fn","makeOpenRouter","fileSystem","path","Str","Arr"],"sources":["../src/cache.ts","../src/decisions.ts","../src/services.ts","../src/openrouter-worker.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 { make as makeOpenRouter } from \"@effect/ai-openrouter/OpenRouterClient\";\nimport { Config, Effect, Option, Schedule, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/http\";\n\nimport { openRouterApp } from \"./openrouter-app.ts\";\nimport { envNameOf } from \"./runtime.ts\";\nimport type { DecideInput } from \"./types.ts\";\nimport type { WireRequest } from \"./wire.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\nconst 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\n/** @internal */\nexport { send };\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, Config, Effect, Option, pipe, String as Str } 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 { send } from \"./decisions.ts\";\nimport type { AppServices } from \"./openrouter-app.ts\";\nimport { envNameOf, messageOf } from \"./runtime.ts\";\nimport { workerServices } from \"./services.ts\";\nimport type { DecideInput, DecideResult } from \"./types.ts\";\nimport { mergeResponses, wireRequestsFor } from \"./wire.ts\";\n\nconst DEFAULT_BASE_URL = \"https://openrouter.ai/api/v1\";\nconst API_SUFFIX = /\\/api\\/v1\\/*$|\\/+$/u;\n\nconst serverUrlOf = (env: Readonly<Record<string, string>>): Config.Config<string> =>\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\nconst ask = Effect.fn(\"ask\")(function* ask(\n endpoint: string,\n { request, timeoutMs, env }: DecideInput,\n) {\n const responses = yield* Effect.forEach(\n wireRequestsFor(request),\n (wire) => send(endpoint, wire, { env }),\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(\"timeout\"),\n }),\n );\n return mergeResponses(request, responses);\n});\n\nconst askAndStore = Effect.fn(\"askAndStore\")(function* askAndStore(\n endpoint: string,\n file: string,\n input: DecideInput,\n) {\n const response = yield* ask(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(input: DecideInput) {\n yield* Effect.annotateCurrentSpan({ model: input.request.model });\n const endpoint = yield* serverUrlOf(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(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 input: DecideInput,\n): Effect.Effect<DecideResult, never, AppServices | CacheServices | HttpClient.HttpClient> =>\n decide(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 inputs: Arr.NonEmptyReadonlyArray<DecideInput>,\n): Effect.Effect<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.all(\n pipe(\n inputs,\n Arr.map((input) => decideOne(input)),\n ),\n { concurrency: \"unbounded\" },\n ).pipe(Effect.provide(workerServices));\n\nconst run = (\n inputs: Arr.NonEmptyReadonlyArray<DecideInput>,\n): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> => Effect.runPromise(decideEach(inputs));\n\nrunAsWorker(run);\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;CA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