-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
621 lines (567 loc) · 32.2 KB
/
Copy pathindex.html
File metadata and controls
621 lines (567 loc) · 32.2 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>patchling · NanoGPT (single file)</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, textarea { width: 100%; box-sizing: border-box; font: inherit; padding: .5rem; border-radius: .5rem; border: 1px solid #8888; }
textarea { font-family: ui-monospace, monospace; font-size: 13px; }
button.go { font: inherit; padding: .55rem 1rem; border-radius: .5rem; border: 1px solid #8888; cursor: pointer; background: #8881; margin-top: .8rem; }
button:disabled { opacity: .5; cursor: default; }
.cols { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
@media (max-width: 680px) { .cols { grid-template-columns: 1fr; } }
pre { font-family: ui-monospace, monospace; font-size: 13px; white-space: pre-wrap; word-break: break-word;
background: #8881; border-radius: .5rem; padding: .8rem; min-height: 3rem; max-height: 360px; overflow: auto; margin: 0; }
.diff .add { color: #1a7f37; } .diff .del { color: #cf222e; } .diff .hdr { opacity: .6; }
#progress { display: none; margin-top: .8rem; 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; }
#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; }
#modelprice { opacity: .6; font-family: ui-monospace, monospace; }
.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; }
#playmodal { position: fixed; inset: 0; background: #000; display: none; z-index: 50; }
#playmodal.open { display: block; }
#playframe { border: 0; width: 100vw; height: 100vh; display: block; background: #222; }
#playclose { position: fixed; top: 12px; right: 14px; z-index: 51; background: #000a; color: #fff;
border: 1px solid #fff6; border-radius: .4rem; padding: .35rem .7rem; cursor: pointer; font: 14px system-ui; }
#playclose:hover { background: #000d; }
.spin { display: inline-block; animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
#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; }
#versions { display: flex; flex-wrap: wrap; gap: .35rem; align-items: center; margin: .6rem 0 .2rem; }
#versions:empty { display: none; }
#versions .vlabel { font-size: .8rem; opacity: .6; margin-right: .15rem; }
.ver { font: inherit; font-size: .8rem; padding: .2rem .55rem; border-radius: 1rem; border: 1px solid #8884;
background: #8881; cursor: pointer; display: inline-flex; align-items: center; gap: .3rem; }
.ver:hover { background: #8882; }
.ver.cur { background: #2563eb22; border-color: #2563eb88; font-weight: 600; }
.ver.seed { font-style: italic; opacity: .85; }
.ver .play { opacity: .65; font-size: .72rem; }
</style>
</head>
<body>
<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 · diff → smartapply</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>
<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>
<label for="path">File path</label>
<input id="path" value="index.html" />
<label for="content">Existing file — just notes & pseudocode (let the AI build it)</label>
<textarea id="content" rows="16">GAME PLAN — a small browser arcade game in one self-contained index.html.
A canvas-based Space Invaders: dark background, centered, no libraries.
LAYOUT
- a title and a score readout
- a game canvas, about 480 x 600
- a one-line hint for the controls
STATE
- player: x, y, width, height, speed — sits near the bottom
- bullets: player shots that move up
- enemies: a grid of aliens near the top
- enemyDir: +1, march right then flip and step down
- score = 0, gameOver = false
INPUT
- ArrowLeft / ArrowRight move the player
- Space fires a bullet (rate-limited)
EACH FRAME (requestAnimationFrame)
- move the player from input, clamped to the canvas
- move bullets up, drop the ones off-screen
- move the enemy block; at an edge, flip direction and step down
- bullet hits an enemy: remove both, score += 10
- lose if any enemy reaches the player's row
- draw everything; show GAME OVER when done
TODO: turn this plan into a real, playable game.</textarea>
<button id="play" class="go" style="margin-top:.4rem" disabled>▶ Play (build it first)</button>
<div id="versions" title="Each build adds a version — click one to view & Play it"></div>
<label for="goal">Goal (what to change)</label>
<input id="goal" value="Make the game more fun, juicy, and polished" />
<button id="run" class="go">Diff & apply</button>
<div id="progress">
<span class="spin">◐</span> <b id="phase">starting…</b> · ⏱ <span id="elapsed">0.0</span>s
<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>
<div class="cols" style="margin-top:1rem">
<div><label>Generated diff</label><pre id="diff" class="diff"></pre></div>
<div><label>New file — applied to the editor automatically</label><pre id="result"></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="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> · <a href="pictureme.html">🪞 picture me as…</a> · <a href="count.html">🔢 count to 100</a>
</footer>
<div id="playmodal">
<iframe id="playframe" sandbox="allow-scripts" title="game preview"></iframe>
<button id="playclose">✕ close (Esc)</button>
</div>
<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);
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 single-file", 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";
$("run").disabled = !signed;
}
$("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 — no Llama,
// Alibaba, Holo, fine-tunes, or smaller models.
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 };
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 }),
});
} 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;
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;
}
}
// 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 } }] };
};
}
// ---------- diff lab ----------
let curPhase = "";
function appendText(phase, chunk) {
const pane = phase.startsWith("Generating") ? $("diff") : $("result");
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);
}
}
async function run() {
const key = getKey();
if (!key) return;
const path = $("path").value.trim() || "file.txt";
const content = $("content").value;
const files = { [path]: content };
$("run").disabled = true; curPhase = "";
$("diff").textContent = ""; $("result").textContent = "";
prog.inDone = prog.outDone = prog.cost = prog.liveIn = prog.liveOut = prog.liveCost = 0; paintUsage();
$("progress").style.display = "block";
document.querySelector("#progress .spin").style.display = "";
$("live").textContent = ""; $("phase").textContent = "starting…";
const t0 = performance.now();
const timer = setInterval(() => { $("elapsed").textContent = ((performance.now() - t0) / 1000).toFixed(1); }, 100);
try {
// Diff uses the selected model; smartapply is locked to ultraspeed (fast, mechanical).
const diff = await generateDiff(buildEnvironment(files), $("goal").value, { apiKey: key, model: MODEL, callLlm: streamingCallLlm("Generating diff") });
const parsed = parseDiffPerFile(diff);
if (!diff.trim() || !parsed.length) {
renderDiff(diff || "");
$("result").textContent = "⚠ The model returned no applicable diff. Try rephrasing the goal.";
} else {
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 }),
});
renderDiff(diff);
const result = updated[path] ?? "(file was deleted)";
if (result === content) {
$("result").textContent = "⚠ smartapply produced no change.";
} else if (result === "(file was deleted)") {
$("result").textContent = "⚠ smartapply deleted the file.";
} else {
$("content").value = result; // apply to the editor automatically — no button needed
$("result").textContent = result;
pushVersion(result, $("goal").value); // snapshot as a new, revisitable version
updatePlayState();
}
}
$("phase").textContent = "done";
document.querySelector("#progress .spin").style.display = "none";
} catch (e) {
$("diff").textContent = "Error: " + e.message;
$("progress").style.display = "none";
} finally {
clearInterval(timer);
$("run").disabled = false;
}
}
$("run").addEventListener("click", run);
$("goal").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); if (!$("run").disabled) run(); } });
// ---------- play modal: render the current file in a sandboxed iframe ----------
const playModal = $("playmodal"), playFrame = $("playframe");
// The file starts as pseudocode; Play only makes sense once it's a built HTML game.
const looksLikeHtml = (s) => /<!doctype/i.test(s) || /<\/?(html|head|body|script|canvas|svg|div|main|style|h1|button)\b/i.test(s);
function updatePlayState() {
const ok = looksLikeHtml($("content").value);
$("play").disabled = !ok;
$("play").textContent = ok ? "▶ Play this file" : "▶ Play (build it first)";
$("play").title = ok ? "" : "This file is still pseudocode — run “Diff & apply” to build the game, then Play.";
}
// The preview runs sandboxed WITHOUT allow-same-origin, so the game can't read the
// page's stored API key. Two consequences we patch up by injecting a small preamble:
// 1. localStorage/sessionStorage throw SecurityError — shim them with in-memory stores
// (high scores etc. work for the session, just don't persist across previews).
// 2. A focused iframe swallows the keyboard — forward Esc out so the modal can close.
const PREVIEW_PREAMBLE =
`<script>(function(){function s(){var m={};return{getItem:function(k){return Object.prototype.hasOwnProperty.call(m,k)?m[k]:null;},setItem:function(k,v){m[k]=String(v);},removeItem:function(k){delete m[k];},clear:function(){m={};},key:function(i){return Object.keys(m)[i]||null;},get length(){return Object.keys(m).length;}};}` +
`try{window.localStorage;}catch(e){try{Object.defineProperty(window,"localStorage",{value:s(),configurable:true});}catch(_){}}` +
`try{window.sessionStorage;}catch(e){try{Object.defineProperty(window,"sessionStorage",{value:s(),configurable:true});}catch(_){}}})();` +
`addEventListener("keydown",function(e){if(e.key==="Escape"){e.preventDefault();parent.postMessage("__play_close__","*");}});<\/script>`;
// Inject the preamble early (kept after the doctype so standards mode is preserved).
function withPreamble(html) {
if (/<head[^>]*>/i.test(html)) return html.replace(/<head[^>]*>/i, (m) => m + PREVIEW_PREAMBLE);
if (/<!doctype[^>]*>/i.test(html)) return html.replace(/<!doctype[^>]*>/i, (m) => m + PREVIEW_PREAMBLE);
if (/<html[^>]*>/i.test(html)) return html.replace(/<html[^>]*>/i, (m) => m + PREVIEW_PREAMBLE);
return PREVIEW_PREAMBLE + html;
}
function openPlay() {
if ($("play").disabled) return;
// Focus the game so Enter / arrows / space reach it immediately — no clicking needed.
playFrame.onload = () => { try { playFrame.contentWindow.focus(); } catch {} };
playFrame.srcdoc = withPreamble($("content").value);
playModal.classList.add("open");
playFrame.focus();
}
$("content").addEventListener("input", updatePlayState);
function closePlay() { playModal.classList.remove("open"); playFrame.srcdoc = ""; }
$("play").addEventListener("click", openPlay);
$("playclose").addEventListener("click", closePlay);
playModal.addEventListener("click", (e) => { if (e.target === playModal) closePlay(); });
addEventListener("keydown", (e) => { if (e.key === "Escape" && playModal.classList.contains("open")) closePlay(); });
addEventListener("message", (e) => { if (e.source === playFrame.contentWindow && e.data === "__play_close__") closePlay(); });
// ---------- version history ----------
// Every successful "Diff & apply" snapshots the result as a new version. v0 is the
// starting notes (pseudocode — not playable); later versions are built files you can
// click to revisit and Play. The strip stays hidden until the first build exists.
let versions = []; // [{ content, goal }] — v0 = seed, then one per applied diff
let curVer = 0;
function renderVersions() {
const wrap = $("versions");
wrap.innerHTML = "";
if (versions.length <= 1) return; // nothing to switch between until the first build
const label = document.createElement("span");
label.className = "vlabel"; label.textContent = "versions:";
wrap.appendChild(label);
versions.forEach((v, i) => {
const seed = i === 0;
const playable = !seed && looksLikeHtml(v.content);
const b = document.createElement("button");
b.className = "ver" + (i === curVer ? " cur" : "") + (seed ? " seed" : "");
b.append(seed ? "v0 · seed" : "v" + i);
if (playable) { const p = document.createElement("span"); p.className = "play"; p.textContent = "▶"; b.appendChild(p); }
b.title = seed ? "starting notes — build it first" : (v.goal ? "goal: " + v.goal : "built version " + i);
b.addEventListener("click", () => selectVersion(i));
wrap.appendChild(b);
});
}
function selectVersion(i) {
if (i < 0 || i >= versions.length || i === curVer) return;
curVer = i;
$("content").value = versions[i].content;
updatePlayState();
renderVersions();
}
function pushVersion(content, goal) {
// A build off an older version branches: drop anything after the one being viewed.
versions = versions.slice(0, curVer + 1);
versions.push({ content, goal });
curVer = versions.length - 1;
renderVersions();
}
// ---------- boot ----------
(async () => {
renderModelRow("diff"); renderModelRow("apply");
versions = [{ content: $("content").value, goal: null }]; curVer = 0; renderVersions();
try { await handleRedirect(); } catch (e) { $("status").textContent = "sign-in error: " + e.message; }
renderAuth();
updatePlayState();
loadModels(); // populate prices/tags (and warm the picker) in the background
})();
</script>
</body>
</html>