(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;i1?"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=limit) return; if(entry.kind==="directory"){ if(IGNORE_DIRS[entry.name]) continue; out.push({path:prefix+entry.name+"/",kind:"dir",handle:entry}); if(depth=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=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"); 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 "); 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;j1?"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;tMAXF) 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=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\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='

What are we building?

'+esc(cfg.model.split("/").pop())+esc(fnote)+'

'+ (hasToken()?'':'
Add your token first. Open Settings and paste a Hugging Face access token that can reach this endpoint.
')+ '
'+starters.map(function(x){return '';}).join("")+'
'; 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(ikeep?(keep>0?idx[idx.length-keep]:msgs.length):-1; } for(i=0;i=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=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)&&waitedMAX_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=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("")<0) return null; var fre=/([\s\S]*?)(?:<\/function>|$)/g, m; while((m=fre.exec(rest))){ var args={}, pre=/\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=/\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(/|=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 ""'); 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='