-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount.html
More file actions
589 lines (538 loc) · 29.6 KB
/
Copy pathcount.html
File metadata and controls
589 lines (538 loc) · 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>patchling · count to 100</title>
<style>
:root { color-scheme: light dark; }
body { font: 15px/1.5 system-ui, sans-serif; max-width: 900px; margin: 1.5rem auto; padding: 0 1rem; }
header { display: flex; align-items: baseline; gap: .6rem; flex-wrap: wrap; }
h1 { font-size: 1.15rem; margin: 0; flex: 1; }
#status { font-size: .78rem; opacity: .6; }
a, button.link { font-size: .78rem; background: none; border: none; color: #2563eb; cursor: pointer; padding: 0; }
label { display: block; font-size: .8rem; opacity: .7; margin: .8rem 0 .2rem; }
input { width: 100%; box-sizing: border-box; font: inherit; padding: .5rem; border-radius: .5rem; border: 1px solid #8888; }
button.go { font: inherit; padding: .55rem 1rem; border-radius: .5rem; border: 1px solid #8888; cursor: pointer; background: #8881; }
button.go.primary { background: #2563eb; color: #fff; border-color: #2563eb; }
button:disabled { opacity: .5; cursor: default; }
.dim { opacity: .6; }
/* the one uneditable file */
.stage { margin-top: 1.2rem; display: flex; flex-direction: column; align-items: center; gap: .8rem;
border: 1px solid #8884; border-radius: .8rem; padding: 1.4rem 1rem 1.2rem; }
.filecard { width: 220px; border: 1px solid #8885; border-radius: .6rem; overflow: hidden; background: #8881; }
.fname { font-family: ui-monospace, monospace; font-size: 12px; padding: .35rem .6rem; background: #8882;
border-bottom: 1px solid #8884; display: flex; align-items: center; gap: .4rem; }
.fname .lock { opacity: .55; }
.num { font-family: ui-monospace, monospace; font-size: 4.2rem; font-weight: 700; text-align: center;
line-height: 1.15; padding: .4rem 0 .6rem; font-variant-numeric: tabular-nums; transition: color .15s; }
.num.ok { color: #1a7f37; } .num.bad { color: #cf222e; }
.bar { width: 220px; height: 6px; border-radius: 99px; background: #8883; overflow: hidden; }
.bar > i { display: block; height: 100%; width: 0; background: #2563eb; transition: width .2s; }
.bar.ok > i { background: #1a7f37; } .bar.bad > i { background: #cf222e; }
.controls { display: flex; gap: .6rem; }
.verdict { font-size: .95rem; text-align: center; min-height: 1.4em; max-width: 560px; }
.verdict.ok { color: #1a7f37; font-weight: 600; }
.verdict.bad { color: #cf222e; font-weight: 600; }
.verdict.stop { color: #b45309; font-weight: 600; }
#progress { display: none; margin-top: .9rem; padding: .7rem .9rem; border: 1px solid #8884; border-radius: .5rem; background: #8881; font-size: 13px; }
#progress .metrics { font-family: ui-monospace, monospace; margin-top: .25rem; }
#progress .dim { opacity: .6; }
.cols { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-top: 1.2rem; }
@media (max-width: 680px) { .cols { grid-template-columns: 1fr; } }
pre { font-family: ui-monospace, monospace; font-size: 12.5px; white-space: pre-wrap; word-break: break-word;
background: #8881; border-radius: .5rem; padding: .8rem; min-height: 3rem; max-height: 320px; overflow: auto; margin: 0; }
.diff .add { color: #1a7f37; } .diff .del { color: #cf222e; } .diff .hdr { opacity: .6; }
#log .ok { color: #1a7f37; } #log .bad { color: #cf222e; } #log .stop { color: #b45309; }
#key { display: none; margin-top: .5rem; }
#key input { max-width: 420px; display: inline-block; width: auto; }
.modelrow { font-size: .85rem; }
.modelrow b { font-family: ui-monospace, monospace; }
#modelrow { margin-top: .9rem; }
#modelrow-apply { margin-top: .25rem; }
#modelpicker { display: none; margin-top: .4rem; border: 1px solid #8884; border-radius: .5rem; padding: .6rem; max-width: 520px; }
#modellist { max-height: 240px; overflow: auto; margin-top: .4rem; }
#modellist button { display: flex; justify-content: space-between; gap: 1rem; width: 100%; text-align: left;
font-family: ui-monospace, monospace; font-size: 12px; padding: .3rem .4rem; border: none;
background: none; border-radius: .3rem; cursor: pointer; }
#modellist button:hover { background: #8882; }
#modellist button.sel { background: #2563eb22; font-weight: 600; }
#modellist .price { opacity: .6; white-space: nowrap; }
#modellist .divider { font-size: 11px; opacity: .5; text-align: center; margin: .35rem 0; }
#modellist .mname { display: flex; align-items: center; gap: .4rem; min-width: 0; }
.tag { font-family: system-ui, sans-serif; font-size: 10px; padding: .05rem .35rem; border-radius: .6rem; white-space: nowrap; }
.tag.priv { background: #3b82f622; color: #2563eb; }
.tag.closed { background: #f59e0b22; color: #b45309; }
.spin { display: inline-block; animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>
</head>
<body>
<style>
#banner { font-size: .8rem; text-align: center; padding: .5rem 1rem; margin: -1.5rem -1rem 1.2rem;
border-bottom: 1px solid #8883; background: #8881; }
#banner a { font-size: inherit; }
#banner .sep { opacity: .4; margin: 0 .5rem; }
</style>
<div id="banner">
<a href="https://patchling.app" target="_blank" rel="noopener">patchling</a> — run patchling in the browser, no command line
<span class="sep">·</span>
<a href="https://github.com/255BITS/patchling-examples" target="_blank" rel="noopener">more examples</a>
</div>
<header>
<h1>patchling · count to 100</h1>
<span id="status">checking…</span>
<a id="signin" href="#" style="display:none">Sign in with NanoGPT</a>
<button id="pastebtn" class="link" style="display:none">paste key</button>
<button id="signout" class="link" style="display:none">sign out</button>
</header>
<p class="dim" style="font-size:.88rem;margin:.3rem 0 0">
A reliability loop. One uneditable file — <b><code>count</code></b> — holding a single number. Each step,
patchling is asked to <b>add 1</b>, the diff is applied, and the result is <b>verified</b> to be exactly the
previous number plus one. The <code>for</code> loop starts, steps, and stops: it <b>passes</b> when it reaches
100, <b>fails</b> the instant a step doesn't land on n+1, or <b>stops</b> when you press Stop.
</p>
<div id="key">
<input id="keyinput" placeholder="sk-nano-…" />
<button id="keysave" class="link">save</button>
<span class="dim" style="font-size:.78rem">— from <a href="https://nano-gpt.com/r/FXrrGWE4" target="_blank" rel="noopener">nano-gpt.com</a> → Settings → API</span>
</div>
<div id="modelrow" class="modelrow">Diff model: <b id="modelname-diff">…</b> <span id="modeltags-diff"></span> <span id="modelprice-diff"></span> <button class="link modelchange" data-target="diff">change</button></div>
<div id="modelrow-apply" class="modelrow">Apply model: <b id="modelname-apply">…</b> <span id="modeltags-apply"></span> <span id="modelprice-apply"></span> <button class="link modelchange" data-target="apply">change</button></div>
<div id="modelpicker">
<input id="modelsearch" placeholder="filter 600+ models, or type an exact id…" autocomplete="off" />
<div id="modellist"></div>
<div class="dim" style="font-size:.75rem;margin-top:.3rem"><span id="modelcount"></span> · top = each frontier lab's latest flagship · price = $ in / $ out per 1M · Enter to use exact text</div>
</div>
<section class="stage">
<div class="filecard">
<div class="fname"><span class="lock">🔒</span> count <span class="dim" style="margin-left:auto">read-only</span></div>
<div id="num" class="num">1</div>
</div>
<div id="bar" class="bar"><i id="barfill"></i></div>
<div class="controls">
<button id="start" class="go primary" disabled>▶ Count to 100</button>
<button id="stop" class="go" disabled>■ Stop</button>
</div>
<div id="verdict" class="verdict dim">Ready — counts the file 1 → 100, one patchling edit per step, verifying each lands on n+1.</div>
<div id="progress">
<span class="spin">◐</span> <b id="phase">starting…</b> · ⏱ <span id="elapsed">0.0</span>s · step <span id="step">0</span>
<div class="metrics">
↓ <span id="inTok">0</span> in · ↑ <span id="outTok">0</span> out · <span id="cost">$0.00000</span>
<span id="live" class="dim"></span>
</div>
</div>
</section>
<div class="cols">
<div><label>Current step — generated diff</label><pre id="diff" class="diff"></pre></div>
<div><label>Step log</label><pre id="log"></pre></div>
</div>
<footer style="margin-top:2rem;padding-top:1rem;border-top:1px solid #8883;font-size:.85rem">
<b>Other examples</b> · <a href="index.html">patchling · diff → smartapply</a> · <a href="overlay.html">🎬 realtime video overlay</a> · <a href="object3d.html">🧊 3d object studio</a> · <a href="comic.html">📖 AI-liftoff comic</a> · <a href="marvis.html">🤖 MARVIS</a>
</footer>
<script type="module">
import { buildEnvironment, generateDiff, smartapply, parseDiffPerFile, callLlmForApply, setEnv }
from "https://esm.sh/patchling";
const DEFAULT_MODEL = "xiaomi/mimo-v2.5-pro-ultraspeed";
const APPLY_DEFAULT = "xiaomi/mimo-v2.5-pro-ultraspeed"; // smartapply default (fast, mechanical)
const NANOGPT = "https://nano-gpt.com";
const $ = (id) => document.getElementById(id);
const START = 1, TARGET = 100;
const GOAL = "The file `count` contains a single integer and nothing else. Increment that integer by exactly one (for example 41 becomes 42). Output only the new number.";
let MODEL = localStorage.getItem("ngpt_model") || DEFAULT_MODEL; // selectable DIFF model
let APPLY = localStorage.getItem("ngpt_apply_model") || APPLY_DEFAULT; // selectable APPLY model
let pickerTarget = "diff"; // which row the picker edits
// NanoGPT canonicalizes the loopback host to "localhost"; start there so the OAuth
// redirect returns to the same origin (keeping sessionStorage intact).
if (location.hostname === "127.0.0.1") location.hostname = "localhost";
// ---------- key storage ----------
const getKey = () => localStorage.getItem("ngpt_key");
const setKey = (k) => { k ? localStorage.setItem("ngpt_key", k) : localStorage.removeItem("ngpt_key"); if (k) setEnv("GPTDIFF_LLM_API_KEY", k); };
if (getKey()) setEnv("GPTDIFF_LLM_API_KEY", getKey());
// ---------- browser OAuth PKCE (token + register are CORS-open) ----------
const REDIRECT_URI = location.origin + location.pathname;
const b64url = (b) => btoa(String.fromCharCode(...new Uint8Array(b))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const rand = (n) => b64url(crypto.getRandomValues(new Uint8Array(n)));
const sha256url = async (s) => b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
async function clientId() {
const cached = JSON.parse(localStorage.getItem("ngpt_client") || "null");
if (cached && cached.redirect === REDIRECT_URI) return cached.id;
const r = await fetch(`${NANOGPT}/oauth/register`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ client_name: "patchling count", redirect_uris: [REDIRECT_URI],
grant_types: ["authorization_code"], response_types: ["code"], token_endpoint_auth_method: "none" }),
});
if (!r.ok) throw new Error("register " + r.status);
const id = (await r.json()).client_id;
localStorage.setItem("ngpt_client", JSON.stringify({ id, redirect: REDIRECT_URI }));
return id;
}
async function signIn() {
const id = await clientId();
const verifier = rand(32), state = rand(16);
sessionStorage.setItem("pkce", JSON.stringify({ verifier, state, id }));
const u = new URL(`${NANOGPT}/oauth/authorize`);
u.search = new URLSearchParams({
response_type: "code", client_id: id, redirect_uri: REDIRECT_URI, scope: "api.use models.read",
state, code_challenge: await sha256url(verifier), code_challenge_method: "S256", invitation_code: "FXrrGWE4",
}).toString();
location.assign(u.toString());
}
async function handleRedirect() {
const p = new URLSearchParams(location.search);
if (!p.has("code") && !p.has("error")) return;
history.replaceState({}, "", REDIRECT_URI);
const saved = JSON.parse(sessionStorage.getItem("pkce") || "null");
sessionStorage.removeItem("pkce");
if (p.get("error")) throw new Error(p.get("error"));
if (!saved || p.get("state") !== saved.state) throw new Error("state mismatch");
const r = await fetch(`${NANOGPT}/oauth/token`, {
method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "authorization_code", client_id: saved.id,
redirect_uri: REDIRECT_URI, code: p.get("code"), code_verifier: saved.verifier }),
});
if (!r.ok) throw new Error("token exchange: " + (await r.text()));
setKey((await r.json()).access_token);
}
function renderAuth() {
const signed = !!getKey();
$("status").textContent = signed ? "ready ✓" : "not signed in";
$("signin").style.display = signed ? "none" : "";
$("pastebtn").style.display = signed ? "none" : "";
$("signout").style.display = signed ? "" : "none";
$("start").disabled = !signed || running;
}
$("signin").addEventListener("click", (e) => { e.preventDefault(); signIn().catch((err) => $("status").textContent = "sign-in error: " + err.message); });
$("pastebtn").addEventListener("click", () => { $("key").style.display = "block"; $("keyinput").focus(); });
$("keysave").addEventListener("click", () => { const k = $("keyinput").value.trim(); if (k) { setKey(k); $("key").style.display = "none"; renderAuth(); } });
$("signout").addEventListener("click", () => { setKey(null); renderAuth(); });
// ---------- model selection ----------
let allModels = null; // [{ id, prompt, completion, owned_by, created }] prices = USD per 1M
let topOrder = new Map(); // id -> rank for the curated top list; everything else sorts below
// Top list = each frontier lab's latest flagship (newest release matching the lab's
// flagship line), excluding small/cheap variants. Only the major labs.
const LABS = [
["OpenAI", /^openai\/(gpt-[0-9]|o[1-9])/i],
["Anthropic", /claude-(opus|sonnet)/i],
["Google", /gemini[0-9.\-]*-pro|gemini-pro/i],
["xAI", /grok-[0-9]/i],
["DeepSeek", /deepseek-(r1|v3|v4|chat)/i],
["Qwen", /qwen[0-9.]*-max/i],
["Mistral", /mistral-large/i],
];
// Always pinned at the very top, in this order (default first).
const PINNED = ["xiaomi/mimo-v2.5-pro-ultraspeed", "moonshotai/kimi-k2.7-code-highspeed", "moonshotai/kimi-k2.7-code"];
// Exclude small/cheap/variant rows. \bmini\b avoids matching "geMINI".
const SMALL = /flash|nano|\blite\b|\bmini\b|-mini|\bsmall\b|tiny|oss|guard|preview|search|codex|:(low|medium|high|thinking)|cheaper|multi-agent|-\d+b\b|a\d+b\b|^tee\//i;
const px = (x) => (x == null ? null : "$" + Number(x).toFixed(2));
const priceOf = (id) => (allModels || []).find((m) => m.id === id);
function computeTop() {
const ids = new Set(allModels.map((m) => m.id));
const order = PINNED.filter((id) => ids.has(id)); // pinned first, in given order
const picks = [];
for (const [, re] of LABS) {
const m = allModels.filter((x) => re.test(x.id) && !SMALL.test(x.id)).sort((a, b) => (b.created || 0) - (a.created || 0))[0];
if (m && !order.includes(m.id)) picks.push(m);
}
picks.sort((a, b) => (b.created || 0) - (a.created || 0)); // most recent flagship first
for (const m of picks) order.push(m.id);
topOrder = new Map(order.map((id, i) => [id, i]));
}
const rank = (id) => (topOrder.has(id) ? topOrder.get(id) : 1e9);
const selectedFor = (target) => (target === "apply" ? APPLY : MODEL);
function setModel(id, target) {
if (target === "apply") { APPLY = id; localStorage.setItem("ngpt_apply_model", id); }
else { MODEL = id; localStorage.setItem("ngpt_model", id); }
renderModelRow(target);
}
function renderModelRow(target) {
const id = selectedFor(target);
const m = priceOf(id) || { id };
$(`modelname-${target}`).textContent = id;
$(`modelprice-${target}`).textContent = m.prompt != null ? `(${px(m.prompt)} / ${px(m.completion)} per 1M)` : "";
$(`modeltags-${target}`).replaceChildren(...tagEls(m));
}
async function loadModels() {
if (allModels) return allModels;
let arr = [];
try {
const headers = {}; const k = getKey(); if (k) headers.Authorization = `Bearer ${k}`;
arr = (await (await fetch(`${NANOGPT}/api/v1/models?detailed=true`, { headers })).json()).data || [];
} catch { /* ignore */ }
allModels = arr.map((m) => ({ id: m.id, prompt: m.pricing?.prompt, completion: m.pricing?.completion, owned_by: m.owned_by, created: m.created })).filter((m) => m.id);
if (!allModels.length) allModels = [{ id: DEFAULT_MODEL }]; // fallback; custom ids still typeable
computeTop();
allModels.sort((a, b) => (rank(a.id) - rank(b.id)) || a.id.localeCompare(b.id));
renderModelRow("diff"); renderModelRow("apply"); // refresh prices/tags now that we have data
return allModels;
}
// Tags: TEE = private (runs in a Trusted Execution Environment); OpenAI/Anthropic = closed source.
function tagsFor(m) {
const t = [];
if (m.id.startsWith("TEE/")) t.push(["private", "priv", "Runs in a Trusted Execution Environment"]);
const ob = (m.owned_by || "").toLowerCase();
if (["openai", "anthropic", "x-ai", "google", "gemini"].includes(ob)) t.push(["closed source", "closed", "Closed-source / proprietary model"]);
return t;
}
function tagEls(m) {
return tagsFor(m).map(([txt, cls, title]) => { const s = document.createElement("span"); s.className = "tag " + cls; s.textContent = txt; s.title = title; return s; });
}
function modelButton(m) {
const b = document.createElement("button");
if (m.id === selectedFor(pickerTarget)) b.className = "sel";
const left = document.createElement("span"); left.className = "mname";
const name = document.createElement("span"); name.textContent = m.id;
left.append(name, ...tagEls(m));
const price = document.createElement("span"); price.className = "price";
price.textContent = m.prompt != null ? `${px(m.prompt)} / ${px(m.completion)}` : "—";
b.append(left, price);
b.addEventListener("click", () => { setModel(m.id, pickerTarget); $("modelpicker").style.display = "none"; });
return b;
}
function renderModelList() {
const q = $("modelsearch").value.trim().toLowerCase();
const matches = (allModels || []).filter((m) => m.id.toLowerCase().includes(q));
const shown = matches;
$("modellist").innerHTML = "";
let dividerPlaced = !!q; // no top/rest split while searching
for (const m of shown) {
if (!dividerPlaced && rank(m.id) === 1e9) {
const d = document.createElement("div"); d.className = "divider"; d.textContent = "— all models —";
$("modellist").appendChild(d); dividerPlaced = true;
}
$("modellist").appendChild(modelButton(m));
}
$("modelcount").textContent = `${matches.length} match${matches.length === 1 ? "" : "es"}`;
}
for (const btn of document.querySelectorAll(".modelchange")) {
btn.addEventListener("click", async () => {
const target = btn.dataset.target;
const same = $("modelpicker").style.display === "block" && pickerTarget === target;
pickerTarget = target;
$("modelpicker").style.display = same ? "none" : "block";
if (!same) { $("modelsearch").value = ""; $("modellist").innerHTML = "<div class='dim'>loading…</div>"; await loadModels(); renderModelList(); $("modelsearch").focus(); }
});
}
$("modelsearch").addEventListener("input", renderModelList);
$("modelsearch").addEventListener("keydown", (e) => {
if (e.key === "Enter") { const v = $("modelsearch").value.trim(); if (v) { setModel(v, pickerTarget); $("modelpicker").style.display = "none"; } }
});
// ---------- streaming LLM client injected into patchling ----------
const fmtCost = (c) => "$" + (c || 0).toFixed(5);
const n = (x) => (x || 0).toLocaleString();
const words = (s) => (String(s).match(/\S+/g) || []).length; // ~tokens, counted as words
// inDone/outDone = exact tokens from finished calls; liveIn/liveOut = in-flight word estimates.
const prog = { inDone: 0, outDone: 0, cost: 0, liveIn: 0, liveOut: 0, liveCost: 0 };
let abort = null; // AbortController for the in-flight LLM call (Stop aborts it)
function paintUsage() {
$("inTok").textContent = n(prog.inDone + prog.liveIn);
$("outTok").textContent = n(prog.outDone + prog.liveOut);
$("cost").textContent = fmtCost(prog.cost + prog.liveCost); // committed + in-flight estimate
}
function streamingCallLlm(phase) {
return async ({ apiKey, baseUrl, model, messages, maxTokens = null, temperature = 1.0 }) => {
$("phase").textContent = phase;
// Input estimate from the prompt (words ≈ tokens) — shown immediately, fixed for the call.
const inEst = messages.reduce((s, m) => s + words(typeof m.content === "string" ? m.content : JSON.stringify(m.content)), 0);
// Live cost estimate = approximated tokens × the selected model's per-token price
// (USD per 1M from the model list). Replaced by NanoGPT's exact figure on commit.
const price = priceOf(model) || {};
const inPer = (Number(price.prompt) || 0) / 1e6, outPer = (Number(price.completion) || 0) / 1e6;
let prevOut = 0, myCost = 0;
const recost = () => { const c = inEst * inPer + prevOut * outPer; prog.liveCost += c - myCost; myCost = c; };
prog.liveIn += inEst; recost(); paintUsage();
const endpoint = (baseUrl || `${NANOGPT}/api/v1/`).replace(/\/+$/, "") + "/chat/completions";
let r;
try {
r = await fetch(endpoint, {
method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
// No max_tokens by default → let the model emit its full output (avoids silent
// truncation that produces an unparseable diff). Callers may still pass a cap.
body: JSON.stringify({ model, messages, ...(maxTokens ? { max_tokens: maxTokens } : {}), temperature, stream: true }),
signal: abort?.signal,
});
} catch (e) { prog.liveIn -= inEst; prog.liveCost -= myCost; throw e; }
if (!r.ok) { prog.liveIn -= inEst; prog.liveCost -= myCost; throw new Error(`LLM ${r.status}: ${await r.text()}`); }
const reader = r.body.getReader();
const dec = new TextDecoder();
let buf = "", content = "", reasoning = "", pricing = null, lastTick = 0;
try {
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop();
for (const line of lines) {
const t = line.trim();
if (!t.startsWith("data:")) continue;
const data = t.slice(5).trim();
if (data === "[DONE]") continue;
let j; try { j = JSON.parse(data); } catch { continue; }
const d = j.choices?.[0]?.delta;
if (d) {
if (d.content) { content += d.content; appendText(phase, d.content); }
if (d.reasoning) reasoning += d.reasoning;
if (d.content || d.reasoning) {
// recount from accumulated text (avoids miscounting words split across chunks)
const cur = words(content) + words(reasoning);
prog.liveOut += cur - prevOut; prevOut = cur; recost();
const now = performance.now();
if (now - lastTick > 80) { lastTick = now; paintUsage(); $("live").textContent = content ? "" : "· thinking…"; }
}
}
if (j.x_nanogpt_pricing) pricing = j.x_nanogpt_pricing;
}
}
} catch (e) {
// Stop() aborts the fetch mid-stream — unwind this call's live estimates and rethrow.
prog.liveIn -= inEst; prog.liveOut -= prevOut; prog.liveCost -= myCost; paintUsage();
throw e;
}
// Commit: drop this call's estimates, add exact tokens (fall back to the estimate).
prog.liveIn -= inEst; prog.liveOut -= prevOut; prog.liveCost -= myCost;
prog.inDone += pricing?.inputTokens ?? inEst;
prog.outDone += pricing?.outputTokens ?? prevOut;
prog.cost += pricing?.costUsd ?? pricing?.cost ?? myCost; // exact, else keep the estimate
paintUsage(); $("live").textContent = "";
return { choices: [{ message: { content } }] };
};
}
// ---------- the counting loop ----------
let running = false; // a run is in progress
let stopRequested = false; // user pressed Stop
let count = START;
let curPhase = "";
function appendText(phase, chunk) {
if (!phase.startsWith("Generating")) return; // apply streams in parallel — show the meter, not its text
const pane = $("diff");
if (phase !== curPhase) { curPhase = phase; pane.textContent = ""; }
pane.textContent += chunk;
pane.scrollTop = pane.scrollHeight;
}
function renderDiff(diff) {
$("diff").innerHTML = "";
if (!diff.trim()) { $("diff").textContent = "(no diff produced)"; return; }
for (const line of diff.split("\n")) {
const span = document.createElement("span");
span.textContent = line + "\n";
if (/^\+\+\+|^---|^@@|^diff |^a\/|^b\//.test(line)) span.className = "hdr";
else if (line.startsWith("+")) span.className = "add";
else if (line.startsWith("-")) span.className = "del";
$("diff").appendChild(span);
}
}
function paintCount(cls) {
$("num").textContent = count;
$("num").className = "num" + (cls ? " " + cls : "");
const pct = Math.max(0, Math.min(100, ((count - START) / (TARGET - START)) * 100));
$("barfill").style.width = pct + "%";
$("bar").className = "bar" + (cls ? " " + cls : "");
}
function logLine(text, cls) {
const span = document.createElement("span");
span.textContent = text + "\n";
if (cls) span.className = cls;
$("log").appendChild(span);
$("log").scrollTop = $("log").scrollHeight;
}
function setVerdict(text, cls) { $("verdict").textContent = text; $("verdict").className = "verdict" + (cls ? " " + cls : ""); }
// One step: ask patchling to add 1, apply, and verify the result is exactly prev+1.
// Returns { ok, next, raw }. Throws only on network/abort/LLM errors.
async function step(key) {
const before = count;
const files = { count: String(before) };
curPhase = ""; $("diff").textContent = "";
const diff = await generateDiff(buildEnvironment(files), GOAL,
{ apiKey: key, model: MODEL, callLlm: streamingCallLlm("Generating diff") });
renderDiff(diff);
const parsed = parseDiffPerFile(diff);
if (!diff.trim() || !parsed.length) return { ok: false, raw: "(model returned no diff)" };
const applyLlm = streamingCallLlm("Applying diff");
const updated = await smartapply(diff, files, {
apiKey: key, model: APPLY,
callLlmForApply: (p, o, d, m, o2) => callLlmForApply(p, o, d, m, { ...o2, callLlm: applyLlm }),
});
const raw = (updated.count ?? "(file deleted)").trim();
const next = Number(raw);
const ok = /^-?\d+$/.test(raw) && next === before + 1;
return { ok, next, raw };
}
async function runLoop() {
const key = getKey();
if (!key || running) return;
running = true; stopRequested = false; abort = new AbortController();
count = START;
prog.inDone = prog.outDone = prog.cost = prog.liveIn = prog.liveOut = prog.liveCost = 0; paintUsage();
$("log").innerHTML = ""; $("diff").textContent = "";
paintCount("");
setVerdict(`Counting… verifying each step lands on n+1.`, "");
$("start").disabled = true; $("stop").disabled = false;
$("progress").style.display = "block";
document.querySelector("#progress .spin").style.display = "";
const t0 = performance.now();
const timer = setInterval(() => { $("elapsed").textContent = ((performance.now() - t0) / 1000).toFixed(1); }, 100);
try {
// The for loop: start at START, step while below TARGET, stop on pass / fail / user.
for (let i = 0; count < TARGET; i++) {
if (stopRequested) break;
$("step").textContent = i + 1;
const before = count;
const r = await step(key);
if (stopRequested) break; // a result that arrived after Stop doesn't count
if (!r.ok) {
count = before; paintCount("bad");
logLine(`${before} → ${r.raw} ✗ expected ${before + 1}`, "bad");
setVerdict(`✗ FAILED at ${before}. The model produced "${r.raw}" — expected ${before + 1}. Stopped.`, "bad");
document.querySelector("#progress .spin").style.display = "none";
return;
}
count = r.next; paintCount("ok");
logLine(`${before} → ${count} ✓`, "ok");
}
if (stopRequested) {
paintCount("stop");
logLine(`stopped by user at ${count}`, "stop");
setVerdict(`■ Stopped by you at ${count}. The loop was interrupted — it did not pass or fail on its own.`, "stop");
} else {
paintCount("ok");
setVerdict(`✓ PASSED — reached ${TARGET}, every step verified as exactly n+1.`, "ok");
}
document.querySelector("#progress .spin").style.display = "none";
} catch (e) {
if (stopRequested || e.name === "AbortError") {
paintCount("stop");
logLine(`stopped by user at ${count}`, "stop");
setVerdict(`■ Stopped by you at ${count}. The loop was interrupted — it did not pass or fail on its own.`, "stop");
document.querySelector("#progress .spin").style.display = "none";
} else {
paintCount("bad");
setVerdict("Error: " + e.message, "bad");
$("progress").style.display = "none";
}
} finally {
clearInterval(timer);
running = false; abort = null;
$("stop").disabled = true;
renderAuth(); // re-enables Start if still signed in
}
}
$("start").addEventListener("click", runLoop);
$("stop").addEventListener("click", () => {
if (!running) return;
stopRequested = true;
$("stop").disabled = true;
$("phase").textContent = "stopping…";
abort?.abort(); // cut the in-flight LLM call short so Stop is immediate
});
// ---------- boot ----------
(async () => {
renderModelRow("diff"); renderModelRow("apply");
try { await handleRedirect(); } catch (e) { $("status").textContent = "sign-in error: " + e.message; }
renderAuth();
paintCount("");
loadModels(); // populate prices/tags (and warm the picker) in the background
})();
</script>
</body>
</html>