@r_masseater/oxlint-plugin-decision 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -3
- package/dist/{src-CknkhDKf.mjs → app-UakaWKAT.mjs} +69 -209
- package/dist/app-UakaWKAT.mjs.map +1 -0
- package/dist/cloudflare-worker.mjs +5 -182
- package/dist/cloudflare-worker.mjs.map +1 -1
- package/dist/decision-B7hahWHz.mjs +561 -0
- package/dist/decision-B7hahWHz.mjs.map +1 -0
- package/dist/{presets-CxYinkkJ.mjs → define-presets-yflVt8vT.mjs} +197 -17
- package/dist/define-presets-yflVt8vT.mjs.map +1 -0
- package/dist/{index-DiH-hZUS.d.mts → index-C0Twu0w7.d.mts} +26 -33
- package/dist/index-HOwrGbIA.d.mts +89 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/preset-plugin-ClpEFUN5.mjs +10 -0
- package/dist/preset-plugin-ClpEFUN5.mjs.map +1 -0
- package/dist/presets/ai-slop.d.mts +3 -13
- package/dist/presets/ai-slop.mjs +3 -183
- package/dist/presets/ai-slop.mjs.map +1 -1
- package/dist/presets/index.d.mts +2 -78
- package/dist/presets/index.mjs +1 -1
- package/dist/presets/recommended.d.mts +1 -1
- package/dist/presets/recommended.mjs +3 -2
- package/dist/presets/recommended.mjs.map +1 -1
- package/dist/presets/review-only.d.mts +1 -1
- package/dist/presets/review-only.mjs +3 -2
- package/dist/presets/review-only.mjs.map +1 -1
- package/dist/presets/strict.d.mts +1 -1
- package/dist/presets/strict.mjs +3 -2
- package/dist/presets/strict.mjs.map +1 -1
- package/dist/serve-decisions-DYGwLMft.mjs +287 -0
- package/dist/serve-decisions-DYGwLMft.mjs.map +1 -0
- package/dist/typesafe-worker.mjs +11 -0
- package/dist/typesafe-worker.mjs.map +1 -0
- package/package.json +7 -12
- package/skills/write-decision-rules/SKILL.md +18 -17
- package/skills/write-decision-rules/references/tuning.md +1 -3
- package/dist/openrouter-app.d.mts +0 -15
- package/dist/openrouter-app.mjs +0 -89
- package/dist/openrouter-app.mjs.map +0 -1
- package/dist/openrouter-worker.mjs +0 -46
- package/dist/openrouter-worker.mjs.map +0 -1
- package/dist/presets-CxYinkkJ.mjs.map +0 -1
- package/dist/runtime-CICpEidL.mjs +0 -271
- package/dist/runtime-CICpEidL.mjs.map +0 -1
- package/dist/select-bvQylrUt.mjs +0 -12
- package/dist/select-bvQylrUt.mjs.map +0 -1
- package/dist/serve-decisions-BM0bUWWe.mjs +0 -119
- package/dist/serve-decisions-BM0bUWWe.mjs.map +0 -1
- package/dist/src-CknkhDKf.mjs.map +0 -1
- package/dist/wire-CRD1mSAo.mjs +0 -251
- package/dist/wire-CRD1mSAo.mjs.map +0 -1
- package/skills/write-decision-rules/references/providers.md +0 -55
- /package/dist/{openrouter-worker.d.mts → typesafe-worker.d.mts} +0 -0
|
@@ -1,187 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { i as yesNoRequestFor, n as mergeYesNo } from "./wire-CRD1mSAo.mjs";
|
|
5
|
-
import { Array, Boolean, Config, Effect, Number as Number$1, Option, Record, Schedule, Schema, String as String$1, pipe } from "effect";
|
|
6
|
-
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
|
|
7
|
-
// src/cloudflare-chat.ts
|
|
8
|
-
const TOOL = "oxlint-plugin-decision";
|
|
9
|
-
const DEFAULT_API_URL = "https://api.cloudflare.com/client/v4";
|
|
10
|
-
const DEFAULT_GATEWAY = "default";
|
|
11
|
-
const CHAT_PATH = "/ai/v1/chat/completions";
|
|
12
|
-
const TRAILING_SLASHES = /\/+$/u;
|
|
13
|
-
const WORKERS_AI = "@cf/";
|
|
14
|
-
const TOP_LOGPROBS = 10;
|
|
15
|
-
const TOKENS_PER_ANSWER = 8;
|
|
16
|
-
const SPARE_TOKENS = 16;
|
|
17
|
-
const FIRST_LABEL = 1;
|
|
18
|
-
const NONE = 0;
|
|
19
|
-
const CERTAIN = 1;
|
|
20
|
-
const FIRST_REDIRECT = 300;
|
|
21
|
-
const RETRY_INITIAL_MS = 10;
|
|
22
|
-
const RETRY_EXPONENT = 2;
|
|
23
|
-
const LEADING_JUNK = /^(?<lead>[\s::*]*)(?<word>[\s\S]*)$/u;
|
|
24
|
-
const LABEL_BEFORE = /(?:^|\n)[\s*]*q(?<index>\d+)[\s*]*[::]\s*$/u;
|
|
25
|
-
const ANSWER_WORD = /^(?<word>yes|no)[\s.,!*]*$/iu;
|
|
26
|
-
const SYSTEM = Array.join([
|
|
27
|
-
"You answer yes-or-no questions about the material the user gives you.",
|
|
28
|
-
"Answer every question on its own line in the form `q<number>: yes` or `q<number>: no`, in the order asked.",
|
|
29
|
-
"Write nothing else."
|
|
30
|
-
], " ");
|
|
31
|
-
const TopLogprob = Schema.Struct({
|
|
32
|
-
token: Schema.String,
|
|
33
|
-
logprob: Schema.Finite
|
|
34
|
-
});
|
|
35
|
-
const TokenLogprob = Schema.Struct({
|
|
36
|
-
token: Schema.String,
|
|
37
|
-
logprob: Schema.Finite,
|
|
38
|
-
top_logprobs: Schema.optional(Schema.Array(TopLogprob))
|
|
39
|
-
});
|
|
40
|
-
const Logprobs = Schema.Struct({ content: Schema.NullOr(Schema.Array(TokenLogprob)) });
|
|
41
|
-
const OptionalLogprobs = Schema.optional(Schema.NullOr(Logprobs));
|
|
42
|
-
const Choice = Schema.Struct({ logprobs: OptionalLogprobs });
|
|
43
|
-
const ChatResponse = Schema.Struct({
|
|
44
|
-
model: Schema.optional(Schema.String),
|
|
45
|
-
choices: Schema.NonEmptyArray(Choice)
|
|
46
|
-
});
|
|
47
|
-
const ChatBody = Schema.Struct({ body: ChatResponse });
|
|
48
|
-
const ErrorBody = Schema.Struct({ errors: Schema.NonEmptyArray(Schema.Struct({ message: Schema.String })) });
|
|
49
|
-
const decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);
|
|
50
|
-
const labelOf = (index) => `q${String(Number$1.sum(index, FIRST_LABEL))}`;
|
|
51
|
-
const accountUrl = ({ api, account }) => `${String$1.replace(TRAILING_SLASHES, "")(String$1.trim(api))}/accounts/${String$1.trim(account)}`;
|
|
52
|
-
/** @internal */
|
|
53
|
-
const endpointOf = (env) => Config.all({
|
|
54
|
-
api: Config.String(envNameOf(env, "CLOUDFLARE_API_BASE_URL")).pipe(Config.withDefault(DEFAULT_API_URL)),
|
|
55
|
-
account: Config.NonEmptyString(envNameOf(env, "CLOUDFLARE_ACCOUNT_ID"))
|
|
56
|
-
}).pipe(Config.map(accountUrl));
|
|
57
|
-
const yesNoOf = (word) => Boolean.match(String$1.toLowerCase(word) === "yes", {
|
|
58
|
-
onTrue: () => "yes",
|
|
59
|
-
onFalse: () => "no"
|
|
60
|
-
});
|
|
61
|
-
const answerOf = (text) => captured(String$1.match(ANSWER_WORD)(text), "word").pipe(Option.map(yesNoOf));
|
|
62
|
-
const splitToken = (token) => {
|
|
63
|
-
const match = String$1.match(LEADING_JUNK)(token);
|
|
64
|
-
return {
|
|
65
|
-
lead: Option.getOrElse(captured(match, "lead"), () => ""),
|
|
66
|
-
word: Option.getOrElse(captured(match, "word"), () => token)
|
|
67
|
-
};
|
|
68
|
-
};
|
|
69
|
-
const massOf = (token) => {
|
|
70
|
-
const mass = {
|
|
71
|
-
yes: NONE,
|
|
72
|
-
no: NONE
|
|
73
|
-
};
|
|
74
|
-
for (const alternative of token.top_logprobs ?? [token]) {
|
|
75
|
-
const answer = answerOf(splitToken(alternative.token).word);
|
|
76
|
-
if (Option.isSome(answer)) mass[answer.value] += Math.exp(alternative.logprob);
|
|
77
|
-
}
|
|
78
|
-
return mass;
|
|
79
|
-
};
|
|
80
|
-
const yesOf = (token, answer) => {
|
|
81
|
-
const mass = massOf(token);
|
|
82
|
-
const total = Number$1.sum(mass.yes, mass.no);
|
|
83
|
-
if (total > NONE) return mass.yes / total;
|
|
84
|
-
return Boolean.match(answer === "yes", {
|
|
85
|
-
onTrue: () => CERTAIN,
|
|
86
|
-
onFalse: () => NONE
|
|
87
|
-
});
|
|
88
|
-
};
|
|
89
|
-
const labelIndexOf = (text) => captured(String$1.match(LABEL_BEFORE)(text), "index").pipe(Option.map((index) => Number$1.subtract(Number(index), FIRST_LABEL)));
|
|
90
|
-
/** @internal */
|
|
91
|
-
const yesByLabel = (tokens) => {
|
|
92
|
-
const found = /* @__PURE__ */ new Map();
|
|
93
|
-
let text = "";
|
|
94
|
-
for (const token of tokens) {
|
|
95
|
-
const { lead, word } = splitToken(token.token);
|
|
96
|
-
const answer = answerOf(word);
|
|
97
|
-
const index = labelIndexOf(`${text}${lead}`);
|
|
98
|
-
if (Option.isSome(answer) && Option.isSome(index) && !found.has(index.value)) found.set(index.value, yesOf(token, answer.value));
|
|
99
|
-
text = `${text}${token.token}`;
|
|
100
|
-
}
|
|
101
|
-
return found;
|
|
102
|
-
};
|
|
103
|
-
const stateText = (state) => {
|
|
104
|
-
if (typeof state === "string") return state;
|
|
105
|
-
return toJson(state);
|
|
106
|
-
};
|
|
107
|
-
const promptOf = (wire, questions) => {
|
|
108
|
-
const asked = pipe(questions, Array.map(([, question], index) => `${labelOf(index)}: ${question.instructions}`), Array.join("\n"));
|
|
109
|
-
return `${stateText(wire.state)}\n\nQuestions:\n${asked}`;
|
|
110
|
-
};
|
|
111
|
-
const templateOf = (model) => {
|
|
112
|
-
if (String$1.startsWith(WORKERS_AI)(model)) return { chat_template_kwargs: {
|
|
113
|
-
enable_thinking: false,
|
|
114
|
-
thinking: false
|
|
115
|
-
} };
|
|
116
|
-
return {};
|
|
117
|
-
};
|
|
118
|
-
const bodyOf = (wire, questions) => ({
|
|
119
|
-
model: wire.model,
|
|
120
|
-
temperature: NONE,
|
|
121
|
-
logprobs: true,
|
|
122
|
-
top_logprobs: TOP_LOGPROBS,
|
|
123
|
-
max_tokens: Number$1.sum(Number$1.multiply(questions.length, TOKENS_PER_ANSWER), SPARE_TOKENS),
|
|
124
|
-
messages: [{
|
|
125
|
-
role: "system",
|
|
126
|
-
content: SYSTEM
|
|
127
|
-
}, {
|
|
128
|
-
role: "user",
|
|
129
|
-
content: promptOf(wire, questions)
|
|
130
|
-
}],
|
|
131
|
-
...templateOf(wire.model)
|
|
132
|
-
});
|
|
133
|
-
const messageOfBody = (body) => Option.match(decodeErrorBody(body), {
|
|
134
|
-
onNone: () => "request failed",
|
|
135
|
-
onSome: ({ errors }) => pipe(errors, Array.map(({ message }) => message), Array.join("; "))
|
|
136
|
-
});
|
|
137
|
-
const failureOf = (response) => response.json.pipe(Effect.option, Effect.flatMap((body) => Effect.fail(`http ${String(response.status)}: ${messageOfBody(Option.getOrUndefined(body))}`)));
|
|
138
|
-
const answersOf = (questions, tokens) => {
|
|
139
|
-
const byLabel = yesByLabel(tokens);
|
|
140
|
-
const answered = pipe(questions, Array.flatMap(([id], index) => pipe(Option.fromUndefinedOr(byLabel.get(index)), Option.map((noul) => [id, {
|
|
141
|
-
type: "noul",
|
|
142
|
-
noul
|
|
143
|
-
}]), Option.toArray)));
|
|
144
|
-
if (answered.length < questions.length) return Effect.fail("the model did not answer every question with yes or no");
|
|
145
|
-
return Effect.succeed(Record.fromEntries(answered));
|
|
146
|
-
};
|
|
147
|
-
const tokensOf = ({ body }) => {
|
|
148
|
-
const [{ logprobs }] = body.choices;
|
|
149
|
-
return Option.fromNullishOr(logprobs).pipe(Option.flatMap(({ content }) => Option.fromNullishOr(content)), Option.getOrElse(() => []));
|
|
150
|
-
};
|
|
151
|
-
const post = Effect.fn("post")(function* post(endpoint, wire, { env }) {
|
|
152
|
-
const token = yield* Config.Redacted(envNameOf(env, "CLOUDFLARE_API_TOKEN"));
|
|
153
|
-
const gateway = yield* Config.String(envNameOf(env, "CLOUDFLARE_AI_GATEWAY_ID")).pipe(Config.withDefault(DEFAULT_GATEWAY));
|
|
154
|
-
const app = yield* appContext;
|
|
155
|
-
const body = bodyOf(wire, Record.toEntries(wire.questions));
|
|
156
|
-
const client = (yield* HttpClient.HttpClient).pipe(HttpClient.retryTransient({
|
|
157
|
-
retryOn: "response-only",
|
|
158
|
-
schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT)
|
|
159
|
-
}));
|
|
160
|
-
return yield* HttpClientRequest.post(`${endpoint}${CHAT_PATH}`).pipe(HttpClientRequest.bearerToken(token), HttpClientRequest.setHeaders({
|
|
161
|
-
"cf-aig-gateway-id": gateway,
|
|
162
|
-
"cf-aig-metadata": toJson({
|
|
163
|
-
tool: TOOL,
|
|
164
|
-
...app
|
|
165
|
-
})
|
|
166
|
-
}), HttpClientRequest.bodyJsonUnsafe(body), client.execute);
|
|
167
|
-
});
|
|
168
|
-
/** @internal */
|
|
169
|
-
const sendChat = Effect.fn("sendChat")(function* sendChat(endpoint, wire, input) {
|
|
170
|
-
const response = yield* post(endpoint, wire, input).pipe(Effect.mapError((error) => `network: ${error.message}`));
|
|
171
|
-
if (response.status >= FIRST_REDIRECT) return yield* failureOf(response);
|
|
172
|
-
const chat = yield* HttpClientResponse.schemaJson(ChatBody)(response).pipe(Effect.mapError((error) => `invalid response: ${error.message}`));
|
|
173
|
-
const answers = yield* answersOf(Record.toEntries(wire.questions), tokensOf(chat));
|
|
174
|
-
return {
|
|
175
|
-
model: chat.body.model ?? wire.model,
|
|
176
|
-
answers
|
|
177
|
-
};
|
|
178
|
-
});
|
|
179
|
-
// src/cloudflare-worker.ts
|
|
1
|
+
import { r as snippetRequestsFor } from "./decision-B7hahWHz.mjs";
|
|
2
|
+
import { a as sendWorkersAi, i as endpointOf, t as serveDecisions } from "./serve-decisions-DYGwLMft.mjs";
|
|
3
|
+
// src/app/cloudflare-worker.ts
|
|
180
4
|
serveDecisions({
|
|
181
5
|
endpoint: endpointOf,
|
|
182
|
-
wires:
|
|
183
|
-
|
|
184
|
-
send: sendChat
|
|
6
|
+
wires: snippetRequestsFor,
|
|
7
|
+
send: sendWorkersAi
|
|
185
8
|
});
|
|
186
9
|
export {};
|
|
187
10
|
|
|
@@ -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\n/** @internal */\nexport type Token = typeof TokenLogprob.Type;\n\n/** @internal */\nexport type 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\n/** @internal */\nexport const endpointOf = (env: DecideInput[\"env\"]): Config.Config<string> =>\n Config.all({\n api: Config.String(envNameOf(env, \"CLOUDFLARE_API_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_API_URL),\n ),\n account: Config.NonEmptyString(envNameOf(env, \"CLOUDFLARE_ACCOUNT_ID\")),\n }).pipe(Config.map(accountUrl));\n\nconst 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\n/** @internal */\nexport const 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\n/** @internal */\nexport const 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","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,M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AAU,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;;AAGD,MAAa,WAAW,OAAO,GAAG,UAAU,CAAC,CAAC,UAAU,SACtD,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;;ACzRD,eAAe;CACb,UAAU;CACV,OAAO;CACP,SAAS;CACT,MAAM;AACR,CAAC"}
|
|
1
|
+
{"version":3,"file":"cloudflare-worker.mjs","names":[],"sources":["../src/app/cloudflare-worker.ts"],"sourcesContent":["import { snippetRequestsFor } from \"#/entities/decision/index.ts\";\nimport { endpointOf, sendWorkersAi, serveDecisions } from \"#/features/serve-decisions/index.ts\";\n\nserveDecisions({\n endpoint: endpointOf,\n wires: snippetRequestsFor,\n send: sendWorkersAi,\n});\n"],"mappings":";;;AAGA,eAAe;CACb,UAAU;CACV,OAAO;CACP,MAAM;AACR,CAAC"}
|