- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/scripts/autosettle/jev.ts?version=190&format=json
176 linesautosettle 100%Last change autosettle in version 189, 1 version changed it
You're reading version 190. The newest is 318, and 3 versions since then changed this file.
1// Ask Jev (TypeSafe's System One model) how a held push's collision should be
2// settled (#19). Jev answers a Choice with a probability per option, so it can
3// pick among abso's own settle choices but can't write code.
4//
5// API: POST https://api.typesafe.ai/v1/systemone, per https://docs.typesafe.ai/api.md.
6// The key comes from JEV_API_KEY (or TYPESAFE_API_KEY, the SDK's own name) and
7// is never printed or written anywhere.
9import { execFileSync } from "node:child_process";
11export const ENDPOINT = "https://api.typesafe.ai/v1/systemone";
13/** abso's settle choices, plus a hand edit by an agent. */
14export type Pick = "yours" | "theirs" | "both" | "agent";
15export const PICKS: readonly Pick[] = ["yours", "theirs", "both", "agent"];
17/** One collision as the held agent sees it: a marker block and what's around it. */
18export interface Hold {
19 readonly file: string;
20 readonly base: readonly string[];
21 readonly yours: readonly string[];
22 readonly theirs: readonly string[];
23 readonly before: readonly string[];
24 readonly after: readonly string[];
25 /** The held push's message: the settler's reason. */
26 readonly yourMessage?: string;
27 readonly yourAgent?: string;
28 /** The push that got there first: its reason. */
29 readonly theirMessage?: string;
30 readonly theirAgent?: string;
31 readonly issue?: string;
32}
34export interface Verdict {
35 readonly pick: Pick;
36 /** Averaged over both option orders. */
37 readonly probabilities: Record<Pick, number>;
38 /** Choice confidence on the averaged probabilities: 0 at an even split, 1 when certain. */
39 readonly confidence: number;
40 /** Each order's own answer, to see whether the order moved it. */
41 readonly orders: readonly { pick: Pick; probabilities: Record<Pick, number>; confidence: number }[];
42 /** Yes-probabilities of the side questions. */
43 readonly signs: Record<string, number>;
44 readonly model: string;
45 readonly ms: number;
46 readonly inputTokens: number;
47}
49export function apiKey(): string {
50 const key = process.env.JEV_API_KEY ?? process.env.TYPESAFE_API_KEY ?? userVariable("JEV_API_KEY");
51 if (!key) throw new Error("No Jev key: set JEV_API_KEY in the environment.");
52 return key;
53}
55/** On Windows, a user variable set after this shell started (setx, or the Environment Variables dialog). */
56function userVariable(name: string): string | undefined {
57 if (process.platform !== "win32") return undefined;
58 try {
59 const out = execFileSync(
60 "powershell.exe",
61 ["-NoProfile", "-Command", `[Environment]::GetEnvironmentVariable('${name}','User')`],
62 { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
63 ).trim();
64 return out || undefined;
65 } catch {
66 return undefined;
67 }
68}
70const text = (lines: readonly string[]): string => (lines.length === 0 ? "(no lines)" : lines.join("\n"));
72function stateOf(h: Hold): Record<string, unknown> {
73 return {
74 file: h.file,
75 lines_above: text(h.before),
76 before_either_change: text(h.base),
77 yours: text(h.yours),
78 theirs: text(h.theirs),
79 lines_below: text(h.after),
80 your_push: { agent: h.yourAgent ?? "you", message: h.yourMessage ?? "(no message)" },
81 their_push: { agent: h.theirAgent ?? "the other agent", message: h.theirMessage ?? "(no message)" },
82 ...(h.issue ? { issue: h.issue } : {}),
83 };
84}
86const INSTRUCTIONS =
87 "Two agents changed the same lines of `file`. Both started from `before_either_change`. " +
88 "`yours` is what the held agent wrote, for the reason in `your_push`; `theirs` was pushed first, for the reason in `their_push`. " +
89 "The region sits between `lines_above` and `lines_below`. " +
90 "Which result is correct code that does what both pushes meant?";
92const CRITERIA: Record<Pick, string> = {
93 yours: "Keep `yours` only: `yours` already does what `theirs` meant, or `theirs` is wrong or out of date.",
94 theirs: "Keep `theirs` only: `theirs` already does what `yours` meant, or `yours` is wrong or out of date.",
95 both: "Keep both unchanged, `yours` then `theirs`: they add separate things that work side by side, and nothing is duplicated or contradicts.",
96 agent:
97 "Neither side alone and not both unchanged: 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.",
98};
100function choice(order: readonly Pick[]) {
101 return {
102 type: "choice",
103 instructions: INSTRUCTIONS,
104 criteria: Object.fromEntries(order.map((p) => [p, CRITERIA[p]])),
105 };
106}
108const SIGNS: Record<string, string> = {
109 same_setting_different_values:
110 "Do `yours` and `theirs` set the same setting, constant or value to two different values?",
111 theirs_covers_yours: "Does `theirs` already do everything `yours` was changed to do?",
112 yours_covers_theirs: "Does `yours` already do everything `theirs` was changed to do?",
113 both_unchanged_compiles:
114 "If `yours` were placed directly above `theirs`, unchanged, would the file still be correct code with nothing defined twice?",
115};
117function confidenceOf(p: Record<Pick, number>): number {
118 const max = Math.max(...PICKS.map((k) => p[k]));
119 const even = 1 / PICKS.length;
120 return Math.max(0, (max - even) / (1 - even));
121}
123function top(p: Record<Pick, number>): Pick {
124 return PICKS.reduce((a, b) => (p[b] > p[a] ? b : a));
125}
127/** Ask Jev once, with the choice in two option orders (Jev's docs warn order can sway a Choice) and the side questions. */
128export async function ask(h: Hold, opts: { model?: string; key?: string } = {}): Promise<Verdict> {
129 const forward = PICKS;
130 const backward = [...PICKS].reverse();
131 const body = {
132 model: opts.model ?? "jev-latest",
133 state: stateOf(h),
134 questions: {
135 settle: choice(forward),
136 settle_reversed: choice(backward),
137 ...Object.fromEntries(Object.entries(SIGNS).map(([id, q]) => [id, { type: "noul", instructions: q }])),
138 },
139 };
140 const started = performance.now();
141 const res = await fetch(ENDPOINT, {
142 method: "POST",
143 headers: { authorization: `Bearer ${opts.key ?? apiKey()}`, "content-type": "application/json" },
144 body: JSON.stringify(body),
145 });
146 const ms = performance.now() - started;
147 if (!res.ok) throw new Error(`Jev answered ${res.status}: ${(await res.text()).slice(0, 500)}`);
148 const out = (await res.json()) as {
149 model: string;
150 answers: Record<string, { type: string; probabilities?: Record<string, number>; noul?: number; choice?: string }>;
151 usage: { input_tokens: number };
152 };
153 const orders = ["settle", "settle_reversed"].map((id) => {
154 const probabilities = Object.fromEntries(PICKS.map((k) => [k, out.answers[id]!.probabilities![k] ?? 0])) as Record<
155 Pick,
156 number
157 >;
158 return { pick: top(probabilities), probabilities, confidence: confidenceOf(probabilities) };
159 });
160 const probabilities = Object.fromEntries(
161 PICKS.map((k) => [k, (orders[0]!.probabilities[k] + orders[1]!.probabilities[k]) / 2]),
162 ) as Record<Pick, number>;
163 return {
164 pick: top(probabilities),
165 probabilities,
166 confidence: confidenceOf(probabilities),
167 orders,
168 signs: Object.fromEntries(Object.keys(SIGNS).map((id) => [id, out.answers[id]?.noul ?? Number.NaN])),
169 model: out.model,
170 ms,
171 inputTokens: out.usage.input_tokens,
172 };
173}
175/** Dollars for one call: Jev charges $0.042 per million input tokens, output free (docs.typesafe.ai/models). */
176export const dollars = (inputTokens: number): number => (inputTokens * 0.042) / 1e6;