Skip to content
Myr

binding.test.ts

This file

Path

packages/drafting/test/binding.test.ts

280 lines · 8.3 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e

lines 1–35why, one step back
1import { describe, expect, expectTypeOf, it } from "@effect/vitest";
2import { Brand } from "@repo/brand";3import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";4import { Effect, Schema } from "effect";56import { DraftedAsk, DraftFailed } from "../src/drafted.ts";7import type { DraftInput } from "../src/drafted.ts";8import { Drafter } from "../src/drafter.ts";9import { DrafterWorkersAi } from "../src/drafter/binding.ts";10import type { AiLike, ChatInputs } from "../src/drafter/binding.ts";1112const model = "@cf/test/drafting-model";1314const drafted: DraftedAsk = {15 id: AskId.make("iso-week"),16 kind: "fix",17 rationale: "The parser has no week dates.",18 territory: [RepoPath.make("src/parse.ts")],19 test: {20 path: RepoPath.make("test/asks/iso-week.test.ts"),21 source: 'it("parses", () => expect(parse("2026-W01")).toBe(1));\n',22 },23 want: "An ISO week date parses to the Monday of that week.",24};2526const encoded = Schema.encodeSync(DraftedAsk)(drafted);2728const json = JSON.stringify(encoded);2930const input: DraftInput = {31 attempt: 1,32 context: {33 at: LandedSha.make("4".repeat(40)),34 files: [],35 policy: "Ask kinds: fix (redThenGreen).",

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 36why, one step back
36 project: ProjectName.make("oscabriel/datekit"),

Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e

