- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/scripts/autosettle/workers-ai/index.ts?format=json
134 linesautosettle 100%Last change autosettle in version 198, 3 versions changed it
1// A Worker that asks a Workers AI text model how a held push's collision should
2// be settled (#19). JSON mode limits the answer to abso's settle choices, a
3// confidence and a one-line reason: the model picks, it never writes code.
4//
5// cd scripts/autosettle/workers-ai && npx wrangler dev --port 8845 (the AI binding always runs on Cloudflare)
6// POST / with {"hold": <Hold>, "model"?: "<@cf/... model>"}
8interface Env {
9 readonly AI: { run(model: string, input: unknown): Promise<unknown> };
10}
12interface Hold {
13 readonly file: string;
14 readonly base: readonly string[];
15 readonly yours: readonly string[];
16 readonly theirs: readonly string[];
17 readonly before: readonly string[];
18 readonly after: readonly string[];
19 readonly yourMessage?: string;
20 readonly yourAgent?: string;
21 readonly theirMessage?: string;
22 readonly theirAgent?: string;
23 readonly issue?: string;
24}
26const PICKS = ["yours", "theirs", "both", "agent"] as const;
27const DEFAULT_MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast";
29const SYSTEM = `You settle merge collisions in a version control system for coding agents.
30Two agents changed the same lines of one file. Both started from BEFORE. YOURS is what the held agent wrote, for the reason in its push message; THEIRS was pushed first, for the reason in its push message.
31Pick exactly one:
32- "yours": keep YOURS only. YOURS already does what THEIRS meant, or THEIRS is wrong or out of date.
33- "theirs": keep THEIRS only. THEIRS already does what YOURS meant, or YOURS is wrong or out of date.
34- "both": keep both unchanged, YOURS then THEIRS. They add separate things that work side by side, with nothing duplicated or contradictory.
35- "agent": none of those is correct. The sides change the same thing in different ways (such as two different values for one setting), or keeping both would duplicate or contradict, so a correct result needs a hand edit.
36Give "confidence" from 0 to 1: how likely your pick is the correct settle. Give "reason" as one plain sentence. Do not write code.`;
38const block = (lines: readonly string[]) => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
40function prompt(h: Hold): string {
41 return [
42 `FILE: ${h.file}`,
43 `YOUR PUSH (${h.yourAgent ?? "you"}): ${h.yourMessage ?? "(no message)"}`,
44 `THEIR PUSH (${h.theirAgent ?? "the other agent"}): ${h.theirMessage ?? "(no message)"}`,
45 ...(h.issue ? [`ISSUE: ${h.issue}`] : []),
46 "",
47 "LINES ABOVE:",
48 block(h.before),
49 "",
50 "BEFORE (what both started from):",
51 block(h.base),
52 "",
53 "YOURS:",
54 block(h.yours),
55 "",
56 "THEIRS:",
57 block(h.theirs),
58 "",
59 "LINES BELOW:",
60 block(h.after),
61 ].join("\n");
62}
64const SCHEMA = {
65 type: "object",
66 properties: {
67 pick: { type: "string", enum: PICKS },
68 confidence: { type: "number", minimum: 0, maximum: 1 },
69 reason: { type: "string" },
70 },
71 required: ["pick", "confidence", "reason"],
72};
74export default {
75 async fetch(request: Request, env: Env): Promise<Response> {
76 if (request.method !== "POST") return new Response("POST a hold", { status: 405 });
77 // POST /system-one: a System One request (state and typed questions) for a Clef decision model, passed through.
78 if (new URL(request.url).pathname === "/system-one") {
79 const body = (await request.json()) as { model?: string };
80 const id = body.model === "clef-flash" ? "@cf/cloudflare/clef-flash" : "@cf/cloudflare/clef";
81 const started = Date.now();
82 try {
83 const out = await env.AI.run(id, { ...body, model: body.model ?? "clef" });
84 return Response.json({ ...(out as object), ms: Date.now() - started });
85 } catch (e) {
86 return Response.json({ error: (e as Error).message, model: id }, { status: 502 });
87 }
88 }
89 const {
90 hold,
91 model = DEFAULT_MODEL,
92 samples = 1,
93 } = (await request.json()) as { hold: Hold; model?: string; samples?: number };
94 const started = Date.now();
95 // One sample answers at temperature 0 with the model's own confidence. Several sample at 0.7 in parallel,
96 // and the confidence is the share that agree with the most common pick: steadier than a self-report.
97 const one = async () => {
98 const out = (await env.AI.run(model, {
99 messages: [
100 { role: "system", content: SYSTEM },
101 { role: "user", content: prompt(hold) },
102 ],
103 response_format: { type: "json_schema", json_schema: SCHEMA },
104 temperature: samples > 1 ? 0.7 : 0,
105 max_tokens: 200,
106 })) as { response: unknown; usage?: { prompt_tokens?: number; completion_tokens?: number } };
107 const answer = (typeof out.response === "string" ? JSON.parse(out.response) : out.response) as {
108 pick: string;
109 confidence: number;
110 reason: string;
111 };
112 if (!(PICKS as readonly string[]).includes(answer?.pick)) throw new Error(`not a settle choice: ${answer?.pick}`);
113 return { ...answer, usage: out.usage ?? null };
114 };
115 try {
116 const answers = await Promise.all(Array.from({ length: Math.min(9, Math.max(1, samples)) }, one));
117 const votes = Object.fromEntries(PICKS.map((p) => [p, answers.filter((a) => a.pick === p).length]));
118 const pick = PICKS.reduce((a, b) => (votes[b]! > votes[a]! ? b : a));
119 const first = answers.find((a) => a.pick === pick)!;
120 return Response.json({
121 pick,
122 confidence: answers.length > 1 ? votes[pick]! / answers.length : first.confidence,
123 selfReported: answers.map((a) => a.confidence),
124 votes,
125 reason: first.reason,
126 model,
127 ms: Date.now() - started,
128 usage: first.usage,
129 });
130 } catch (e) {
131 return Response.json({ error: (e as Error).message, model, ms: Date.now() - started }, { status: 502 });
132 }
133 },
134};