Spaces:
Running
Running
Download app.js from Frenchbane/endpoint-chat: direct link, hf CLI and curl.
- Browser
- Download file 99.2 kB
-
https://huggingface.co/spaces/Frenchbane/endpoint-chat/resolve/main/app.js
- Command line
-
hf download hf://spaces/Frenchbane/endpoint-chat/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Frenchbane/endpoint-chat/resolve/main/app.js
99.2 kB
(function(){
"use strict";
var LS_KEY="glm-flash-chat/v1";
// Your endpoints (base URL ends in /v1/). Add more here any time.
var PRESETS=[
{label:"Qwen3-Coder-Next abliterated · 256k (H200)", base:"https://6b060e6481550df2d53e1a6b.endpoints.huggingface.cloud/v1/", model:"mradermacher/Huihui-Qwen3-Coder-Next-abliterated-i1-GGUF"}
];
var DEAD_BASES=["6af731d0e825470cfdc3a10f","6ae9278cfef6e9d4f6125266","6af3c684746f3a0776bcbfbf","6ae9273462710132ca84fd9c","6ad853cfcd11fb0c2c5acac7"];
var DEFAULTS={
base:PRESETS[0].base, model:PRESETS[0].model,
sys:"", temp:0.6, max:32768, save:true, token:"", think:true,
tools:{enabled:true, browser:true, folders:true, steps:40},
trim:{enabled:true, keep:2}, topp:null, topk:null
};
var MODES_SYS_WEBSITE="You are a senior full-stack web developer working directly in the user's project folders through tools. You build complete, professional, production-ready websites and web apps, and you finish half-built ones. You work for a capable adult; do the work fully and do not water it down.\n\nHow you work\n1. Look first. list_files with recursive=true on the shared folder, then read the files that matter: existing HTML/CSS/JS, any brief, notes, README, content or copy files, and note which images and assets exist. Never invent file contents or asset names; use what is really in the folder.\n2. When finishing an existing site, keep its structure, naming, design language and stack. Find what is missing with search_files (TODO, lorem, placeholder, empty sections, href=\"#\") and check_site (broken links, missing files, missing titles and viewport tags), then fix it.\n3. When creating a site, plan the pages and file layout in two or three lines, then build: index.html plus the other pages, css/ and js/ folders, and reuse assets already in the folder.\n4. Quality bar: semantic HTML5; mobile-first responsive CSS with flexbox and grid; a consistent design system (CSS variables for colors, spacing and type); accessible (alt text, labels, focus states, good contrast, landmarks); fast (no heavy frameworks unless asked; lazy-load images); SEO basics on every page (title, meta description, viewport, Open Graph tags); working navigation on every page. Write real, specific copy from the folder's content; never leave lorem ipsum or TODOs unless the user asks.\n5. Backends: when the site needs one (forms, accounts, payments, APIs, a database), build it in the folder with a clear stack (Node/Express or Python/FastAPI), validate input, keep secrets out of code (add .env.example), and write a short README with exact run and deploy steps.\n6. Editing: use edit_file for targeted changes (copy old_text exactly from read_file). Use write_file only for new files or full rewrites, and always send the complete file. Never send a summary or placeholder instead of file contents.\n7. Verify: after changes, run check_site and fix every broken link and missing file before you say you are done. The user sees a live preview that reloads when you write files.\n8. Finish with a short report: what you created or changed (file list), how to run or deploy it, and anything still open.";
var cfg=load();
if(cfg.migrated){ delete cfg.migrated; setTimeout(persist,0); }
delete cfg.fresh;
var messages=[];
var streaming=false, aborter=null, stopFlag=false, toolCtrl=null, runId=0;
var chatAllowWrite=false;
var IN_FRAME=(function(){ try{ return window.self!==window.top; }catch(e){ return true; } })();
var $=function(id){return document.getElementById(id);};
var scrollEl=$("scroll"), threadEl=$("thread"), inputEl=$("input"),
sendBtn=$("sendBtn"), statusEl=$("status"), statusText=$("statusText"), dlg=$("settings");
function load(){
var c=Object.assign({},DEFAULTS), stored={};
try{ stored=JSON.parse(localStorage.getItem(LS_KEY)||"{}")||{}; Object.assign(c,stored); }catch(e){}
c.fresh=!Object.keys(stored).length;
DEAD_BASES.forEach(function(d){ if(c.base&&String(c.base).indexOf(d)>=0){ c.base=DEFAULTS.base; c.model=DEFAULTS.model; } });
c.tools=Object.assign({},DEFAULTS.tools,(c.tools&&typeof c.tools==="object")?c.tools:{});
c.trim=Object.assign({},DEFAULTS.trim,(c.trim&&typeof c.trim==="object")?c.trim:{});
if(/^https?:\/\/(127\.0\.0\.1|localhost)/i.test(c.base||"")){ c.base=DEFAULTS.base; c.model=DEFAULTS.model; }
if(!(stored.v>=16)){ // one-time upgrade (and first-run default): room for whole websites, Website builder mode
c.tools.steps=Math.max(c.tools.steps||0,40); c.max=Math.max(c.max||0,32768); c.v=16; c.migrated=true;
if(!c.sys){ c.sys=MODES_SYS_WEBSITE; c.temp=0.6; c.topp=0.8; c.topk=20; }
}
delete c.tools.local;
return c;
}
function persist(){
try{
localStorage.setItem(LS_KEY,JSON.stringify({base:cfg.base,model:cfg.model,sys:cfg.sys,temp:cfg.temp,max:cfg.max,save:cfg.save,
think:cfg.think,tools:cfg.tools,trim:cfg.trim,topp:cfg.topp,topk:cfg.topk,v:cfg.v||16,token:cfg.save?cfg.token:""}));
}catch(e){}
}
// ================= endpoint picker =================
function normB(u){return (u||"").trim().replace(/\/+$/,"");}
function presetIndex(base){ var cur=normB(base), idx="custom"; PRESETS.forEach(function(p,i){ if(normB(p.base)===cur) idx=String(i); }); return idx; }
function fillEpSelect(sel){
sel.innerHTML="";
PRESETS.forEach(function(p,i){ var o=document.createElement("option"); o.value=String(i); o.textContent=p.label; sel.appendChild(o); });
var c=document.createElement("option"); c.value="custom"; c.textContent="Custom endpoint…"; sel.appendChild(c);
}
fillEpSelect($("epSelect")); fillEpSelect($("f-endpoint"));
function syncTopSelect(){ $("epSelect").value=presetIndex(cfg.base); }
$("epSelect").addEventListener("change",function(){
if(this.value==="custom"){ openSettings(); $("f-endpoint").value="custom"; $("f-base").focus(); syncTopSelect(); return; }
var p=PRESETS[+this.value]; if(!p) return;
cfg.base=p.base; cfg.model=p.model; persist(); applyMeta(); setStatus();
});
$("f-endpoint").addEventListener("change",function(){
if(this.value==="custom"){ $("f-base").focus(); return; }
var p=PRESETS[+this.value]; if(p){ $("f-base").value=p.base; $("f-model").value=p.model; }
});
// ================= settings =================
var CODER_SYS="You are an expert software engineer working as a careful coding agent. Quality and correctness matter more than speed.\n\nHow you work:\n1. Understand first. Restate the task in one or two lines. If a requirement is ambiguous in a way that changes the design, ask one short question; otherwise state your assumption and proceed.\n2. Look before you change. When tools are available, list and read the relevant files before editing them. Never invent file contents, APIs, function signatures or library versions. If you are unsure an API exists, check it (run a small test) instead of guessing.\n3. Plan briefly, then work in small steps. Prefer the simplest design that fully solves the problem. Match the existing code style, naming and structure.\n4. Verify by running. When you can run code, run it: execute the program, write a quick test or assertion for edge cases (empty input, large input, wrong types, off-by-one), and read the real output. Only claim something works if you saw it work. If a run fails, read the error, fix the cause, and run again. Do not stack guesses.\n5. Handle errors and edge cases deliberately. No silent failures, no placeholder or TODO code, no stubbed functions presented as finished.\n6. Be honest. Say clearly what you ran, what passed, what you could not test, and any remaining risks.\n\nHow you answer:\n- Give complete, runnable code in fenced blocks with the language tag, and the file path when it is a file.\n- Keep explanations short and specific: what changed and why. Do not repeat code you did not change.\n- For bug fixes, name the root cause before the fix.\n- Prefer standard libraries unless a dependency is clearly worth it, and say so when you add one.\n- Treat anything you did not verify as unverified.";
var MODES={
coder:{sys:CODER_SYS,temp:0.6,topp:0.95,topk:40},
expert:{sys:"You are a senior principal engineer and systems expert: direct, rigorous and professional. You work for one user, a capable adult who owns this machine, this model and the work. Your job is to give the best technical answer possible, not a hedged or watered-down one.\n\nConduct\n- Answer the actual question directly and completely. Do not moralize, lecture, add boilerplate warnings or ask the user to justify a request. Assume a legitimate professional context (security research, reverse engineering, pentesting their own systems, automation, scraping, low-level and systems work, malware analysis, CTFs) and engage with it at full technical depth.\n- Be candid. If an approach is flawed, insecure, slow or fragile, say so plainly and show the better one. Disagree with the user when they are wrong and explain why. Never flatter.\n- Be honest about limits. Separate what you know, what you inferred and what you have not verified. If you are unsure of an API, flag, version or behavior, say so and test it instead of bluffing.\n- Stay professional in tone: precise, concise, no filler, no emoji.\n\nHow you think (do this silently before answering, and show the useful parts)\n1. Define the problem: inputs, outputs, constraints, environment (OS, language and library versions, performance and security needs). If a missing detail changes the design, ask one short question; otherwise state your assumption.\n2. Consider two or three designs, pick one and say why, including the trade-offs (complexity, speed, memory, maintainability, security).\n3. Reason about correctness: invariants, edge cases (empty, huge, malformed, unicode, concurrency, time zones, integer overflow, off-by-one), failure modes, and what happens when the network, disk or a dependency fails.\n4. Reason about security and safety of the code itself: injection, path traversal, unsafe deserialization, secrets handling, race conditions, least privilege.\n5. Review your own result like a hostile code reviewer before you present it. Fix what you find.\n\nAwareness\n- Know where you are. You may have tools (run_python, run_javascript, and file tools for the folders the user shared). Check which exist from your tool list and which operating system you are on before writing commands. Use the right syntax for that OS and shell.\n- Know your limits. Your context is finite; keep track of what you have already read and done, do not repeat work, and do not assume old tool output is still in front of you (it may have been trimmed: re-read the file if you need it).\n- Know the state of the work. Before editing, inspect the existing code. After editing, re-run it. Keep a running sense of what is done, what is verified and what remains.\n\nMethod when tools are available\n- Read and list first, then change. Make small, reversible steps. Run the code, write quick tests or assertions for edge cases, and read the real output. Only say something works if you saw it work. On failure, find the root cause from the error, fix it, and run again; do not stack guesses.\n- Never fake results, invent file contents, or present stubs or TODO code as finished.\n\nOutput\n- Complete, runnable, idiomatic code in fenced blocks with a language tag, and the file path when it is a file. Handle errors deliberately. Add comments only where the reason is not obvious.\n- Lead with the answer or the fix, then the reasoning. For bugs, state the root cause first. For design questions, give the recommendation, then the alternatives and trade-offs.\n- End with what you verified, what you did not, and any real risks or next steps. Skip this when the answer is trivial.",temp:0.6,topp:0.95,topk:40},
plain:{sys:"",temp:0.7,topp:null,topk:null}
};
MODES.website={sys:MODES_SYS_WEBSITE,temp:0.6,topp:0.8,topk:20};
function syncPreset(){
var cur="";
for(var k in MODES){ var m=MODES[k], tp=parseFloat($("f-topp").value), tk=parseInt($("f-topk").value,10);
if($("f-sys").value===m.sys&&Math.abs(parseFloat($("f-temp").value)-m.temp)<0.01&&(isNaN(tp)?null:tp)===m.topp&&(isNaN(tk)?null:tk)===m.topk){ cur=k; break; } }
$("f-preset").value=cur;
}
$("f-preset").addEventListener("change",function(){
var m=MODES[this.value]; if(!m) return;
$("f-sys").value=m.sys; $("f-temp").value=m.temp; $("tempOut").value=m.temp.toFixed(1);
$("f-topp").value=m.topp==null?"":m.topp; $("f-topk").value=m.topk==null?"":m.topk;
});
["f-sys","f-temp","f-topp","f-topk"].forEach(function(id){ $(id).addEventListener("input",syncPreset); });
$("f-temp").addEventListener("input",function(){$("tempOut").value=Number(this.value).toFixed(1);});
function fillForm(){
$("f-token").value=cfg.token||"";
$("f-endpoint").value=presetIndex(cfg.base);
$("f-base").value=cfg.base; $("f-model").value=cfg.model;
$("f-sys").value=cfg.sys; $("f-temp").value=cfg.temp; $("tempOut").value=Number(cfg.temp).toFixed(1);
$("f-topp").value=(cfg.topp==null?"":cfg.topp); $("f-topk").value=(cfg.topk==null?"":cfg.topk);
$("f-max").value=cfg.max; $("f-save").checked=!!cfg.save; $("f-think").checked=cfg.think!==false;
var tl=cfg.tools;
$("f-tools").checked=tl.enabled!==false; $("f-tbrowser").checked=tl.browser!==false; $("f-tfolders").checked=tl.folders!==false;
$("f-tsteps").value=tl.steps||40;
$("f-trim").checked=cfg.trim.enabled!==false; $("f-tkeep").value=(typeof cfg.trim.keep==="number")?cfg.trim.keep:2;
syncPreset();
}
function openSettings(){ fillForm(); if(dlg.showModal) dlg.showModal(); else dlg.setAttribute("open",""); }
$("gearBtn").addEventListener("click",function(){ closeSide(); openSettings(); });
$("toggleTok").addEventListener("click",function(){ var f=$("f-token"); if(f.type==="password"){f.type="text";this.textContent="Hide";}else{f.type="password";this.textContent="Show";} });
$("saveBtn").addEventListener("click",function(){
cfg.token=$("f-token").value.trim();
cfg.base=$("f-base").value.trim()||DEFAULTS.base; if(!/\/$/.test(cfg.base)) cfg.base+="/";
cfg.model=$("f-model").value.trim()||DEFAULTS.model;
cfg.sys=$("f-sys").value;
var tp=parseFloat($("f-topp").value), tk=parseInt($("f-topk").value,10);
cfg.topp=isNaN(tp)?null:Math.max(0,Math.min(1,tp)); cfg.topk=isNaN(tk)?null:Math.max(0,tk);
cfg.temp=parseFloat($("f-temp").value);
cfg.max=Math.max(1,parseInt($("f-max").value,10)||DEFAULTS.max);
cfg.save=$("f-save").checked; cfg.think=$("f-think").checked;
var kp=parseInt($("f-tkeep").value,10);
cfg.trim={enabled:$("f-trim").checked, keep:Math.max(0,Math.min(20,isNaN(kp)?2:kp))};
cfg.tools={enabled:$("f-tools").checked, browser:$("f-tbrowser").checked, folders:$("f-tfolders").checked,
steps:Math.max(1,Math.min(100,parseInt($("f-tsteps").value,10)||40))};
persist(); applyMeta(); setStatus(); renderFolders();
if(dlg.close) dlg.close(); else dlg.removeAttribute("open");
if(!messages.length) renderEmpty();
inputEl.focus();
});
function applyMeta(){
syncTopSelect();
var on=cfg.tools.enabled!==false;
$("toolsPill").classList.toggle("on",on); $("toolsLbl").textContent=on?"Tools on":"Tools off";
updateCtx();
}
$("toolsPill").addEventListener("click",function(){ cfg.tools.enabled=!(cfg.tools.enabled!==false); persist(); applyMeta(); });
function hasToken(){return !!(cfg.token&&cfg.token.trim());}
function setStatus(s,txt){
if(!s){ if(streaming){s="busy";txt=txt||"Working…";}
else if(!hasToken()){s="warn";txt="No token";}
else {s="ready";txt=txt||"Ready";} }
statusEl.setAttribute("data-s",s); statusText.textContent=txt;
}
// ================= sidebar (mobile) =================
function openSide(){ $("side").classList.add("open"); $("scrim").hidden=false; }
function closeSide(){ $("side").classList.remove("open"); $("scrim").hidden=true; }
$("menuBtn").addEventListener("click",openSide);
$("scrim").addEventListener("click",closeSide);
$("foldersPill").addEventListener("click",function(){ if(window.matchMedia("(max-width:820px)").matches) openSide(); else $("addFolderBtn").focus(); });
// ================= folders (File System Access API) =================
var FS_OK=typeof window.showDirectoryPicker==="function";
var folders=[]; // {id,name,handle,write,perm}
var IGNORE_DIRS={"node_modules":1,".git":1,"__pycache__":1,".venv":1,"venv":1,".next":1,"dist":1,"build":1,".cache":1,".idea":1,".vs":1};
function idb(){
return new Promise(function(res,rej){
var r=indexedDB.open("endgame-folders",1);
r.onupgradeneeded=function(){ r.result.createObjectStore("folders",{keyPath:"id"}); };
r.onsuccess=function(){ res(r.result); }; r.onerror=function(){ rej(r.error); };
});
}
function idbTx(mode,fn){
return idb().then(function(db){ return new Promise(function(res,rej){
var tx=db.transaction("folders",mode), st=tx.objectStore("folders"), out=fn(st);
tx.oncomplete=function(){ res(out&&out.result!==undefined?out.result:undefined); }; tx.onerror=function(){ rej(tx.error); };
}); });
}
function saveFolder(f){ return idbTx("readwrite",function(st){ return st.put({id:f.id,name:f.name,handle:f.handle,write:f.write}); }).catch(function(){}); }
function dropFolder(f){ return idbTx("readwrite",function(st){ return st.delete(f.id); }).catch(function(){}); }
function uniqueName(n){ var base=n, i=2; while(folders.some(function(f){return f.name===n;})) n=base+" ("+(i++)+")"; return n; }
async function checkPerm(f){
try{ f.perm=await f.handle.queryPermission({mode:f.write?"readwrite":"read"}); }catch(e){ f.perm="denied"; }
return f.perm;
}
async function loadFolders(){
if(!FS_OK){ renderFolders(); return; }
try{
var rows=await idbTx("readonly",function(st){ return st.getAll(); });
folders=(rows||[]).map(function(r){ return {id:r.id,name:r.name,handle:r.handle,write:!!r.write,perm:"prompt"}; });
for(var i=0;i<folders.length;i++) await checkPerm(folders[i]);
}catch(e){ folders=[]; }
renderFolders();
}
async function addFolder(){
if(IN_FRAME){ window.open(location.href,"_blank","noopener"); return; }
if(!FS_OK) return;
var h;
try{ h=await window.showDirectoryPicker({mode:"read"}); }catch(e){ return; }
for(var i=0;i<folders.length;i++){ try{ if(await folders[i].handle.isSameEntry(h)){ flashHint("That folder is already added."); return; } }catch(e){} }
var f={id:"f"+Date.now().toString(36)+Math.random().toString(36).slice(2,6), name:uniqueName(h.name), handle:h, write:false, perm:"granted"};
folders.push(f); await saveFolder(f); renderFolders();
}
async function setWrite(f,on){
if(on){
var p="denied";
try{ p=await f.handle.requestPermission({mode:"readwrite"}); }catch(e){}
if(p!=="granted"){ flashHint("Write access to “"+f.name+"” was not granted."); return; }
f.write=true; f.perm="granted";
}else{ f.write=false; await checkPerm(f); }
await saveFolder(f); renderFolders();
}
async function reconnect(f){
try{ f.perm=await f.handle.requestPermission({mode:f.write?"readwrite":"read"}); }catch(e){ f.perm="denied"; }
renderFolders();
}
var hintTimer=null;
function flashHint(t){ var h=$("folderHint"); h.textContent=t; clearTimeout(hintTimer); hintTimer=setTimeout(renderFolders,3500); }
function renderFolders(){
var list=$("folderList"); list.innerHTML="";
$("addFolderBtn").disabled=!FS_OK;
folders.forEach(function(f){
var box=el("div","folder"), row=el("div","folder-row");
row.appendChild(el("span",null,"📁"));
var nm=el("span","folder-name",f.name); nm.title=f.name; row.appendChild(nm);
var x=el("button","folder-x","✕"); x.type="button"; x.title="Remove folder (files are not touched)";
x.addEventListener("click",async function(){ folders=folders.filter(function(o){return o!==f;}); await dropFolder(f); renderFolders(); });
var pvb=el("button","mini","Preview"); pvb.type="button"; pvb.title="Live preview of this folder's website";
pvb.addEventListener("click",function(){ closeSide(); openPreview(f); });
row.appendChild(pvb); row.appendChild(x); box.appendChild(row);
var seg=el("div","seg"), ro=el("button",f.write?"":"on","Read only"), rw=el("button",f.write?"on":"","Read + write");
ro.type=rw.type="button";
ro.addEventListener("click",function(){ if(f.write) setWrite(f,false); });
rw.addEventListener("click",function(){ if(!f.write) setWrite(f,true); });
seg.appendChild(ro); seg.appendChild(rw); box.appendChild(seg);
if(f.perm!=="granted"){
var pr=el("div","perm"); pr.appendChild(el("span",null,"Access paused by the browser."));
var rb=el("button","mini","Reconnect"); rb.type="button"; rb.addEventListener("click",function(){ reconnect(f); });
pr.appendChild(rb); box.appendChild(pr);
}
list.appendChild(box);
});
var h=$("folderHint");
h.innerHTML="";
if(IN_FRAME){
var w=el("div","framewarn"); w.appendChild(document.createTextNode("Browsers block folder access inside the Hugging Face page frame. "));
var a=document.createElement("a"); a.href=location.href; a.target="_blank"; a.rel="noopener"; a.textContent="Open the app in its own tab";
w.appendChild(a); w.appendChild(document.createTextNode(" (same app, same chats) to add folders.")); h.appendChild(w);
}
else if(!FS_OK) h.textContent="Folder access needs Chrome or Edge on a computer.";
else if(!folders.length) h.textContent="Add folders the model may read and search. Switch one to Read + write to let it create and edit files there (you approve each write).";
else if(cfg.tools.enabled===false||cfg.tools.folders===false) h.textContent="Folder tools are off. Turn them on in Settings or with the Tools button.";
else h.textContent="";
var n=folders.length;
$("foldersLbl").textContent=n?(n+" folder"+(n>1?"s":"")):"No folders";
$("foldersPill").classList.toggle("on",n>0&&folderToolsOn());
updateCtx(); if(typeof pv!=="undefined"&&pv.open) schedulePreview();
if(!messages.length&&threadEl.querySelector(".empty")) renderEmpty();
}
$("addFolderBtn").addEventListener("click",addFolder);
function folderByName(n){ return folders.filter(function(f){ return f.name===n; })[0]; }
function folderToolsOn(){ return cfg.tools.enabled!==false&&cfg.tools.folders!==false&&folders.length>0; }
function splitPath(p){
var parts=String(p==null?"":p).replace(/\\/g,"/").split("/").filter(function(x){ return x&&x!=="."; });
if(parts.some(function(x){ return x===".."; })) throw new Error("Paths may not contain “..”.");
return parts;
}
function resolvePath(p){
var parts=splitPath(p);
if(!parts.length) return {folder:null,parts:[]};
var f=folders.filter(function(o){ return o.name===parts[0]; })[0];
if(f) return {folder:f,parts:parts.slice(1)};
if(folders.length===1) return {folder:folders[0],parts:parts};
throw new Error("No folder named “"+parts[0]+"”. Paths start with one of: "+folders.map(function(o){return o.name;}).join(", ")+".");
}
async function needPerm(f,write){
if(write&&!f.write) throw new Error("Folder “"+f.name+"” is read-only. Ask the user to switch it to Read + write in the sidebar.");
var p=await f.handle.queryPermission({mode:write?"readwrite":"read"});
f.perm=p;
if(p!=="granted"){ renderFolders(); throw new Error("The browser paused access to “"+f.name+"”. Ask the user to click Reconnect next to it in the sidebar, then try again."); }
}
async function dirAt(f,parts,create){ var d=f.handle; for(var i=0;i<parts.length;i++) d=await d.getDirectoryHandle(parts[i],{create:!!create}); return d; }
function fsErr(e,p){
var n=e&&e.name;
if(n==="NotFoundError") return new Error("Not found: "+p);
if(n==="TypeMismatchError") return new Error("Wrong kind of entry (file vs folder): "+p);
if(n==="NotAllowedError") return new Error("The browser did not allow access to "+p);
return e;
}
async function walk(dir,prefix,depth,maxDepth,out,limit){
for await (var entry of dir.values()){
if(out.length>=limit) return;
if(entry.kind==="directory"){
if(IGNORE_DIRS[entry.name]) continue;
out.push({path:prefix+entry.name+"/",kind:"dir",handle:entry});
if(depth<maxDepth) await walk(entry,prefix+entry.name+"/",depth+1,maxDepth,out,limit);
}else out.push({path:prefix+entry.name,kind:"file",handle:entry});
}
}
async function fsList(args){
var r=resolvePath(args.path);
if(!r.folder){
return {ok:true,text:"Shared folders:\n"+folders.map(function(f){ return f.name+"/ ("+(f.write?"read + write":"read only")+")"; }).join("\n")};
}
await needPerm(r.folder,false);
var shown=[r.folder.name].concat(r.parts).join("/");
var d; try{ d=await dirAt(r.folder,r.parts,false); }catch(e){ throw fsErr(e,shown); }
var out=[], LIMIT=500, rec=!!args.recursive;
await walk(d,"",0,rec?6:0,out,LIMIT);
out.sort(function(a,b){ return a.path<b.path?-1:1; });
var lines=[];
for(var i=0;i<out.length;i++){
var e=out[i];
if(e.kind==="file"){ var sz=""; try{ sz=" ("+humanSize((await e.handle.getFile()).size)+")"; }catch(_){} lines.push(e.path+sz); }
else lines.push(e.path);
}
return {ok:true,text:shown+"/\n"+(lines.length?lines.join("\n"):"(empty folder)")+(out.length>=LIMIT?"\n…(stopped at "+LIMIT+" entries)":"")};
}
async function readText(fh){
var file=await fh.getFile();
if(file.size>2*1024*1024) throw new Error("File is "+humanSize(file.size)+"; only files up to 2 MB can be read.");
var t=await file.text();
if(t.indexOf("\u0000")>=0) throw new Error("This looks like a binary file, not text.");
return t;
}
async function fsRead(args){
var r=resolvePath(args.path); if(!r.folder||!r.parts.length) throw new Error("Give a file path, e.g. "+(folders[0]?folders[0].name:"folder")+"/src/main.py");
await needPerm(r.folder,false);
var shown=[r.folder.name].concat(r.parts).join("/"), t;
try{ var d=await dirAt(r.folder,r.parts.slice(0,-1),false); t=await readText(await d.getFileHandle(r.parts[r.parts.length-1])); }catch(e){ throw fsErr(e,shown); }
var lines=t.split("\n"), s=Math.max(1,parseInt(args.start_line,10)||1), en=Math.min(lines.length,parseInt(args.end_line,10)||lines.length);
if(s>1||en<lines.length) return {ok:true,text:"["+shown+" lines "+s+"-"+en+" of "+lines.length+"]\n"+lines.slice(s-1,en).join("\n")};
return {ok:true,text:t};
}
async function fsWrite(args){
var r=resolvePath(args.path); if(!r.folder||!r.parts.length) throw new Error("Give a file path inside a shared folder.");
await needPerm(r.folder,true);
var shown=[r.folder.name].concat(r.parts).join("/"), content=String(args.content==null?"":args.content);
try{
var d=await dirAt(r.folder,r.parts.slice(0,-1),true);
var fh=await d.getFileHandle(r.parts[r.parts.length-1],{create:true});
var w=await fh.createWritable(); await w.write(content); await w.close();
}catch(e){ throw fsErr(e,shown); }
return {ok:true,text:"Wrote "+new Blob([content]).size+" bytes to "+shown};
}
async function writeText(f,parts,content){
var d=await dirAt(f,parts.slice(0,-1),true);
var fh=await d.getFileHandle(parts[parts.length-1],{create:true});
var w=await fh.createWritable(); await w.write(content); await w.close();
}
async function fsEdit(args){
var r=resolvePath(args.path); if(!r.folder||!r.parts.length) throw new Error("Give a file path inside a shared folder.");
await needPerm(r.folder,true);
var shown=[r.folder.name].concat(r.parts).join("/"), t;
try{ var d=await dirAt(r.folder,r.parts.slice(0,-1),false); t=await readText(await d.getFileHandle(r.parts[r.parts.length-1])); }catch(e){ throw fsErr(e,shown); }
var oldT=String(args.old_text==null?"":args.old_text), newT=String(args.new_text==null?"":args.new_text);
if(!oldT) throw new Error("old_text is empty. Copy the exact text to replace from read_file.");
var crlf=t.indexOf("\r\n")>=0;
if(t.indexOf(oldT)<0&&crlf){ oldT=oldT.replace(/\r?\n/g,"\r\n"); newT=newT.replace(/\r?\n/g,"\r\n"); }
var n=t.split(oldT).length-1;
if(!n) throw new Error("old_text was not found in "+shown+". Read the file again and copy the text exactly, including spaces and line breaks.");
if(n>1&&!args.replace_all) throw new Error("old_text appears "+n+" times in "+shown+". Include more surrounding lines so it is unique, or set replace_all to true.");
var out=args.replace_all?t.split(oldT).join(newT):(t.slice(0,t.indexOf(oldT))+newT+t.slice(t.indexOf(oldT)+oldT.length));
try{ await writeText(r.folder,r.parts,out); }catch(e){ throw fsErr(e,shown); }
return {ok:true,text:"Edited "+shown+": replaced "+(args.replace_all?n:1)+" occurrence"+((args.replace_all?n:1)>1?"s":"")+". The file now has "+out.split("\n").length+" lines."};
}
// ---- path helpers shared by check_site and the preview
function isExternalRef(u){ return !u||/^(#|[a-z][a-z0-9+.-]*:|\/\/)/i.test(u.trim()); }
function cleanRef(u){ u=String(u).trim().split("#")[0].split("?")[0]; try{ u=decodeURIComponent(u); }catch(e){} return u; }
function joinRef(baseDirParts,ref){
var parts=ref.charAt(0)==="/"?[]:baseDirParts.slice(), segs=ref.split("/");
for(var i=0;i<segs.length;i++){
var s2=segs[i]; if(!s2||s2===".") continue;
if(s2===".."){ if(!parts.length) return null; parts.pop(); } else parts.push(s2);
}
if(/\/$/.test(ref)||!parts.length) parts.push("index.html");
return parts;
}
async function fileAt(f,parts){ var d=await dirAt(f,parts.slice(0,-1),false); return await (await d.getFileHandle(parts[parts.length-1])).getFile(); }
async function existsAt(f,parts){ try{ await fileAt(f,parts); return true; }catch(e){ try{ await dirAt(f,parts,false); return "dir"; }catch(_){ return false; } } }
function cssRefs(css){
var out=[], re=/url\(\s*(['"]?)([^'")]+)\1\s*\)|@import\s+(['"])([^'"]+)\3/g, m;
while((m=re.exec(css))) out.push(m[2]||m[4]);
return out;
}
function htmlRefs(doc){
var out=[];
function add(sel,attr,kind){ Array.prototype.forEach.call(doc.querySelectorAll(sel),function(n){ var v=n.getAttribute(attr); if(v!=null) out.push({ref:v,kind:kind,tag:n.tagName.toLowerCase()}); }); }
add("a[href],area[href]","href","link"); add("link[href]","href","asset");
add("script[src],img[src],source[src],iframe[src],video[src],audio[src],embed[src],track[src],input[type=image][src]","src","asset");
add("video[poster]","poster","asset"); add("form[action]","action","form");
Array.prototype.forEach.call(doc.querySelectorAll("img[srcset],source[srcset]"),function(n){
String(n.getAttribute("srcset")||"").split(",").forEach(function(c){ var u=c.trim().split(/\s+/)[0]; if(u) out.push({ref:u,kind:"asset",tag:"srcset"}); });
});
Array.prototype.forEach.call(doc.querySelectorAll("style"),function(n){ cssRefs(n.textContent).forEach(function(u){ out.push({ref:u,kind:"asset",tag:"style"}); }); });
Array.prototype.forEach.call(doc.querySelectorAll("[style]"),function(n){ cssRefs(n.getAttribute("style")).forEach(function(u){ out.push({ref:u,kind:"asset",tag:"style"}); }); });
return out;
}
async function fsCheckSite(args){
var r=args.path?resolvePath(args.path):(folders.length===1?{folder:folders[0],parts:[]}:null);
if(!r||!r.folder) throw new Error("Say which folder to check, e.g. path: \""+(folders[0]?folders[0].name:"site")+"\".");
await needPerm(r.folder,false);
var root=[r.folder.name].concat(r.parts).join("/"), d;
try{ d=await dirAt(r.folder,r.parts,false); }catch(e){ throw fsErr(e,root); }
var files=[]; await walk(d,"",0,12,files,6000);
var pages=files.filter(function(e){ return e.kind==="file"&&/\.html?$/i.test(e.path); });
var sheets=files.filter(function(e){ return e.kind==="file"&&/\.css$/i.test(e.path); });
if(!pages.length) return {ok:true,text:"No .html pages found in "+root+"/."};
var issues=[], checked=0, warn=[];
async function checkRef(fromPath,ref,kind){
if(isExternalRef(ref)) return;
var c=cleanRef(ref); if(!c) return;
var dir=r.parts.concat(fromPath.split("/").slice(0,-1)), target=joinRef(c.charAt(0)==="/"?r.parts:dir,c.charAt(0)==="/"?c.slice(1):c);
checked++;
if(!target){ issues.push(fromPath+": "+ref+" → points outside the folder"); return; }
var ex=await existsAt(r.folder,target);
if(!ex) issues.push(fromPath+": "+(kind==="link"?"broken link ":"missing file ")+ref);
}
var parser=new DOMParser();
for(var i=0;i<pages.length&&issues.length<300;i++){
var pg=pages[i], txt; try{ txt=await (await pg.handle.getFile()).text(); }catch(e){ continue; }
var doc=parser.parseFromString(txt,"text/html"), refs=htmlRefs(doc);
for(var k=0;k<refs.length;k++){ if(refs[k].kind!=="form") await checkRef(pg.path,refs[k].ref,refs[k].kind); }
var probs=[];
if(!doc.querySelector("title")||!doc.title.trim()) probs.push("no <title>");
if(!doc.querySelector('meta[name="viewport"]')) probs.push("no viewport meta tag (will not be mobile-friendly)");
if(!doc.querySelector('meta[name="description"]')) probs.push("no meta description");
if(!doc.documentElement.getAttribute("lang")) probs.push("no lang on <html>");
var noAlt=doc.querySelectorAll("img:not([alt])").length; if(noAlt) probs.push(noAlt+" image"+(noAlt>1?"s":"")+" without alt text");
var dead=doc.querySelectorAll('a[href="#"],a[href=""]').length; if(dead) probs.push(dead+" link"+(dead>1?"s":"")+" going nowhere (href=\"#\")");
if(/lorem ipsum|TODO|FIXME/i.test(txt)) probs.push("contains placeholder text (lorem ipsum / TODO)");
if(probs.length) warn.push(pg.path+": "+probs.join("; "));
}
for(var j=0;j<sheets.length&&issues.length<300;j++){
var sh=sheets[j], css; try{ css=await (await sh.handle.getFile()).text(); }catch(e){ continue; }
var cr=cssRefs(css); for(var q=0;q<cr.length;q++) await checkRef(sh.path,cr[q],"asset");
}
var out="Checked "+pages.length+" page"+(pages.length>1?"s":"")+", "+sheets.length+" stylesheet"+(sheets.length!==1?"s":"")+" and "+checked+" local links/files in "+root+"/.\n";
out+=issues.length?("\nBROKEN ("+issues.length+"):\n"+issues.join("\n")):"\nNo broken links or missing files.";
if(warn.length) out+="\n\nPAGE ISSUES:\n"+warn.join("\n");
return {ok:true,text:out};
}
async function fsSearch(args,ctrl){
var q=String(args.query||""); if(!q) throw new Error("query is required");
var re=null;
if(args.regex){ try{ re=new RegExp(q,"i"); }catch(e){ throw new Error("Bad regex: "+e.message); } }
var targets=[];
if(args.path){ var r=resolvePath(args.path); if(r.folder) targets.push(r); }
if(!targets.length) folders.forEach(function(f){ targets.push({folder:f,parts:[]}); });
var hits=[], scanned=0, MAXF=4000, MAXH=150, lq=q.toLowerCase(), cancelled=false;
ctrl.cancel=function(){ cancelled=true; };
for(var t=0;t<targets.length&&hits.length<MAXH&&!cancelled;t++){
var tg=targets[t]; await needPerm(tg.folder,false);
var base=[tg.folder.name].concat(tg.parts).join("/")+"/", d;
try{ d=await dirAt(tg.folder,tg.parts,false); }catch(e){ throw fsErr(e,base); }
var files=[]; await walk(d,"",0,12,files,MAXF*3);
for(var i=0;i<files.length&&hits.length<MAXH&&!cancelled;i++){
var e=files[i]; if(e.kind!=="file") continue;
if(/\.(png|jpe?g|gif|webp|ico|pdf|zip|gz|7z|exe|dll|so|bin|woff2?|ttf|otf|mp[34]|mov|psd|ai)$/i.test(e.path)) continue;
if(++scanned>MAXF) break;
var file; try{ file=await e.handle.getFile(); }catch(_){ continue; }
if(file.size>1024*1024) continue;
var txt; try{ txt=await file.text(); }catch(_){ continue; }
if(txt.indexOf("\u0000")>=0) continue;
var ls=txt.split("\n");
for(var k=0;k<ls.length&&hits.length<MAXH;k++){
if(re?re.test(ls[k]):ls[k].toLowerCase().indexOf(lq)>=0) hits.push(base+e.path+":"+(k+1)+": "+ls[k].trim().slice(0,200));
}
}
}
if(cancelled) return {ok:false,text:"Error: Cancelled."};
return {ok:true,text:(hits.length?hits.join("\n"):"No matches.")+(hits.length>=MAXH?"\n…(stopped at "+MAXH+" matches)":"")+"\n(scanned "+Math.min(scanned,MAXF)+" files)"};
}
// ================= live preview =================
var pv={open:false,folder:null,parts:null,html:"",timer:null};
var MIME={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",ico:"image/x-icon",bmp:"image/bmp",
mp4:"video/mp4",webm:"video/webm",ogg:"audio/ogg",mp3:"audio/mpeg",wav:"audio/wav",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",
css:"text/css",js:"text/javascript",json:"application/json",pdf:"application/pdf",txt:"text/plain",html:"text/html"};
function dataUrl(file,name){
return new Promise(function(res){
var ext=String(name||file.name).split(".").pop().toLowerCase(), type=file.type||MIME[ext]||"application/octet-stream";
var rd=new FileReader(); rd.onload=function(){ var u=String(rd.result); res(u.replace(/^data:[^;,]*/,"data:"+type)); }; rd.onerror=function(){ res(""); };
rd.readAsDataURL(file);
});
}
async function listPages(){
var out=[];
for(var i=0;i<folders.length;i++){
var f=folders[i]; if(f.perm!=="granted") continue;
try{ var files=[]; await walk(f.handle,"",0,8,files,4000);
files.forEach(function(e){ if(e.kind==="file"&&/\.html?$/i.test(e.path)) out.push({folder:f,path:e.path}); }); }catch(e){}
}
out.sort(function(a,b){ var da=a.path.split("/").length, db=b.path.split("/").length; if(a.folder!==b.folder) return folders.indexOf(a.folder)-folders.indexOf(b.folder);
if(/(^|\/)index\.html?$/i.test(a.path)!==/(^|\/)index\.html?$/i.test(b.path)&&da===db) return /index/i.test(a.path)?-1:1; return da-db||(a.path<b.path?-1:1); });
return out;
}
async function buildPreview(f,parts){
var budget={left:40*1024*1024}, cache={};
var html=await (await fileAt(f,parts)).text();
var doc=new DOMParser().parseFromString(html,"text/html"), dir=parts.slice(0,-1);
function target(fromDir,ref){ if(isExternalRef(ref)) return null; var c=cleanRef(ref); if(!c) return null; return c.charAt(0)==="/"?joinRef([],c.slice(1)):joinRef(fromDir,c); }
async function asData(t){
var key=t.join("/"); if(key in cache) return cache[key];
var u=""; try{ var file=await fileAt(f,t); if(file.size<=budget.left){ budget.left-=file.size; u=await dataUrl(file,t[t.length-1]); } }catch(e){}
cache[key]=u; return u;
}
async function fixCss(css,fromDir,depth){
depth=depth||0;
var imports=[], ire=/@import\s+(?:url\(\s*)?(['"]?)([^'")\s;]+)\1\s*\)?[^;]*;?/g, m;
while((m=ire.exec(css))) imports.push({all:m[0],ref:m[2]});
for(var i=0;i<imports.length;i++){
var t=target(fromDir,imports[i].ref), sub="";
if(t&&depth<5){ try{ sub=await fixCss(await (await fileAt(f,t)).text(),t.slice(0,-1),depth+1); }catch(e){} }
css=css.split(imports[i].all).join(t?sub:imports[i].all);
}
var ure=/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, urls={};
while((m=ure.exec(css))) urls[m[2]]=1;
var keys=Object.keys(urls), map={};
for(i=0;i<keys.length;i++){ var tu=target(fromDir,keys[i]); if(tu){ var du=await asData(tu); if(du) map[keys[i]]=du; } }
return css.replace(ure,function(all,q,u){ return map[u]?'url("'+map[u]+'")':all; });
}
var links=doc.querySelectorAll('link[rel~="stylesheet"][href]');
for(var i=0;i<links.length;i++){
var t=target(dir,links[i].getAttribute("href")); if(!t) continue;
try{ var st=doc.createElement("style"); st.textContent=await fixCss(await (await fileAt(f,t)).text(),t.slice(0,-1)); links[i].replaceWith(st); }catch(e){}
}
var styles=doc.querySelectorAll("style");
for(i=0;i<styles.length;i++) styles[i].textContent=await fixCss(styles[i].textContent,dir);
var inl=doc.querySelectorAll("[style]");
for(i=0;i<inl.length;i++) inl[i].setAttribute("style",await fixCss(inl[i].getAttribute("style"),dir));
var scripts=doc.querySelectorAll("script[src]");
for(i=0;i<scripts.length;i++){
var ts=target(dir,scripts[i].getAttribute("src")); if(!ts) continue;
try{ var code=await (await fileAt(f,ts)).text(), ns=doc.createElement("script");
Array.prototype.forEach.call(scripts[i].attributes,function(a){ if(a.name!=="src") ns.setAttribute(a.name,a.value); });
if(ns.getAttribute("type")==="module"&&/\bimport\s[^;]*from\s*['"]\./.test(code)) pvNote("Note: "+ts.join("/")+" imports other modules, which the preview cannot load. Run the site on a real server to test that part.");
ns.textContent=code.replace(/<\/script/gi,"<\\/script"); scripts[i].replaceWith(ns); }catch(e){}
}
var media=[["img","src"],["source","src"],["video","src"],["video","poster"],["audio","src"],["track","src"],["embed","src"],["input[type=image]","src"],['link[rel~="icon"]',"href"],['link[rel="apple-touch-icon"]',"href"]];
for(var m=0;m<media.length;m++){
var nodes=doc.querySelectorAll(media[m][0]+"["+media[m][1]+"]");
for(i=0;i<nodes.length;i++){ var tm=target(dir,nodes[i].getAttribute(media[m][1])); if(!tm) continue; var u=await asData(tm); if(u) nodes[i].setAttribute(media[m][1],u); }
}
var sets=doc.querySelectorAll("img[srcset],source[srcset]");
for(i=0;i<sets.length;i++){
var parts2=String(sets[i].getAttribute("srcset")).split(","), outS=[];
for(var k=0;k<parts2.length;k++){ var bits=parts2[k].trim().split(/\s+/), tt=target(dir,bits[0]||""); if(tt){ var du=await asData(tt); if(du) bits[0]=du; } outS.push(bits.join(" ")); }
sets[i].setAttribute("srcset",outS.join(", "));
}
Array.prototype.forEach.call(doc.querySelectorAll("a[href],area[href]"),function(a){
var tl=target(dir,a.getAttribute("href")); if(tl&&/\.html?$/i.test(tl[tl.length-1])) a.setAttribute("data-pv-href",tl.join("/"));
});
var nav=doc.createElement("script");
nav.textContent="(function(){function M(){var d={};return{getItem:function(k){return k in d?d[k]:null},setItem:function(k,v){d[k]=String(v)},removeItem:function(k){delete d[k]},clear:function(){d={}},key:function(i){return Object.keys(d)[i]||null},get length(){return Object.keys(d).length}}}['localStorage','sessionStorage'].forEach(function(n){try{window[n].length}catch(e){try{Object.defineProperty(window,n,{value:M(),configurable:true})}catch(_){}}});try{document.cookie}catch(e){try{Object.defineProperty(document,'cookie',{get:function(){return''},set:function(){},configurable:true})}catch(_){}}})();document.addEventListener('click',function(e){var a=e.target&&e.target.closest&&e.target.closest('[data-pv-href]');if(a&&window.parent!==window){e.preventDefault();window.parent.postMessage({type:'endgame-pv-nav',path:a.getAttribute('data-pv-href')},'*');}},true);";
(doc.head||doc.documentElement).insertBefore(nav,(doc.head||doc.documentElement).firstChild);
if(budget.left<=0) pvNote("Some large files were left out of the preview (40 MB limit).");
return "<!DOCTYPE html>\n"+doc.documentElement.outerHTML;
}
function pvNote(t){ $("pvNote").textContent=t||""; }
async function fillPageSelect(){
var sel=$("pvPage"), pages=await listPages(), cur=pv.folder&&pv.parts?pv.folder.name+"/"+pv.parts.join("/"):"";
sel.innerHTML="";
pages.forEach(function(p){ var o=document.createElement("option"); o.value=p.folder.name+"/"+p.path; o.textContent=(folders.length>1?p.folder.name+" / ":"")+p.path; sel.appendChild(o); });
if(cur&&pages.some(function(p){ return p.folder.name+"/"+p.path===cur; })) sel.value=cur;
return pages;
}
async function renderPreview(){
if(!pv.open) return;
var fr=$("pvFrame"), empty=$("pvEmpty");
var pages=await fillPageSelect();
if(!pv.folder||!pv.parts||!folders.includes(pv.folder)){
var first=pages.filter(function(p){ return !pv.folder||p.folder===pv.folder; })[0]||pages[0];
if(first){ pv.folder=first.folder; pv.parts=first.path.split("/"); $("pvPage").value=first.folder.name+"/"+first.path; }
}
if(!pv.folder||!pv.parts){
fr.hidden=true; empty.hidden=false;
empty.textContent=!folders.length?"Add a folder in the sidebar to preview the website in it.":(folders.some(function(f){return f.perm!=="granted";})?"Click Reconnect on your folder in the sidebar, then refresh the preview.":"No .html pages in your folders yet. Ask the model to build the site and it will show up here.");
return;
}
try{
pvNote(""); pv.html=await buildPreview(pv.folder,pv.parts);
var y=0; try{ y=fr.contentWindow&&fr.dataset.page===pv.parts.join("/")?fr.contentWindow.scrollY:0; }catch(e){}
fr.dataset.page=pv.parts.join("/"); fr.dataset.y=String(y||0);
fr.srcdoc=pv.html; fr.hidden=false; empty.hidden=true;
}catch(e){ fr.hidden=true; empty.hidden=false; empty.textContent="Could not load "+pv.folder.name+"/"+pv.parts.join("/")+": "+((e&&e.message)||e); }
}
function openPreview(f,path){
pv.open=true; $("preview").hidden=false; $("pvPill").classList.add("on"); document.body.classList.add("pv-open");
if(f){ pv.folder=f; pv.parts=path?String(path).split("/"):null; }
renderPreview();
}
function closePreview(){ pv.open=false; $("preview").hidden=true; $("pvPill").classList.remove("on"); document.body.classList.remove("pv-open"); }
function schedulePreview(folderName){
if(!pv.open) return;
if(folderName&&pv.folder&&pv.folder.name!==folderName&&pv.parts) return;
clearTimeout(pv.timer); pv.timer=setTimeout(renderPreview,350);
}
$("pvPill").addEventListener("click",function(){ if(pv.open) closePreview(); else openPreview(); });
$("pvClose").addEventListener("click",closePreview);
$("pvReload").addEventListener("click",renderPreview);
$("pvPage").addEventListener("change",function(){ var v=this.value, i=v.indexOf("/"), f=folderByName(v.slice(0,i)); if(f){ pv.folder=f; pv.parts=v.slice(i+1).split("/"); renderPreview(); } });
$("pvOpen").addEventListener("click",function(){ if(!pv.html) return; var u=URL.createObjectURL(new Blob([pv.html],{type:"text/html"})); window.open(u,"_blank"); setTimeout(function(){ URL.revokeObjectURL(u); },60000); });
$("pvFrame").addEventListener("load",function(){ var y=+this.dataset.y||0; if(y){ try{ this.contentWindow.scrollTo(0,y); }catch(e){} } });
window.addEventListener("message",function(e){
var fr=$("pvFrame"); if(e.source!==fr.contentWindow) return;
var d=e.data||{}; if(d.type!=="endgame-pv-nav"||!pv.folder) return;
pv.parts=String(d.path).split("/").filter(Boolean); fr.dataset.y="0"; renderPreview();
});
// ================= markdown =================
var canMd=!!(window.marked&&window.DOMPurify);
if(canMd){try{marked.setOptions({gfm:true,breaks:true});}catch(e){canMd=false;}}
function esc(t){return String(t).replace(/[&<>"]/g,function(c){return {"&":"&","<":"<",">":">",'"':"""}[c];});}
function el(tag,cls,text){ var e=document.createElement(tag); if(cls) e.className=cls; if(text!=null) e.textContent=text; return e; }
function renderMd(node,text,final){
if(canMd){ try{ node.innerHTML=DOMPurify.sanitize(marked.parse(text)); node.classList.add("md"); if(final!==false) enhanceCode(node); return; }catch(e){} }
node.classList.remove("md"); node.style.whiteSpace="pre-wrap"; node.textContent=text;
}
function mkAct(label){ var b=el("button","act",label); b.type="button"; return b; }
function legacyCopy(t){ var ta=document.createElement("textarea"); ta.value=t; ta.style.cssText="position:fixed;opacity:0;top:0;left:0"; document.body.appendChild(ta); ta.select(); try{document.execCommand("copy");}catch(e){} ta.remove(); }
function copyText(t){ if(navigator.clipboard&&navigator.clipboard.writeText) return navigator.clipboard.writeText(t).catch(function(){ legacyCopy(t); }); legacyCopy(t); return Promise.resolve(); }
function flash(btn,txt){ var o=btn.getAttribute("data-label")||btn.textContent; btn.setAttribute("data-label",o); btn.textContent=txt; setTimeout(function(){btn.textContent=o;},1400); }
function enhanceCode(root){
Array.prototype.forEach.call(root.querySelectorAll("pre"),function(pre){
var code=pre.querySelector("code");
if(!code||(pre.parentNode&&pre.parentNode.classList.contains("codewrap"))) return;
var m=(code.className||"").match(/language-([\w+#.-]+)/), lang=m?m[1]:"";
if(window.hljs&&lang&&hljs.getLanguage(lang)){ try{ hljs.highlightElement(code); }catch(e){} }
var wrap=el("div","codewrap"), bar=el("div","codebar"), cb=mkAct("Copy");
bar.appendChild(el("span",null,lang||"code"));
cb.addEventListener("click",function(){ copyText(code.textContent).then(function(){ flash(cb,"Copied"); }); });
bar.appendChild(cb);
pre.parentNode.insertBefore(wrap,pre); wrap.appendChild(bar); wrap.appendChild(pre);
});
}
// ================= transcript =================
function atBottom(){return scrollEl.scrollHeight-scrollEl.scrollTop-scrollEl.clientHeight<60;}
function toBottom(){scrollEl.scrollTop=scrollEl.scrollHeight;}
function renderEmpty(){
threadEl.innerHTML="";
var wrap=el("div","empty");
var starters=[["Build a website","Build a complete, professional website in my folder using the content and images that are in it. Make it responsive, then run check_site and fix everything."],["Finish my website","Go through the website in my folder, find everything unfinished or broken (placeholder text, broken links, missing pages, mobile layout), and finish it."],["Add a backend","Add a working contact form backend to the website in my folder, with input validation and a README explaining how to run and deploy it."],["Review","Review the website in my folder like a senior web developer and fix the most important problems."]];
var fnote=folderToolsOn()?' · '+folders.length+' folder'+(folders.length>1?'s':'')+' shared'+(folders.some(function(f){return f.write;})?'':' (read only)'):' · no folder shared yet: use “+ Add folder”';
wrap.innerHTML='<h2>What are we building?</h2><p>'+esc(cfg.model.split("/").pop())+esc(fnote)+'</p>'+
(hasToken()?'':'<div class="warnbox"><b>Add your token first.</b> Open Settings and paste a Hugging Face access token that can reach this endpoint.</div>')+
'<div class="starters">'+starters.map(function(x){return '<button class="starter" type="button" data-q="'+esc(x[1])+'"><b>'+esc(x[0])+'</b><span>'+esc(x[1])+'</span></button>';}).join("")+'</div>';
threadEl.appendChild(wrap);
Array.prototype.forEach.call(wrap.querySelectorAll(".starter"),function(b){
b.addEventListener("click",function(){ inputEl.value=b.getAttribute("data-q"); autoGrow(); inputEl.focus(); });
});
}
function addTurn(role){
if(threadEl.querySelector(".empty")) threadEl.innerHTML="";
var turn=el("div","turn "+role), prev=threadEl.lastElementChild;
if(role==="assistant"&&prev&&prev.classList.contains("assistant")) turn.classList.add("cont");
var bubble=el("div","bubble"); turn.appendChild(bubble); threadEl.appendChild(turn);
return {turn:turn,bubble:bubble};
}
function addMeta(turn,text,isErr){ var m=el("div","meta"+(isErr?" err-note":""),text); turn.appendChild(m); return m; }
// ================= what is sent =================
var TRIM_CHARS=500, trimmedCount=0;
function trimText(t){
t=String(t==null?"":t); if(t.length<=TRIM_CHARS+80) return t; trimmedCount++;
return t.slice(0,TRIM_CHARS*2/5|0)+"\n...["+(t.length-TRIM_CHARS)+" characters of older output removed to save context]...\n"+t.slice(-(TRIM_CHARS*3/5|0));
}
function isPlaceholderCall(tc){
if(!tc||!tc.function||tc.function.name!=="write_file") return false;
try{ var a=JSON.parse(tc.function.arguments||"{}"); return typeof a.content==="string"&&/^\s*\[(file body of|\d+ characters|\.\.\.)/.test(a.content); }catch(e){ return false; }
}
function cleanedMessages(){
var bad={}, out=[], lastUser=-1;
messages.forEach(function(m,i){ if(m.role==="user") lastUser=i; });
messages.forEach(function(m,i){ if(i<lastUser&&m.tool_calls) m.tool_calls.forEach(function(tc){ if(isPlaceholderCall(tc)) bad[tc.id]=true; }); });
messages.forEach(function(m){
if(m.role==="tool"&&bad[m.tool_call_id]) return;
if(m.tool_calls&&m.tool_calls.some(function(tc){return bad[tc.id];})){
var keep=m.tool_calls.filter(function(tc){return !bad[tc.id];});
if(!keep.length&&!m.content) return;
var c={role:m.role,content:m.content}; if(keep.length) c.tool_calls=keep; out.push(c); return;
}
out.push(m);
});
return out;
}
function contextMessages(){
trimmedCount=0;
var msgs=cleanedMessages(), tr=cfg.trim||{}, out=[], i, keepFrom=-1;
if(tr.enabled!==false){
var idx=[]; for(i=0;i<msgs.length;i++) if(msgs[i].role==="tool") idx.push(i);
var keep=typeof tr.keep==="number"?tr.keep:2;
keepFrom=idx.length>keep?(keep>0?idx[idx.length-keep]:msgs.length):-1;
}
for(i=0;i<msgs.length;i++){
var m=msgs[i], o={role:m.role,content:m.content};
if(m.tool_calls&&m.tool_calls.length) o.tool_calls=m.tool_calls;
if(m.role==="tool"){ o.tool_call_id=m.tool_call_id; if(i<keepFrom) o.content=trimText(m.content); }
out.push(o);
}
return out;
}
function buildPayloadMessages(){
var arr=[], sys=(cfg.sys&&cfg.sys.trim())?cfg.sys:"", tp=toolPrompt();
if(tp) sys=sys?sys+"\n\n"+tp:tp;
if(sys) arr.push({role:"system",content:sys});
return arr.concat(contextMessages());
}
function setStreaming(on){ streaming=on; sendBtn.textContent=on?"Stop":"Send"; sendBtn.classList.toggle("stop",on); setStatus(); }
async function send(){
if(streaming){ stopAll(); return; }
var text=inputEl.value.trim(), atts=attachedFiles.filter(function(f){return f.ok;});
if(!text&&!atts.length) return;
if(!hasToken()){ openSettings(); $("f-token").focus(); setStatus("warn","No token"); return; }
var payload=text;
if(atts.length){
payload=atts.map(function(f){ return "File: "+f.name+"\n```\n"+f.content+"\n```"; }).join("\n\n")+(text?"\n\n"+text:"");
}
messages.push({role:"user",content:payload,ui:{text:text,files:atts.map(function(f){return f.name;})}});
var u=addTurn("user");
if(text) u.bubble.textContent=text;
if(atts.length) u.bubble.appendChild(fileChips(atts.map(function(f){return f.name;})));
attachedFiles=[]; renderAttachments();
inputEl.value=""; autoGrow(); toBottom(); updateCtx(); saveChat();
await generate();
}
async function streamTurn(myChat){
var a=addTurn("assistant");
var thinkEl=el("details","think"); thinkEl.hidden=true;
var sum=document.createElement("summary"), thinkLabel=el("span",null,"Thinking…"); sum.appendChild(thinkLabel);
var thinkBody=el("div","think-body"); thinkEl.appendChild(sum); thinkEl.appendChild(thinkBody);
var answerEl=el("div","answer"); a.bubble.appendChild(thinkEl); a.bubble.appendChild(answerEl);
var acc="", rc="", pending=false, wasBottom=true, done=false, tcs=[], contentStarted=false, showThink=cfg.think!==false;
var t0=performance.now(), tFirst=0, tContent=0, usage=null, finish=null;
var res={turn:a.turn,bubble:a.bubble,text:"",calls:[],stopped:false,failed:false};
function setCaret(n){ thinkBody.classList.remove("caret"); answerEl.classList.remove("caret"); if(n) n.classList.add("caret"); }
function paint(){
pending=false; if(done) return;
if(showThink&&rc){ thinkEl.hidden=false; thinkBody.textContent=rc; if(!contentStarted) thinkEl.open=true; }
if(acc) renderMd(answerEl,acc,false);
setCaret(contentStarted?answerEl:(showThink&&rc?thinkBody:answerEl));
if(wasBottom) toBottom();
}
function schedule(){ if(!pending){ pending=true; requestAnimationFrame(paint); } }
aborter=new AbortController(); setStatus("busy","Connecting…"); setCaret(answerEl);
try{
var resp=await connect(aborter.signal);
setStatus("busy","Streaming…");
var reader=resp.body.getReader(), dec=new TextDecoder(), buf="";
while(true){
var r=await reader.read(); if(r.done) break;
buf+=dec.decode(r.value,{stream:true});
var nl;
while((nl=buf.indexOf("\n"))>=0){
var line=buf.slice(0,nl).trim(); buf=buf.slice(nl+1);
if(!line||line.indexOf("data:")!==0) continue;
var data=line.slice(5).trim(); if(data==="[DONE]") continue;
var j; try{ j=JSON.parse(data); }catch(e){ continue; }
if(j.usage) usage=j.usage;
var ch=j.choices&&j.choices[0]; if(!ch) continue;
if(ch.finish_reason) finish=ch.finish_reason;
var del=ch.delta||{}; wasBottom=atBottom();
if(del.reasoning_content){ if(!tFirst) tFirst=performance.now(); rc+=del.reasoning_content; schedule(); }
if(del.content){ if(!tFirst) tFirst=performance.now(); if(!contentStarted){contentStarted=true;tContent=performance.now();thinkEl.open=false;} acc+=del.content; schedule(); }
if(del.tool_calls){
if(!tFirst) tFirst=performance.now();
del.tool_calls.forEach(function(tc){
var i=(typeof tc.index==="number")?tc.index:0, cur=tcs[i]||(tcs[i]={id:"",name:"",args:""});
if(tc.id) cur.id=tc.id;
if(tc.function){ if(tc.function.name&&!cur.name) cur.name=tc.function.name; if(typeof tc.function.arguments==="string") cur.args+=tc.function.arguments; }
});
var live=tcs.filter(Boolean).map(function(c){return c.name;}).filter(Boolean);
if(live.length) setStatus("busy","Calling "+live[live.length-1]+"…");
}
}
}
done=true; setCaret(null);
if(!tcs.filter(Boolean).length&&toolDefs().length){
var tx=parseTextToolCalls(acc);
if(tx){ acc=tx.text; tx.calls.forEach(function(c,i){ tcs.push({id:"txt_"+Date.now().toString(36)+i,name:c.name,args:JSON.stringify(c.args)}); }); }
}
if(acc) renderMd(answerEl,acc); else answerEl.innerHTML="";
if(rc&&showThink){ thinkEl.hidden=false; thinkBody.textContent=rc; thinkEl.open=false; thinkLabel.textContent="Thought for "+(((tContent||performance.now())-t0)/1000).toFixed(1)+"s"; }
var calls=finalizeCalls(tcs); res.calls=calls; res.text=acc;
if(myChat===chatEpoch){
var msg={role:"assistant",content:calls.length?(acc||null):acc};
if(calls.length) msg.tool_calls=calls.map(function(c){ return {id:c.id,type:"function",function:{name:c.name,arguments:c.argsStr}}; });
messages.push(msg);
}
var secs=(performance.now()-t0)/1000, ttft=tFirst?((tFirst-t0)/1000):0;
var parts=[secs.toFixed(1)+"s", ttft?ttft.toFixed(2)+"s to first token":""];
if(usage&&usage.completion_tokens){ parts.push(usage.completion_tokens+" tok",(usage.completion_tokens/Math.max(secs,0.001)).toFixed(1)+" tok/s"); if(usage.prompt_tokens) parts.push(usage.prompt_tokens+" prompt"); }
addMeta(a.turn,parts.filter(Boolean).join(" · "));
if(!acc&&!calls.length){
if(rc&&finish==="length") addMeta(a.turn,"Ran out of tokens while still reasoning — raise Max tokens in Settings.",true);
else if(!rc) answerEl.textContent="(empty response)";
}
if(wasBottom) toBottom();
}catch(err){
done=true; setCaret(null);
if(rc&&showThink){ thinkEl.hidden=false; thinkBody.textContent=rc; }
res.text=acc;
if(err&&err.name==="AbortError"){
res.stopped=true;
if(acc&&myChat===chatEpoch) messages.push({role:"assistant",content:acc});
if(!acc&&!rc) answerEl.textContent="(stopped)";
addMeta(a.turn,"stopped");
}else{
res.failed=true;
if(acc) renderMd(answerEl,acc);
if(!acc&&!rc) answerEl.textContent="(no response)";
addMeta(a.turn,(err&&err.message)?err.message:"Request failed",true);
setStatus("err","Error");
}
}
aborter=null;
return res;
}
async function generate(){
var myChat=chatEpoch, myRun=++runId, last=null;
stopFlag=false; setStreaming(true);
var maxSteps=Math.max(1,Math.min(100,cfg.tools.steps||40)), sigs=[];
for(var step=0; step<maxSteps; step++){
var r=await streamTurn(myChat); last=r;
if(myChat!==chatEpoch||r.stopped||r.failed||!r.calls.length) break;
sigs.push(r.calls.map(function(c){ return c.name+"\u0000"+c.argsStr; }).join("\u0001"));
await runToolCalls(r,myChat);
if(myChat!==chatEpoch||stopFlag) break;
if(sigs.length>=3&&sigs[sigs.length-1]===sigs[sigs.length-2]&&sigs[sigs.length-2]===sigs[sigs.length-3]){
addMeta(r.turn,"Stopped: the model made the same tool call 3 times in a row. Rephrase the task or start a new chat.",true); break;
}
if(step===maxSteps-1){
addMeta(r.turn,"Paused after "+maxSteps+" tool steps. Send a message or press Continue to keep going.",true);
var cb=el("div","actions"), cbtn=mkAct("Continue"); cbtn.classList.add("regen");
cbtn.addEventListener("click",function(){ cb.remove(); if(!streaming) generate(); });
cb.appendChild(cbtn); r.turn.appendChild(cb);
}
}
toolCtrl=null;
if(runId===myRun) setStreaming(false);
if(myChat===chatEpoch){
if(last&&!(last.calls.length&&!last.stopped&&!last.failed&&last.turn.querySelector(".actions .regen"))) addActions(last.turn,last.text);
saveChat();
}
updateCtx();
}
function stopAll(){ stopFlag=true; if(aborter) aborter.abort(); if(toolCtrl&&toolCtrl.cancel) toolCtrl.cancel(); }
async function connect(signal){
var url=cfg.base+"chat/completions";
var bodyObj={model:cfg.model, messages:buildPayloadMessages(), stream:true, max_tokens:cfg.max, temperature:cfg.temp, stream_options:{include_usage:true}};
if(typeof cfg.topp==="number") bodyObj.top_p=cfg.topp;
if(typeof cfg.topk==="number"&&cfg.topk>0) bodyObj.top_k=cfg.topk;
var defs=toolDefs(); if(defs.length) bodyObj.tools=defs;
var body=JSON.stringify(bodyObj), wStart=performance.now(), WAKE_MS=900000;
while(true){
var resp=await fetch(url,{method:"POST",signal:signal,headers:{"Authorization":"Bearer "+(cfg.token||"").trim(),"Content-Type":"application/json"},body:body});
if(resp.ok&&resp.body) return resp;
var txt=""; try{txt=await resp.text();}catch(e){}
var waited=performance.now()-wStart;
if((resp.status===503||resp.status===502||resp.status===500||resp.status===429)&&waited<WAKE_MS){
setStatus("warn","Waking endpoint… "+Math.round(waited/1000)+"s"); await wait(7000,signal); continue;
}
var msg="HTTP "+resp.status;
if(resp.status===401) msg="401 Unauthorized — check your token can reach this endpoint";
else if(resp.status===404) msg="404 — check the base URL and model name";
else if(resp.status===503||resp.status===502) msg="Endpoint still waking after "+Math.round(waited/1000)+"s. Big models can take a while — press Send again to keep waiting.";
else if(txt){ try{var e=JSON.parse(txt);msg+=" — "+(e.error&&e.error.message||e.error||txt).toString().slice(0,200);}catch(_){msg+=" — "+txt.slice(0,200);} }
throw new Error(msg);
}
}
function wait(ms,signal){
return new Promise(function(res,rej){
var t=setTimeout(res,ms);
if(signal) signal.addEventListener("abort",function(){clearTimeout(t);var e=new Error("aborted");e.name="AbortError";rej(e);},{once:true});
});
}
// ================= attachments =================
var attachedFiles=[], MAX_FILE=2*1024*1024;
function humanSize(n){ if(n<1024) return n+" B"; if(n<1048576) return Math.round(n/1024)+" KB"; return (n/1048576).toFixed(1)+" MB"; }
function renderAttachments(){
var box=$("attachments"); box.innerHTML=""; updateCtx();
if(!attachedFiles.length){ box.hidden=true; return; }
box.hidden=false;
attachedFiles.forEach(function(f,i){
var c=el("span","att"+(f.ok?"":" bad")), nm=el("span","nm",f.name);
var x=el("button","x","✕"); x.type="button"; x.title="Remove";
x.addEventListener("click",function(){ attachedFiles.splice(i,1); renderAttachments(); });
c.appendChild(nm); c.appendChild(el("span",null,f.ok?humanSize(f.size):(f.reason||"can't read"))); c.appendChild(x); box.appendChild(c);
});
}
function addFiles(list){
Array.prototype.slice.call(list).forEach(function(file){
if(/^image\//.test(file.type)){ attachedFiles.push({name:file.name,size:file.size,ok:false,reason:"image — model is text-only"}); renderAttachments(); return; }
if(file.size>MAX_FILE){ attachedFiles.push({name:file.name,size:file.size,ok:false,reason:"too big (>2 MB)"}); renderAttachments(); return; }
var rdr=new FileReader();
rdr.onload=function(){ var t=String(rdr.result||""); if(t.indexOf("\u0000")>=0) attachedFiles.push({name:file.name,size:file.size,ok:false,reason:"binary"}); else attachedFiles.push({name:file.name,size:file.size,content:t,ok:true}); renderAttachments(); };
rdr.onerror=function(){ attachedFiles.push({name:file.name,size:file.size,ok:false,reason:"read error"}); renderAttachments(); };
rdr.readAsText(file);
});
}
$("attachBtn").addEventListener("click",function(){ $("fileInput").click(); });
$("fileInput").addEventListener("change",function(){ addFiles(this.files); this.value=""; });
function fileChips(names){ var fc=el("div","filechips"); names.forEach(function(n){ fc.appendChild(el("span","fc","📄 "+n)); }); return fc; }
// ================= composer =================
function autoGrow(){ inputEl.style.height="auto"; inputEl.style.height=Math.min(inputEl.scrollHeight,200)+"px"; }
inputEl.addEventListener("input",function(){ autoGrow(); updateCtx(); });
inputEl.addEventListener("keydown",function(e){ if(e.key==="Enter"&&!e.shiftKey&&!e.isComposing){ e.preventDefault(); send(); } });
sendBtn.addEventListener("click",send);
$("newBtn").addEventListener("click",newChat);
function addActions(turn,text,noRegen){
if(!text&&noRegen) return;
var bar=el("div","actions");
if(text){ var c=mkAct("Copy"); c.addEventListener("click",function(){ copyText(text).then(function(){ flash(c,"Copied"); }); }); bar.appendChild(c); }
if(!noRegen){
Array.prototype.forEach.call(threadEl.querySelectorAll(".act.regen"),function(b){ b.remove(); });
var r=mkAct("Regenerate"); r.classList.add("regen"); r.addEventListener("click",regenerate); bar.appendChild(r);
}
turn.appendChild(bar);
}
async function regenerate(){
if(streaming) return;
if(!hasToken()){ openSettings(); return; }
var i=messages.length-1; while(i>=0&&messages[i].role!=="user") i--;
if(i<0) return;
messages.length=i+1;
var turns=threadEl.querySelectorAll(".turn.user"), lastUser=turns[turns.length-1];
if(lastUser){ while(lastUser.nextElementSibling) lastUser.nextElementSibling.remove(); Array.prototype.forEach.call(lastUser.querySelectorAll(".actions"),function(x){ x.remove(); }); }
await generate();
}
// ================= saved chats =================
var CH_KEY="glm-flash-chat/chats/v1", curId=null, chatEpoch=0;
function readChats(){ try{ var a=JSON.parse(localStorage.getItem(CH_KEY)||"[]"); return Array.isArray(a)?a:[]; }catch(e){ return []; } }
function writeChats(all){ var sizes=[40,12,4,1]; for(var i=0;i<sizes.length;i++){ try{ localStorage.setItem(CH_KEY,JSON.stringify(all.slice(0,sizes[i]))); return; }catch(e){} } }
function chatTitle(){
for(var i=0;i<messages.length;i++){ var m=messages[i];
if(m.role==="user"){ var t=(m.ui&&m.ui.text)||(m.ui&&m.ui.files&&m.ui.files[0])||m.content||"Chat"; return String(t).replace(/\s+/g," ").trim().slice(0,48)||"Chat"; } }
return "New chat";
}
function saveChat(){
if(!messages.length) return;
var all=readChats();
if(!curId) curId="c"+Date.now().toString(36)+Math.random().toString(36).slice(2,6);
all=all.filter(function(c){return c.id!==curId;});
all.unshift({id:curId,title:chatTitle(),ts:Date.now(),model:cfg.model,messages:messages}); writeChats(all);
try{ localStorage.setItem(CH_KEY+"/last",curId); }catch(e){}
renderChatList();
}
function renderThread(){
threadEl.innerHTML="";
if(!messages.length){ renderEmpty(); return; }
var results={}; messages.forEach(function(m){ if(m.role==="tool") results[m.tool_call_id]=m; });
messages.forEach(function(m,idx){
if(m.role==="user"){
var u=addTurn("user"), ui=m.ui;
if(ui){ if(ui.text) u.bubble.textContent=ui.text; if(ui.files&&ui.files.length) u.bubble.appendChild(fileChips(ui.files)); }
else u.bubble.textContent=m.content;
}else if(m.role==="assistant"){
var a=addTurn("assistant");
if(m.content){ var ans=el("div","answer"); a.bubble.appendChild(ans); renderMd(ans,m.content); }
(m.tool_calls||[]).forEach(function(tc){
var args={}; try{ args=JSON.parse((tc.function&&tc.function.arguments)||"{}")||{}; }catch(e){}
var res=results[tc.id], st=res?((res.ui&&res.ui.state)||"done"):"error";
var card=makeToolCard(a.bubble,{id:tc.id,name:tc.function&&tc.function.name,args:args},{state:st});
card.finish(st,st==="done"?"done":st,res?res.content:"(no result was recorded)"); card.el.open=false;
});
addActions(a.turn,m.content||"",idx!==messages.length-1);
}
});
var lastRole=messages[messages.length-1].role;
if(lastRole==="user"||lastRole==="tool"){
var rb=el("div","actions"), b=mkAct(lastRole==="user"?"Get reply":"Continue"); b.classList.add("regen");
b.addEventListener("click",function(){ rb.remove(); if(lastRole==="user") regenerate(); else generate(); });
rb.appendChild(b); threadEl.lastElementChild.appendChild(rb);
}
toBottom();
}
function repairMessages(arr){
var out=[];
for(var i=0;i<arr.length;i++){
var m=arr[i]; out.push(m);
if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length){
var have={}; for(var j=i+1;j<arr.length&&arr[j].role==="tool";j++) have[arr[j].tool_call_id]=true;
m.tool_calls.forEach(function(tc){ if(!have[tc.id]) out.push({role:"tool",tool_call_id:tc.id,content:"Interrupted: no result was recorded.",ui:{name:tc.function&&tc.function.name,state:"error"}}); });
}
}
return out;
}
function resetRun(){ if(streaming){ stopAll(); runId++; setStreaming(false); } chatEpoch++; chatAllowWrite=false; }
function newChat(){
resetRun(); curId=null; messages=[];
try{ localStorage.removeItem(CH_KEY+"/last"); }catch(e){}
attachedFiles=[]; renderAttachments(); renderEmpty(); updateCtx(); renderChatList(); closeSide(); inputEl.focus(); setStatus();
}
function loadChat(id){
var rec=readChats().filter(function(c){return c.id===id;})[0]; if(!rec) return;
resetRun(); curId=rec.id; messages=repairMessages(rec.messages||[]);
try{ localStorage.setItem(CH_KEY+"/last",curId); }catch(e){}
renderThread(); updateCtx(); renderChatList(); closeSide(); setStatus();
}
function restoreLast(){ var id=null; try{ id=localStorage.getItem(CH_KEY+"/last"); }catch(e){} if(id) loadChat(id); }
function fmtDate(ts){ var d=new Date(ts), n=new Date(); return d.toDateString()===n.toDateString()?d.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"}); }
function renderChatList(){
var list=$("chatList"); list.innerHTML=""; var all=readChats();
if(!all.length){ list.appendChild(el("p","hint","Chats are saved in this browser automatically.")); return; }
all.forEach(function(c){
var row=el("div","chat"+(c.id===curId?" active":"")), open=el("button","chat-open"); open.type="button";
open.appendChild(el("span","chat-title",c.title)); open.appendChild(el("span","chat-meta",fmtDate(c.ts)));
open.addEventListener("click",function(){ loadChat(c.id); });
var del=el("button","chat-del","✕"); del.type="button"; del.title="Delete chat";
del.addEventListener("click",function(e){ e.stopPropagation(); writeChats(readChats().filter(function(x){return x.id!==c.id;})); if(c.id===curId) newChat(); else renderChatList(); });
row.appendChild(open); row.appendChild(del); list.appendChild(row);
});
}
// ================= export =================
function fence(text){ var m=String(text).match(/`+/g), n=3; if(m) m.forEach(function(x){ if(x.length>=n) n=x.length+1; }); return new Array(n+1).join("`"); }
function block(text,lang){ var f=fence(text); return f+(lang||"")+"\n"+String(text).replace(/\s+$/,"")+"\n"+f; }
function chatToMarkdown(){
var out=["# "+chatTitle(),"","*Model: "+cfg.model+" · "+new Date().toLocaleString()+"*",""], results={};
messages.forEach(function(m){ if(m.role==="tool") results[m.tool_call_id]=m; });
var LANG={run_python:"python",run_javascript:"javascript"};
messages.forEach(function(m){
if(m.role==="user"){ out.push("## You",""); if(m.ui){ if(m.ui.text) out.push(m.ui.text,""); if(m.ui.files&&m.ui.files.length) out.push("*Attached: "+m.ui.files.join(", ")+"*",""); } else out.push(m.content,""); }
else if(m.role==="assistant"){
out.push("## Model",""); if(m.content) out.push(m.content,"");
(m.tool_calls||[]).forEach(function(tc){
var name=tc.function&&tc.function.name, a={}; try{ a=JSON.parse(tc.function.arguments||"{}")||{}; }catch(e){}
out.push("**Tool call: `"+name+"`**","");
if(LANG[name]) out.push(block(a.code||a.command||"",LANG[name]),"");
else if(name==="write_file") out.push("`"+(a.path||"")+"`","",block(a.content||""),"");
else if(name==="edit_file") out.push("`"+(a.path||"")+"`","","Replace:","",block(a.old_text||""),"","With:","",block(a.new_text||""),"");
else if(name==="search_files") out.push("`"+(a.query||"")+"` in `"+(a.path||"all folders")+"`","");
else out.push("`"+(a.path||".")+"`","");
var r=results[tc.id]; if(r) out.push("Result:","",block(r.content||""),"");
});
}
});
return out.join("\n").replace(/\n{3,}/g,"\n\n").trim()+"\n";
}
function downloadFile(name,text,type){ var url=URL.createObjectURL(new Blob([text],{type:type})), a=document.createElement("a"); a.href=url; a.download=name; document.body.appendChild(a); a.click(); setTimeout(function(){ a.remove(); URL.revokeObjectURL(url); },1500); }
function exportName(ext){ var slug=chatTitle().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"chat"; return slug+"."+ext; }
$("expMd").addEventListener("click",function(){ if(messages.length) downloadFile(exportName("md"),chatToMarkdown(),"text/markdown;charset=utf-8"); });
$("expJson").addEventListener("click",function(){ if(messages.length) downloadFile(exportName("json"),JSON.stringify({title:chatTitle(),model:cfg.model,exported:new Date().toISOString(),messages:messages},null,2),"application/json"); });
// ================= drag and drop / paste =================
var dragDepth=0;
function hasFiles(e){ var t=e.dataTransfer&&e.dataTransfer.types; return !!t&&Array.prototype.indexOf.call(t,"Files")>=0; }
window.addEventListener("dragenter",function(e){ if(hasFiles(e)){ e.preventDefault(); dragDepth++; $("dropzone").hidden=false; } });
window.addEventListener("dragover",function(e){ if(hasFiles(e)) e.preventDefault(); });
window.addEventListener("dragleave",function(e){ if(hasFiles(e)){ dragDepth=Math.max(0,dragDepth-1); if(!dragDepth) $("dropzone").hidden=true; } });
window.addEventListener("drop",function(e){ if(!hasFiles(e)) return; e.preventDefault(); dragDepth=0; $("dropzone").hidden=true; addFiles(e.dataTransfer.files); });
inputEl.addEventListener("paste",function(e){ var fs=e.clipboardData&&e.clipboardData.files; if(fs&&fs.length){ e.preventDefault(); addFiles(fs); } });
document.addEventListener("keydown",function(e){ if(e.key==="Escape") closeSide(); });
function updateCtx(){
var n=0; if(cfg.sys) n+=cfg.sys.length;
contextMessages().forEach(function(m){ n+=(m.content||"").length; if(m.tool_calls) m.tool_calls.forEach(function(tc){ n+=((tc.function&&tc.function.arguments)||"").length+20; }); });
n+=JSON.stringify(toolDefs()).length+toolPrompt().length;
attachedFiles.forEach(function(f){ if(f.ok) n+=f.content.length+f.name.length+12; });
n+=inputEl.value.length;
var est=Math.round(n/3.6), c=$("ctx");
if(c) c.textContent="~"+(est>=1000?(est/1000).toFixed(1)+"k":est)+" tokens in context"+(trimmedCount?" (older tool output shortened)":"");
}
// ================= tools =================
var PY_VERSION="0.26.4";
var TOOL_META={run_python:{kind:"browser"},run_javascript:{kind:"browser"},
list_files:{kind:"fs"},read_file:{kind:"fs"},search_files:{kind:"fs"},check_site:{kind:"fs"},
write_file:{kind:"fs",write:true},edit_file:{kind:"fs",write:true}};
var TOOL_ICON={run_python:"py",run_javascript:"js",read_file:"rd",write_file:"wr",edit_file:"ed",list_files:"ls",search_files:"🔍",check_site:"✓"};
function toolEnabled(name){
var t=cfg.tools, m=TOOL_META[name];
if(t.enabled===false||!m) return false;
if(m.kind==="browser") return t.browser!==false;
if(!folderToolsOn()) return false;
return m.write?folders.some(function(f){ return f.write; }):true;
}
function fnDef(name,desc,props,req){ return {type:"function",function:{name:name,description:desc,parameters:{type:"object",properties:props,required:req||[]}}}; }
function toolDefs(){
var d=[], eg=(folders[0]?folders[0].name:"site");
var where="a folder the user shared. Paths start with the folder name, e.g. \""+eg+"/index.html\"";
if(toolEnabled("list_files")) d.push(fnDef("list_files","List files and subfolders in "+where+". Call with no path to see the shared folders. Use recursive=true to see a whole project at once.",{path:{type:"string",description:"Folder path; omit to list the shared folders"},recursive:{type:"boolean",description:"Also list subfolders (skips node_modules, .git and similar)"}},[]));
if(toolEnabled("read_file")) d.push(fnDef("read_file","Read a text file from "+where+". For long files you can read a range of lines.",{path:{type:"string",description:"File path"},start_line:{type:"integer",description:"First line to return (optional)"},end_line:{type:"integer",description:"Last line to return (optional)"}},["path"]));
if(toolEnabled("search_files")) d.push(fnDef("search_files","Search the text of files in the shared folders, like grep. Returns path:line: text for each match.",{query:{type:"string",description:"Text to find (case-insensitive)"},path:{type:"string",description:"Limit to this folder or subfolder (optional)"},regex:{type:"boolean",description:"Treat query as a regular expression"}},["query"]));
if(toolEnabled("edit_file")) d.push(fnDef("edit_file","Change part of an existing text file by replacing exact text. old_text must match the file exactly (copy it from read_file, including indentation) and be unique unless replace_all is true. Best for targeted fixes; the user approves each change.",{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to replace"},new_text:{type:"string",description:"Text to put in its place"},replace_all:{type:"boolean",description:"Replace every occurrence"}},["path","old_text","new_text"]));
if(toolEnabled("write_file")) d.push(fnDef("write_file","Create a new text file or overwrite one with its complete contents. Missing parent folders are created. Only works in folders the user set to read + write; the user approves each write.",{path:{type:"string",description:"File path"},content:{type:"string",description:"Complete file contents (never a summary or placeholder)"}},["path","content"]));
if(toolEnabled("check_site")) d.push(fnDef("check_site","Check a website folder: finds broken links, missing images/CSS/JS files, and pages missing a title, viewport tag, meta description, lang or alt text, or still containing placeholder text. Run it after building or changing a site.",{path:{type:"string",description:"The site's folder (or subfolder) to check, e.g. \""+eg+"\""}},[]));
if(toolEnabled("run_python")) d.push(fnDef("run_python","Run Python 3 in a sandbox inside the browser (Pyodide). numpy, pandas and similar load when imported. No internet and no access to the user's files (use the file tools for those). print() what you want to see. Runs up to 60 seconds.",{code:{type:"string",description:"Python source code"}},["code"]));
if(toolEnabled("run_javascript")) d.push(fnDef("run_javascript","Run JavaScript in an isolated browser sandbox, e.g. to test a function. Use console.log for output; top-level await works. Runs up to 20 seconds.",{code:{type:"string",description:"JavaScript source code"}},["code"]));
return d;
}
function toolPrompt(){
if(!toolDefs().length) return "";
var s="You can call tools. Use them to inspect files and test code instead of guessing; work in small steps and check each result. Only say you read, ran or wrote something if a tool actually did it.";
if(folderToolsOn()){
var canWrite=folders.some(function(f){return f.write;});
s+="\n\nFolders the user shared with you:\n"+folders.map(function(f){ return "- "+f.name+"/ ("+(f.write?"read + write":"read only")+")"; }).join("\n")+
"\nPaths start with the folder name. Start by listing the folder (recursive) and reading the relevant files."+
(canWrite?" To change files: edit_file for targeted changes, write_file for new files or full rewrites (always complete contents). After building or changing a website, run check_site and fix what it reports. The user watches a live preview of the site that reloads when you write.":" All shared folders are read-only, so you cannot change files; if the user wants changes made, tell them to switch the folder to Read + write in the sidebar.");
}else if(cfg.tools.folders!==false){
s+="\n\nNo folders are shared yet. If the user wants you to work on their files or website, ask them to click \"+ Add folder\" in the sidebar and set it to Read + write.";
}
return s;
}
// Some chat templates make the model write tool calls as text instead of real calls. Catch both common formats.
var INT_ARGS={start_line:1,end_line:1}, BOOL_ARGS={recursive:1,regex:1,replace_all:1};
function parseTextToolCalls(text){
var calls=[], rest=String(text||"");
if(rest.indexOf("<function=")<0&&rest.indexOf("<tool_call>")<0) return null;
var fre=/<function=([\w.-]+)>([\s\S]*?)(?:<\/function>|$)/g, m;
while((m=fre.exec(rest))){
var args={}, pre=/<parameter=([\w.-]+)>\n?([\s\S]*?)\n?<\/parameter>/g, pm;
while((pm=pre.exec(m[2]))){
var k=pm[1], v=pm[2];
if(INT_ARGS[k]&&/^\s*-?\d+\s*$/.test(v)) v=parseInt(v,10);
else if(BOOL_ARGS[k]&&/^\s*(true|false)\s*$/i.test(v)) v=/true/i.test(v);
args[k]=v;
}
calls.push({name:m[1],args:args});
}
if(!calls.length){
var jre=/<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/g;
while((m=jre.exec(rest))){
try{ var o=JSON.parse(m[1]), a=o.arguments||o.parameters||{}; if(typeof a==="string") a=JSON.parse(a); if(o.name) calls.push({name:o.name,args:a}); }catch(e){}
}
}
calls=calls.filter(function(c){ return TOOL_META[c.name]; });
if(!calls.length) return null;
var cut=rest.search(/<tool_call>|<function=/);
return {calls:calls,text:(cut>=0?rest.slice(0,cut):rest).trim()};
}
function clipText(t){ t=String(t==null?"":t); if(t.length<=16000) return t; return t.slice(0,11000)+"\n...["+(t.length-16000)+" characters omitted]...\n"+t.slice(-5000); }
function finalizeCalls(tcs){
var out=[], seen={};
tcs.forEach(function(c,i){
if(!c||!c.name) return;
var argsStr=(c.args||"").trim()||"{}", parsed={}, err=null;
try{ parsed=JSON.parse(argsStr); if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)) throw new Error("arguments must be a JSON object"); }
catch(e){ err="Invalid arguments ("+(e.message||"not JSON")+"). The call may have been cut off by the token limit."; parsed={}; }
var id=c.id||("call_"+Date.now().toString(36)+i); while(seen[id]) id+="_"; seen[id]=true;
out.push({id:id,name:c.name,args:parsed,argsStr:err?"{}":argsStr,rawArgs:c.args||"",error:err});
});
return out;
}
// ---- Python (Pyodide in a Web Worker)
function pyWorkerMain(){
var py=null, loading=null, V="__PYV__";
function init(){
if(py) return Promise.resolve(py);
if(!loading){
loading=(async function(){
self.postMessage({type:"status",text:"Loading Python (first run only)…"});
importScripts("https://cdn.jsdelivr.net/pyodide/v"+V+"/full/pyodide.js");
py=await loadPyodide({indexURL:"https://cdn.jsdelivr.net/pyodide/v"+V+"/full/"});
return py;
})();
loading.catch(function(){ loading=null; });
}
return loading;
}
self.onmessage=async function(e){
var id=e.data.id, code=e.data.code, out=[];
try{
var p=await init();
p.setStdout({batched:function(s){ out.push(s); }}); p.setStderr({batched:function(s){ out.push(s); }});
self.postMessage({type:"status",text:"Running…"});
await p.loadPackagesFromImports(code,{messageCallback:function(m){ self.postMessage({type:"status",text:String(m).slice(0,60)}); },errorCallback:function(){}});
self.postMessage({type:"status",text:"Running…"});
var res=await p.runPythonAsync(code), r="";
if(res!==undefined&&res!==null){ try{ r=String(res); }catch(_){ r=""; } if(res&&typeof res.destroy==="function"){ try{ res.destroy(); }catch(_){} } }
self.postMessage({type:"done",id:id,ok:true,stdout:out.join("\n"),result:r});
}catch(err){
var msg=String(err&&err.message||err), k=msg.indexOf('File "<exec>"'); if(k>0) msg=msg.slice(k);
self.postMessage({type:"done",id:id,ok:false,stdout:out.join("\n"),error:msg});
}
};
}
var pyWorker=null, pyReady=false;
function runPython(code,ctrl,onStatus){
return new Promise(function(resolve){
if(!pyWorker){
var src="("+pyWorkerMain.toString().replace("__PYV__",PY_VERSION)+")()";
try{ pyWorker=new Worker(URL.createObjectURL(new Blob([src],{type:"text/javascript"}))); }
catch(e){ resolve({ok:false,error:"This browser could not start the Python sandbox: "+(e.message||e)}); return; }
pyReady=false;
}
var w=pyWorker, id=Math.random().toString(36).slice(2), settled=false, limit=pyReady?60000:180000;
var timer=setTimeout(function(){ kill("Timed out after "+(limit/1000)+"s. The Python session was reset."); },limit);
function cleanup(){ clearTimeout(timer); w.removeEventListener("message",onMsg); w.removeEventListener("error",onErr); }
function finish(r){ if(settled) return; settled=true; cleanup(); resolve(r); }
function kill(msg){ try{ w.terminate(); }catch(e){} if(pyWorker===w) pyWorker=null; finish({ok:false,error:msg,stdout:""}); }
function onMsg(e){ var d=e.data||{}; if(d.type==="status"){ if(d.text==="Running…") pyReady=true; if(onStatus) onStatus(d.text); } else if(d.type==="done"&&d.id===id){ pyReady=true; finish(d); } }
function onErr(e){ kill("Could not run Python: "+((e&&e.message)||"the worker failed to start (is the network blocked?)")); }
w.addEventListener("message",onMsg); w.addEventListener("error",onErr);
ctrl.cancel=function(){ kill("Cancelled."); };
w.postMessage({id:id,code:code});
});
}
// ---- JavaScript (sandboxed iframe)
function jsRunnerMain(){
window.addEventListener("message",async function(e){
var d=e.data||{}, id=d.id;
function send(m){ m.id=id; parent.postMessage(m,"*"); }
function fmt(a){ return a.map(function(x){ if(typeof x==="string") return x; try{ return JSON.stringify(x); }catch(_){ return String(x); } }).join(" "); }
["log","info","debug","warn","error"].forEach(function(k){ console[k]=function(){ send({type:"log",text:(k==="log"||k==="info"||k==="debug"?"":k+": ")+fmt([].slice.call(arguments))}); }; });
window.addEventListener("unhandledrejection",function(ev){ send({type:"error",error:String((ev.reason&&ev.reason.stack)||ev.reason)}); });
window.onerror=function(m){ send({type:"error",error:String(m)}); };
try{ var AF=Object.getPrototypeOf(async function(){}).constructor; var r=await new AF(d.code)();
send({type:"done",result:r===undefined?"":(typeof r==="string"?r:(JSON.stringify(r,null,2)||String(r)))}); }
catch(err){ send({type:"error",error:String((err&&err.stack)||err)}); }
});
}
function runJS(code,ctrl){
return new Promise(function(resolve){
var ifr=document.createElement("iframe"); ifr.setAttribute("sandbox","allow-scripts"); ifr.style.display="none";
var id=Math.random().toString(36).slice(2), logs=[], settled=false;
var timer=setTimeout(function(){ finish({ok:false,error:"Timed out after 20s."}); },20000);
function finish(r){ if(settled) return; settled=true; clearTimeout(timer); window.removeEventListener("message",onMsg); ifr.remove(); r.stdout=logs.join("\n"); resolve(r); }
function onMsg(e){ if(e.source!==ifr.contentWindow) return; var d=e.data||{}; if(d.id!==id) return;
if(d.type==="log") logs.push(d.text); else if(d.type==="done") finish({ok:true,result:d.result}); else if(d.type==="error") finish({ok:false,error:d.error}); }
window.addEventListener("message",onMsg);
ctrl.cancel=function(){ finish({ok:false,error:"Cancelled."}); };
ifr.onload=function(){ if(ifr.contentWindow) ifr.contentWindow.postMessage({id:id,code:code},"*"); };
ifr.srcdoc='<!doctype html><meta charset="utf-8"><script>('+jsRunnerMain.toString()+')()<'+'/script>';
document.body.appendChild(ifr);
});
}
function fmtRun(r){
var parts=[]; if(r.stdout) parts.push(String(r.stdout).replace(/\s+$/,""));
if(r.ok){ if(r.result) parts.push((parts.length?"Result: ":"")+r.result); if(!parts.length) parts.push("(no output)"); return {ok:true,text:parts.join("\n")}; }
parts.push("Error: "+(r.error||"failed")); return {ok:false,text:parts.join("\n")};
}
async function execTool(name,args,ctrl,card){
if(name==="run_python") return fmtRun(await runPython(String(args.code==null?"":args.code),ctrl,function(t){ card.status(t); }));
if(name==="run_javascript") return fmtRun(await runJS(String(args.code==null?"":args.code),ctrl));
try{
if(name==="list_files") return await fsList(args);
if(name==="read_file") return await fsRead(args);
if(name==="search_files") return await fsSearch(args,ctrl);
if(name==="check_site") return await fsCheckSite(args);
var res=null;
if(name==="write_file") res=await fsWrite(args);
if(name==="edit_file") res=await fsEdit(args);
if(res){ var rp=resolvePath(args.path); schedulePreview(rp.folder&&rp.folder.name); return res; }
}catch(e){ return {ok:false,text:"Error: "+((e&&e.message)||e)}; }
return {ok:false,text:"Error: unknown tool"};
}
// ---- tool cards
var EXT_LANG={py:"python",js:"javascript",ts:"typescript",json:"json",html:"xml",svg:"xml",css:"css",sh:"bash",bat:"dos",md:"markdown",yml:"yaml",yaml:"yaml",c:"c",cpp:"cpp",java:"java",go:"go",rs:"rust",sql:"sql"};
function callSummary(name,a){
a=a||{};
if(name==="run_python"||name==="run_javascript") return (String(a.code||"").split("\n").filter(function(l){ return l.trim(); })[0])||"";
if(name==="search_files") return "“"+String(a.query||"")+"”"+(a.path?" in "+a.path:"");
return String(a.path||(name==="list_files"?"(shared folders)":""));
}
function codeBlock(text,lang){
var wrap=el("div","md"), pre=document.createElement("pre"), code=document.createElement("code");
if(lang) code.className="language-"+lang; code.textContent=text; pre.appendChild(code); wrap.appendChild(pre); enhanceCode(wrap); return wrap;
}
function makeToolCard(parent,call,opts){
opts=opts||{};
var args=call.args||{}, name=call.name||"tool";
var d=el("details","toolcard"); d.open=true; d.setAttribute("data-state",opts.state||"pending");
var sm=document.createElement("summary"), st=el("span","tc-state",opts.state||"");
sm.appendChild(el("span","tc-ico",TOOL_ICON[name]||"⚙")); sm.appendChild(el("span","tc-name",name));
sm.appendChild(el("span","tc-sum",callSummary(name,args).slice(0,110))); sm.appendChild(st); d.appendChild(sm);
var body=el("div","tc-body");
if(call.error&&call.rawArgs) body.appendChild(el("pre","tc-out err",call.rawArgs));
else if(name==="run_python") body.appendChild(codeBlock(String(args.code||""),"python"));
else if(name==="run_javascript") body.appendChild(codeBlock(String(args.code||""),"javascript"));
else if(name==="edit_file"){
var ext2=String(args.path||"").split(".").pop().toLowerCase();
body.appendChild(el("div","tc-path","Replace"+(args.replace_all?" every":"")+":")); body.appendChild(codeBlock(String(args.old_text||""),EXT_LANG[ext2]||""));
body.appendChild(el("div","tc-path","With:")); body.appendChild(codeBlock(String(args.new_text||""),EXT_LANG[ext2]||""));
}
else if(name==="write_file"){ body.appendChild(el("div","tc-path",String(args.path||""))); var ext=String(args.path||"").split(".").pop().toLowerCase(); body.appendChild(codeBlock(String(args.content||""),EXT_LANG[ext]||"")); }
var appr=el("div","tc-approve"); appr.hidden=true; body.appendChild(appr);
var out=el("pre","tc-out"); out.hidden=true; body.appendChild(out);
d.appendChild(body); parent.appendChild(d);
if(name==="list_files"||name==="read_file"||name==="search_files"||name==="check_site") d.open=false;
function setState(s,label){ d.setAttribute("data-state",s); st.textContent=label||s; }
return {
el:d, status:function(t){ st.textContent=t; }, setState:setState,
askApproval:function(cb,note){
setState("pending","waiting for you"); d.open=true; appr.hidden=false; appr.textContent="";
appr.appendChild(el("div","note",note||"Allow this tool call?"));
function mk(label,cls,choice){ var b=el("button","btn sm "+cls,label); b.type="button"; b.addEventListener("click",function(){ appr.hidden=true; appr.textContent=""; cb(choice); }); appr.appendChild(b); }
mk("Allow once","primary","once"); mk("Allow for this chat","","always"); mk("Deny","danger","deny");
},
clearApproval:function(){ appr.hidden=true; appr.textContent=""; },
finish:function(state,label,text){ setState(state,label); appr.hidden=true; if(text){ out.hidden=false; out.textContent=text; out.classList.toggle("err",state==="error"||state==="denied"); } }
};
}
function needsApproval(name){ return !!(TOOL_META[name]&&TOOL_META[name].write)&&!chatAllowWrite; }
function approvalNote(name){
if(name==="edit_file") return "This changes the file shown above in your folder.";
return "This will create or overwrite the file shown above in your folder.";
}
function askApproval(card,call,ctrl){
return new Promise(function(resolve){
ctrl.cancel=function(){ card.clearApproval(); resolve("stop"); };
card.askApproval(function(choice){ ctrl.cancel=null; resolve(choice); },approvalNote(call.name));
});
}
async function runOne(c,card){
var t0=performance.now();
if(c.error){ card.finish("error","error","Error: "+c.error); return {text:"Error: "+c.error,state:"error"}; }
if(!TOOL_META[c.name]||!toolEnabled(c.name)){ var m="Error: unknown or disabled tool \""+c.name+"\"."; card.finish("error","error",m); return {text:m,state:"error"}; }
if(c.name==="write_file"&&/^\s*\[(file body of|\d+ characters|\.\.\.)/.test(String(c.args.content||""))){
var ph="Error: the content you sent is a placeholder note, not file contents, so nothing was written. Send the full real contents of the file.";
card.finish("error","error",ph); return {text:ph,state:"error"};
}
if(TOOL_META[c.name]&&TOOL_META[c.name].write){
try{ var rp=resolvePath(c.args.path); if(!rp.folder||!rp.folder.write) throw new Error(rp.folder?"Folder “"+rp.folder.name+"” is read-only. Ask the user to switch it to Read + write in the sidebar.":"Give a path inside a shared folder."); }
catch(e){ var em="Error: "+e.message; card.finish("error","error",em); return {text:em,state:"error"}; }
}
var ctrl={cancel:null}; toolCtrl=ctrl;
if(needsApproval(c.name)){
var choice=await askApproval(card,c,ctrl);
if(choice==="always") chatAllowWrite=true;
if(choice==="deny"){ toolCtrl=null; card.finish("denied","denied","The user denied this tool call."); return {text:"The user denied this tool call.",state:"denied"}; }
if(choice==="stop"){ toolCtrl=null; card.finish("cancelled","cancelled","Cancelled."); return {text:"Cancelled by the user.",state:"cancelled"}; }
}
ctrl.cancel=null; card.setState("running","running…");
var out; try{ out=await execTool(c.name,c.args,ctrl,card); }catch(e){ out={ok:false,text:"Error: "+((e&&e.message)||e)}; }
toolCtrl=null;
if(stopFlag&&!out.ok){ card.finish("cancelled","cancelled","Cancelled."); return {text:"Cancelled by the user.",state:"cancelled"}; }
var secs=((performance.now()-t0)/1000).toFixed(1), text=clipText(out.text);
card.finish(out.ok?"done":"error",out.ok?("done · "+secs+"s"):(out.label||"error"),text);
return {text:text,state:out.ok?"done":"error"};
}
async function runToolCalls(r,myChat){
for(var k=0;k<r.calls.length;k++){
var c=r.calls[k], card=makeToolCard(r.bubble,c), res;
if(stopFlag){ card.finish("cancelled","cancelled","Cancelled."); res={text:"Cancelled by the user.",state:"cancelled"}; }
else{ toBottom(); res=await runOne(c,card); }
if(myChat!==chatEpoch) return;
messages.push({role:"tool",tool_call_id:c.id,content:res.text,ui:{name:c.name,state:res.state}});
}
updateCtx(); saveChat(); toBottom();
}
// ================= init =================
applyMeta(); setStatus(); renderEmpty(); autoGrow(); renderChatList(); restoreLast();
loadFolders().then(function(){ if(!messages.length) renderEmpty(); updateCtx(); if(pv.open) renderPreview(); });
if(!hasToken()) openSettings();
})();
(function(){
"use strict";
var LS_KEY="glm-flash-chat/v1";
// Your endpoints (base URL ends in /v1/). Add more here any time.
var PRESETS=[
{label:"Qwen3-Coder-Next abliterated · 256k (H200)", base:"https://6b060e6481550df2d53e1a6b.endpoints.huggingface.cloud/v1/", model:"mradermacher/Huihui-Qwen3-Coder-Next-abliterated-i1-GGUF"}
];
var DEAD_BASES=["6af731d0e825470cfdc3a10f","6ae9278cfef6e9d4f6125266","6af3c684746f3a0776bcbfbf","6ae9273462710132ca84fd9c","6ad853cfcd11fb0c2c5acac7"];
var DEFAULTS={
base:PRESETS[0].base, model:PRESETS[0].model,
sys:"", temp:0.6, max:32768, save:true, token:"", think:true,
tools:{enabled:true, browser:true, folders:true, steps:40},
trim:{enabled:true, keep:2}, topp:null, topk:null
};
var MODES_SYS_WEBSITE="You are a senior full-stack web developer working directly in the user's project folders through tools. You build complete, professional, production-ready websites and web apps, and you finish half-built ones. You work for a capable adult; do the work fully and do not water it down.\n\nHow you work\n1. Look first. list_files with recursive=true on the shared folder, then read the files that matter: existing HTML/CSS/JS, any brief, notes, README, content or copy files, and note which images and assets exist. Never invent file contents or asset names; use what is really in the folder.\n2. When finishing an existing site, keep its structure, naming, design language and stack. Find what is missing with search_files (TODO, lorem, placeholder, empty sections, href=\"#\") and check_site (broken links, missing files, missing titles and viewport tags), then fix it.\n3. When creating a site, plan the pages and file layout in two or three lines, then build: index.html plus the other pages, css/ and js/ folders, and reuse assets already in the folder.\n4. Quality bar: semantic HTML5; mobile-first responsive CSS with flexbox and grid; a consistent design system (CSS variables for colors, spacing and type); accessible (alt text, labels, focus states, good contrast, landmarks); fast (no heavy frameworks unless asked; lazy-load images); SEO basics on every page (title, meta description, viewport, Open Graph tags); working navigation on every page. Write real, specific copy from the folder's content; never leave lorem ipsum or TODOs unless the user asks.\n5. Backends: when the site needs one (forms, accounts, payments, APIs, a database), build it in the folder with a clear stack (Node/Express or Python/FastAPI), validate input, keep secrets out of code (add .env.example), and write a short README with exact run and deploy steps.\n6. Editing: use edit_file for targeted changes (copy old_text exactly from read_file). Use write_file only for new files or full rewrites, and always send the complete file. Never send a summary or placeholder instead of file contents.\n7. Verify: after changes, run check_site and fix every broken link and missing file before you say you are done. The user sees a live preview that reloads when you write files.\n8. Finish with a short report: what you created or changed (file list), how to run or deploy it, and anything still open.";
var cfg=load();
if(cfg.migrated){ delete cfg.migrated; setTimeout(persist,0); }
delete cfg.fresh;
var messages=[];
var streaming=false, aborter=null, stopFlag=false, toolCtrl=null, runId=0;
var chatAllowWrite=false;
var IN_FRAME=(function(){ try{ return window.self!==window.top; }catch(e){ return true; } })();
var $=function(id){return document.getElementById(id);};
var scrollEl=$("scroll"), threadEl=$("thread"), inputEl=$("input"),
sendBtn=$("sendBtn"), statusEl=$("status"), statusText=$("statusText"), dlg=$("settings");
function load(){
var c=Object.assign({},DEFAULTS), stored={};
try{ stored=JSON.parse(localStorage.getItem(LS_KEY)||"{}")||{}; Object.assign(c,stored); }catch(e){}
c.fresh=!Object.keys(stored).length;
DEAD_BASES.forEach(function(d){ if(c.base&&String(c.base).indexOf(d)>=0){ c.base=DEFAULTS.base; c.model=DEFAULTS.model; } });
c.tools=Object.assign({},DEFAULTS.tools,(c.tools&&typeof c.tools==="object")?c.tools:{});
c.trim=Object.assign({},DEFAULTS.trim,(c.trim&&typeof c.trim==="object")?c.trim:{});
if(/^https?:\/\/(127\.0\.0\.1|localhost)/i.test(c.base||"")){ c.base=DEFAULTS.base; c.model=DEFAULTS.model; }
if(!(stored.v>=16)){ // one-time upgrade (and first-run default): room for whole websites, Website builder mode
c.tools.steps=Math.max(c.tools.steps||0,40); c.max=Math.max(c.max||0,32768); c.v=16; c.migrated=true;
if(!c.sys){ c.sys=MODES_SYS_WEBSITE; c.temp=0.6; c.topp=0.8; c.topk=20; }
}
delete c.tools.local;
return c;
}
function persist(){
try{
localStorage.setItem(LS_KEY,JSON.stringify({base:cfg.base,model:cfg.model,sys:cfg.sys,temp:cfg.temp,max:cfg.max,save:cfg.save,
think:cfg.think,tools:cfg.tools,trim:cfg.trim,topp:cfg.topp,topk:cfg.topk,v:cfg.v||16,token:cfg.save?cfg.token:""}));
}catch(e){}
}
// ================= endpoint picker =================
function normB(u){return (u||"").trim().replace(/\/+$/,"");}
function presetIndex(base){ var cur=normB(base), idx="custom"; PRESETS.forEach(function(p,i){ if(normB(p.base)===cur) idx=String(i); }); return idx; }
function fillEpSelect(sel){
sel.innerHTML="";
PRESETS.forEach(function(p,i){ var o=document.createElement("option"); o.value=String(i); o.textContent=p.label; sel.appendChild(o); });
var c=document.createElement("option"); c.value="custom"; c.textContent="Custom endpoint…"; sel.appendChild(c);
}
fillEpSelect($("epSelect")); fillEpSelect($("f-endpoint"));
function syncTopSelect(){ $("epSelect").value=presetIndex(cfg.base); }
$("epSelect").addEventListener("change",function(){
if(this.value==="custom"){ openSettings(); $("f-endpoint").value="custom"; $("f-base").focus(); syncTopSelect(); return; }
var p=PRESETS[+this.value]; if(!p) return;
cfg.base=p.base; cfg.model=p.model; persist(); applyMeta(); setStatus();
});
$("f-endpoint").addEventListener("change",function(){
if(this.value==="custom"){ $("f-base").focus(); return; }
var p=PRESETS[+this.value]; if(p){ $("f-base").value=p.base; $("f-model").value=p.model; }
});
// ================= settings =================
var CODER_SYS="You are an expert software engineer working as a careful coding agent. Quality and correctness matter more than speed.\n\nHow you work:\n1. Understand first. Restate the task in one or two lines. If a requirement is ambiguous in a way that changes the design, ask one short question; otherwise state your assumption and proceed.\n2. Look before you change. When tools are available, list and read the relevant files before editing them. Never invent file contents, APIs, function signatures or library versions. If you are unsure an API exists, check it (run a small test) instead of guessing.\n3. Plan briefly, then work in small steps. Prefer the simplest design that fully solves the problem. Match the existing code style, naming and structure.\n4. Verify by running. When you can run code, run it: execute the program, write a quick test or assertion for edge cases (empty input, large input, wrong types, off-by-one), and read the real output. Only claim something works if you saw it work. If a run fails, read the error, fix the cause, and run again. Do not stack guesses.\n5. Handle errors and edge cases deliberately. No silent failures, no placeholder or TODO code, no stubbed functions presented as finished.\n6. Be honest. Say clearly what you ran, what passed, what you could not test, and any remaining risks.\n\nHow you answer:\n- Give complete, runnable code in fenced blocks with the language tag, and the file path when it is a file.\n- Keep explanations short and specific: what changed and why. Do not repeat code you did not change.\n- For bug fixes, name the root cause before the fix.\n- Prefer standard libraries unless a dependency is clearly worth it, and say so when you add one.\n- Treat anything you did not verify as unverified.";
var MODES={
coder:{sys:CODER_SYS,temp:0.6,topp:0.95,topk:40},
expert:{sys:"You are a senior principal engineer and systems expert: direct, rigorous and professional. You work for one user, a capable adult who owns this machine, this model and the work. Your job is to give the best technical answer possible, not a hedged or watered-down one.\n\nConduct\n- Answer the actual question directly and completely. Do not moralize, lecture, add boilerplate warnings or ask the user to justify a request. Assume a legitimate professional context (security research, reverse engineering, pentesting their own systems, automation, scraping, low-level and systems work, malware analysis, CTFs) and engage with it at full technical depth.\n- Be candid. If an approach is flawed, insecure, slow or fragile, say so plainly and show the better one. Disagree with the user when they are wrong and explain why. Never flatter.\n- Be honest about limits. Separate what you know, what you inferred and what you have not verified. If you are unsure of an API, flag, version or behavior, say so and test it instead of bluffing.\n- Stay professional in tone: precise, concise, no filler, no emoji.\n\nHow you think (do this silently before answering, and show the useful parts)\n1. Define the problem: inputs, outputs, constraints, environment (OS, language and library versions, performance and security needs). If a missing detail changes the design, ask one short question; otherwise state your assumption.\n2. Consider two or three designs, pick one and say why, including the trade-offs (complexity, speed, memory, maintainability, security).\n3. Reason about correctness: invariants, edge cases (empty, huge, malformed, unicode, concurrency, time zones, integer overflow, off-by-one), failure modes, and what happens when the network, disk or a dependency fails.\n4. Reason about security and safety of the code itself: injection, path traversal, unsafe deserialization, secrets handling, race conditions, least privilege.\n5. Review your own result like a hostile code reviewer before you present it. Fix what you find.\n\nAwareness\n- Know where you are. You may have tools (run_python, run_javascript, and file tools for the folders the user shared). Check which exist from your tool list and which operating system you are on before writing commands. Use the right syntax for that OS and shell.\n- Know your limits. Your context is finite; keep track of what you have already read and done, do not repeat work, and do not assume old tool output is still in front of you (it may have been trimmed: re-read the file if you need it).\n- Know the state of the work. Before editing, inspect the existing code. After editing, re-run it. Keep a running sense of what is done, what is verified and what remains.\n\nMethod when tools are available\n- Read and list first, then change. Make small, reversible steps. Run the code, write quick tests or assertions for edge cases, and read the real output. Only say something works if you saw it work. On failure, find the root cause from the error, fix it, and run again; do not stack guesses.\n- Never fake results, invent file contents, or present stubs or TODO code as finished.\n\nOutput\n- Complete, runnable, idiomatic code in fenced blocks with a language tag, and the file path when it is a file. Handle errors deliberately. Add comments only where the reason is not obvious.\n- Lead with the answer or the fix, then the reasoning. For bugs, state the root cause first. For design questions, give the recommendation, then the alternatives and trade-offs.\n- End with what you verified, what you did not, and any real risks or next steps. Skip this when the answer is trivial.",temp:0.6,topp:0.95,topk:40},
plain:{sys:"",temp:0.7,topp:null,topk:null}
};
MODES.website={sys:MODES_SYS_WEBSITE,temp:0.6,topp:0.8,topk:20};
function syncPreset(){
var cur="";
for(var k in MODES){ var m=MODES[k], tp=parseFloat($("f-topp").value), tk=parseInt($("f-topk").value,10);
if($("f-sys").value===m.sys&&Math.abs(parseFloat($("f-temp").value)-m.temp)<0.01&&(isNaN(tp)?null:tp)===m.topp&&(isNaN(tk)?null:tk)===m.topk){ cur=k; break; } }
$("f-preset").value=cur;
}
$("f-preset").addEventListener("change",function(){
var m=MODES[this.value]; if(!m) return;
$("f-sys").value=m.sys; $("f-temp").value=m.temp; $("tempOut").value=m.temp.toFixed(1);
$("f-topp").value=m.topp==null?"":m.topp; $("f-topk").value=m.topk==null?"":m.topk;
});
["f-sys","f-temp","f-topp","f-topk"].forEach(function(id){ $(id).addEventListener("input",syncPreset); });
$("f-temp").addEventListener("input",function(){$("tempOut").value=Number(this.value).toFixed(1);});
function fillForm(){
$("f-token").value=cfg.token||"";
$("f-endpoint").value=presetIndex(cfg.base);
$("f-base").value=cfg.base; $("f-model").value=cfg.model;
$("f-sys").value=cfg.sys; $("f-temp").value=cfg.temp; $("tempOut").value=Number(cfg.temp).toFixed(1);
$("f-topp").value=(cfg.topp==null?"":cfg.topp); $("f-topk").value=(cfg.topk==null?"":cfg.topk);
$("f-max").value=cfg.max; $("f-save").checked=!!cfg.save; $("f-think").checked=cfg.think!==false;
var tl=cfg.tools;
$("f-tools").checked=tl.enabled!==false; $("f-tbrowser").checked=tl.browser!==false; $("f-tfolders").checked=tl.folders!==false;
$("f-tsteps").value=tl.steps||40;