lines 37–110why, one step back
37 },
38 want: "Parse ISO week dates.",39};4041interface Call {42 readonly inputs: ChatInputs;43 readonly model: string;44}4546type Outcome = { readonly reply: object } | { readonly thrown: Error };4748const fakeAi = (outcome: Outcome) => {49 const calls: Call[] = [];5051 const ai: AiLike = {52 run: (name, inputs) => {53 calls.push({ inputs, model: name });5455 return "reply" in outcome56 ? Promise.resolve(outcome.reply)57 : Promise.reject(outcome.thrown);58 },59 };6061 return { ai, calls };62};6364const draftWith = (outcome: Outcome) =>65 Drafter.use(({ draft }) => draft(input)).pipe(66 Effect.provide(DrafterWorkersAi(fakeAi(outcome).ai, model))67 );6869const chat = (content: string): Outcome => ({70 reply: { choices: [{ message: { content } }] },71});7273const thrown = (message: string): Outcome => ({ thrown: new Error(message) });7475const failure = (reason: DraftFailed["reason"]) => new DraftFailed({ reason });7677const callOf = Effect.gen(function* () {78 const { ai, calls } = fakeAi(chat(json));7980 yield* Drafter.use(({ draft }) => draft(input)).pipe(81 Effect.provide(DrafterWorkersAi(ai, model))82 );8384 return yield* Effect.fromNullishOr(calls[0]);85});8687describe("the Workers AI drafter", () => {88 it("takes the generated Ai binding as its AiLike", () => {89 expectTypeOf<Ai>().toExtend<AiLike>();90 });9192 it.effect(93 "asks the given model, once, with the system and user prompts",94 () =>95 Effect.gen(function* () {96 const call = yield* callOf;9798 expect(call.model).toBe(model);99 expect(call.inputs.messages.map(({ role }) => role)).toStrictEqual([100 "system",101 "user",102 ]);103 expect(call.inputs).toMatchObject({104 max_completion_tokens: 12_000,105 temperature: 0.2,106 });107 expect(call.inputs.seed).toBe((yield* callOf).inputs.seed);108 })109 );110

Merge build/1007oscabrielbefore adoption77fa97a

lines 111–154why, one step back
111 it.effect(
112 "gives each model its own room: the fallbacks more tokens and low reasoning, anything else the defaults",113 () =>114 Effect.gen(function* () {115 const asked = yield* Effect.forEach(116 [117 "@cf/moonshotai/kimi-k2.7-code",118 "@cf/zai-org/glm-5.3",119 "@cf/openai/gpt-oss-120b",120 model,121 ],122 (name) =>123 Effect.gen(function* () {124 const { ai, calls } = fakeAi(chat(json));125126 yield* Drafter.use(({ draft }) => draft(input)).pipe(127 Effect.provide(DrafterWorkersAi(ai, name))128 );129130 const call = yield* Effect.fromNullishOr(calls[0]);131132 return {133 max: call.inputs.max_completion_tokens,134 model: call.model,135 reasoning: Object.hasOwn(call.inputs, "reasoning_effort")136 ? call.inputs.reasoning_effort137 : "none sent",138 };139 })140 );141142 expect(asked).toStrictEqual([143 {144 max: 12_000,145 model: "@cf/moonshotai/kimi-k2.7-code",146 reasoning: "none sent",147 },148 { max: 32_000, model: "@cf/zai-org/glm-5.3", reasoning: "low" },149 { max: 32_000, model: "@cf/openai/gpt-oss-120b", reasoning: "low" },150 { max: 12_000, model, reasoning: "none sent" },151 ]);152 })153 );154

Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e

lines 155–197why, one step back
155 it.effect("asks for JSON Schema with no null and no Infinity in it", () =>
156 Effect.gen(function* () {157 const { response_format: format } = (yield* callOf).inputs;158 const text = JSON.stringify(format.json_schema);159160 expect(format.type).toBe("json_schema");161 expect(text).toContain('"want"');162 expect(text).not.toContain("null");163 expect(text).not.toContain("Infinity");164 })165 );166167 it.effect(168 "decodes a valid reply, a fenced reply and a `response` reply",169 () =>170 Effect.gen(function* () {171 expect(yield* draftWith(chat(json))).toStrictEqual(drafted);172 expect(173 yield* draftWith(chat(`\`\`\`json\n${json}\n\`\`\`\n`))174 ).toStrictEqual(drafted);175 expect(yield* draftWith({ reply: { response: json } })).toStrictEqual(176 drafted177 );178 })179 );180181 it.effect(182 "gives a reply off the schema as `schema`, and no JSON as `unparseable`",183 () =>184 Effect.gen(function* () {185 expect(yield* Effect.flip(draftWith(chat('{"id": 3}')))).toStrictEqual(186 failure("schema")187 );188 expect(yield* Effect.flip(draftWith(chat("not json")))).toStrictEqual(189 failure("unparseable")190 );191 expect(192 yield* Effect.flip(draftWith({ reply: { choices: [] } }))193 ).toStrictEqual(failure("unparseable"));194 })195 );196197 it.effect(

Take one sentence where a draft's list is asked for, so kimi's drafts decodeoscabrielbefore adoptionecc2107

lines 198–200why, one step back
198 "takes one sentence where the schema asks for a list of them, as a list of one",
199 () =>200 Effect.gen(function* () {

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 201–202why, one step back
201 // Seen live: kimi-k2.7-code answered every attempt with `context` and
202 // `outOfScope` as strings, whatever the JSON Schema said.

Take one sentence where a draft's list is asked for, so kimi's drafts decodeoscabrielbefore adoptionecc2107

lines 203–222why, one step back
203 const reply = JSON.stringify({
204 ...encoded,205 context: "An ordinal date is YYYY-DDD.",206 outOfScope: "Changing parse.",207 });208209 expect(yield* draftWith(chat(reply))).toStrictEqual({210 ...drafted,211 context: ["An ordinal date is YYYY-DDD."],212 outOfScope: ["Changing parse."],213 });214 expect(215 yield* Effect.flip(216 draftWith(chat(JSON.stringify({ ...encoded, context: "" })))217 )218 ).toStrictEqual(failure("schema"));219 })220 );221222 it.effect(

Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e

lines 223–280why, one step back
223 "refuses a test path in the config folder or off the tree as `schema`, so model text never lands as config",
224 () =>225 Effect.gen(function* () {226 for (const path of [227 `${Brand.configDir}/project.ts`,228 `${Brand.configDir}/asks/other.ask.ts`,229 "../outside.test.ts",230 "/etc/passwd",231 "test/./asks/iso-week.test.ts",232 ]) {233 const reply = JSON.stringify({234 ...encoded,235 test: { path, source: "export default 1;\n" },236 });237238 expect(yield* Effect.flip(draftWith(chat(reply)))).toStrictEqual(239 failure("schema")240 );241 }242243 const offTerritory = JSON.stringify({244 ...encoded,245 territory: ["src/../../secrets.ts"],246 });247248 expect(yield* Effect.flip(draftWith(chat(offTerritory)))).toStrictEqual(249 failure("schema")250 );251 })252 );253254 it.effect(255 "names a 429 `rate-limited`, a JSON-mode miss `schema`, the rest `model-error`",256 () =>257 Effect.gen(function* () {258 expect(259 yield* Effect.flip(260 draftWith(thrown("AiError: 429: Too Many Requests"))261 )262 ).toStrictEqual(failure("rate-limited"));263 expect(264 yield* Effect.flip(265 draftWith(266 thrown("3040: Capacity temporarily exceeded, please try again.")267 )268 )269 ).toStrictEqual(failure("rate-limited"));270 expect(271 yield* Effect.flip(272 draftWith(thrown("AiError: JSON Mode couldn't be met"))273 )274 ).toStrictEqual(failure("schema"));275 expect(276 yield* Effect.flip(draftWith(thrown("5007: No such model")))277 ).toStrictEqual(failure("model-error"));278 })279 );280});