hatchlight 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/hatchlight.js +1 -1
- package/package.json +1 -1
package/bin/hatchlight.js
CHANGED
|
@@ -79,7 +79,7 @@ ${t}<|im_end|>`,`<|im_start|>assistant
|
|
|
79
79
|
`)}class kb{vision=!1;contextChars=12000;store;model;spawn;run;fetch;freePort;windowsPath;idleMs;server=null;idle;serverKey=null;inFlight=0;generation=0;constructor(e){this.store=e.store,this.model=e.model,this.spawn=e.spawn??xb,this.run=e.run??$b,this.fetch=e.fetch??((t,r)=>fetch(t,r)),this.freePort=e.freePort??S9,this.windowsPath=e.windowsPath??Kc,this.idleMs=e.idleMs??y9}async ready(){return(await this.store.list().catch(()=>null))?.models.find((t)=>t.id===this.model)?.ready??!1}toEnglish(e,t){return this.reply(Md,e,t,{temperature:0})}async reply(e,t,r,n={}){let s=await this.store.runtime(this.model),o={instructions:e,text:t,temperature:n.temperature??0};return s.throughWindows?this.once(s,o,r):this.served(s,o,r)}async chat(e,t,r,n){let s=await this.store.runtime(this.model);if(s.throughWindows)throw new le("The assistant on this computer runs only in the Windows app, not under WSL","localAssistantUnavailable");return ad(await this.completion(s,{messages:od(e,t,!1),...r.length>0&&{tools:id(r)},temperature:0.3,max_tokens:x9},n))}async served(e,t,r){let s=(await this.completion(e,{messages:[{role:"system",content:t.instructions},{role:"user",content:t.text}],temperature:t.temperature,max_tokens:S1},r)).choices?.[0]?.message?.content;if(typeof s!=="string")throw Error("No answer came back");return s}async completion(e,t,r){clearTimeout(this.idle),this.inFlight++;try{let n=await this.started(e);r.throwIfAborted();let s=await this.fetch(`${n.url}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:r});if(!s.ok)throw Error(`The language model refused (HTTP ${s.status})`);return await s.json()}finally{if(this.inFlight--,this.inFlight===0)clearTimeout(this.idle),this.idle=setTimeout(()=>this.stop(),this.idleMs),this.idle.unref?.()}}started(e){let t=`${e.executable}:${e.files.model}`;if(this.server&&this.serverKey!==t)this.stop();if(!this.server){let r=this.generation,n=this.start(t,e,r);this.server=n,this.serverKey=t,n.catch(()=>{if(this.server===n)this.forget()})}return this.server}forget(){this.server=null,this.serverKey=null}async start(e,t,r){let n=t.files.model;if(!n)throw Error("The translator has no model file");let s=await this.freePort(),o=this.spawn([t.executable,"-m",n,"--host","127.0.0.1","--port",String(s),"-c",String(_9),"-np","1"]);(async()=>{for await(let u of o.output);})().catch(()=>{});let i=!1,a=`http://127.0.0.1:${s}`,c={key:e,url:a,stop:()=>o.kill(),exited:o.exited};o.exited.then(()=>{i=!0,this.server?.then((u)=>{if(u===c)this.forget()})});let l=Date.now();for(;;){if(i)throw Error("The translator would not start");if(this.generation!==r)throw o.kill(),Error("The translator was stopped");if(Date.now()-l>w9)throw o.kill(),Error("The translator took too long to start");if((await this.fetch(`${a}/health`).catch(()=>null))?.ok)break;await Bun.sleep(b9)}return c}async once(e,t,r){let n=e.files.model;if(!n)throw Error("The translator has no model file");let s=x1(g9(e.executable),h9(e.executable).replace("llama-server","llama-completion"));await f9(e.scratch,{recursive:!0});let o=x1(e.scratch,`${crypto.randomUUID()}.prompt.txt`);await Bun.write(o,$9(t.instructions,t.text));try{let{code:i,stdout:a,stderr:c}=await this.run([s,"-m",await this.windowsPath(n),"-f",await this.windowsPath(o),"-no-cnv","--no-display-prompt","--temp",String(t.temperature),"-n",String(S1),"-c",String(v9),"--no-perf"],r);if(i!==0){let l=c.trim().split(/\r?\n/).at(-1);throw Error(`The translator stopped: ${l??`code ${i}`}`)}return a.replace(/\s*\[end of text\]\s*$/,"").trim()}finally{await m9(o,{force:!0})}}stop(){this.stopAndWait()}async stopAndWait(){clearTimeout(this.idle),this.generation++;let e=this.server;this.forget();let t=await e?.catch(()=>null);t?.stop(),await t?.exited}}var y9=300000,w9=120000,b9=250,S1=512,v9=2048,_9=8192,x9=1024,$b=async(e,t)=>{t.throwIfAborted();let r=Bun.spawn(e,{stdin:"ignore",stdout:"pipe",stderr:"pipe"}),n=()=>r.kill();t.addEventListener("abort",n,{once:!0});try{let[s,o,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return t.throwIfAborted(),{code:i,stdout:s,stderr:o}}finally{t.removeEventListener("abort",n)}};var Tb=b(()=>{Ar();Fc();Vd()});import{mkdir as k9,rm as T9}from"fs/promises";import{basename as P9,dirname as E9,join as $1}from"path";function z9(e){let t=e.replace(/^\s*(caption|description)\s*:\s*/i,"").replace(/["\u201C\u201D]/g,"").replace(/\s+/g," ").trim().replace(/\.$/,"");if(t.length<=k1)return t;let r=t.slice(0,k1),n=r.lastIndexOf(",");return(n>0?r.slice(0,n):r).trim()}function M9(e){let t=e.trim().slice(0,R9);return[t?`The person asked for: "${t}".`:"The person asked for a picture.","In two or three sentences, in English: say what the picture shows, then say plainly whether it matches what was asked and what, if anything, is off (something missing, cut off, the wrong number of things, misspelled text)."].join(" ")}class Pb{store;model;run;windowsPath;constructor(e){this.store=e.store,this.model=e.model,this.run=e.run??$b,this.windowsPath=e.windowsPath??Kc}async ready(){return(await this.store.list().catch(()=>null))?.models.find((t)=>t.id===this.model)?.ready??!1}async look(e,t,r){let n=[];for(let s of e.slice(0,I9)){let o=await this.ask(s,M9(t),A9,r);n.push(s.label?`${s.label}: ${o}`:o)}return n.join(`
|
|
80
80
|
`)}async caption(e,t){return z9(await this.ask(e,O9,C9,t))}async ask(e,t,r,n){let s=await this.store.runtime(this.model),o=s.files.model,i=s.files.llm_vision;if(!o||!i)throw Error("The model that looks at pictures is incomplete");let a=s.throughWindows?this.windowsPath:async(d)=>d,c=$1(E9(s.executable),P9(s.executable).replace("llama-server","llama-mtmd-cli"));await k9(s.scratch,{recursive:!0});let l=e.mimeType.split("/")[1]??"jpeg",u=$1(s.scratch,`${crypto.randomUUID()}.look.${l}`);await Bun.write(u,Buffer.from(e.data,"base64"));try{let{code:d,stdout:p,stderr:f}=await this.run([c,"-m",await a(o),"--mmproj",await a(i),"--image",await a(u),"-p",t,"-n",String(r),"--temp","0.2","--no-perf"],n);if(d!==0){let m=f.trim().split(/\r?\n/).at(-1);throw Error(`Looking at the picture failed: ${m??`code ${d}`}`)}return p.replace(/\s+/g," ").trim()}finally{await T9(u,{force:!0})}}}var I9=2,A9=200,R9=500,C9=120,k1=400,O9="Write a caption for this picture, to train an image model with: one line in English of phrases of a few words each, separated by commas, such as: sitting on a wooden table, soft window light, close-up, plain gray background. Say where it is, what the subject does or how it is posed, what it wears or holds, the light, the framing and the background. Do not say who or what the main subject is, nor its colors or art style. No full sentences, no quotes.";var T1=b(()=>{Vd();Tb()});import{linkSync as N9,readFileSync as P1,renameSync as L9,rmSync as Zd,statSync as E1,writeFileSync as Hd}from"fs";import{dirname as D9,join as j9}from"path";function B9(e){let t=j9(e,`.clock-${crypto.randomUUID()}`);try{return Hd(t,""),E1(t).mtimeMs}finally{Zd(t,{force:!0})}}function Eb(e,t){try{let{mtimeMs:r}=E1(e);return B9(D9(e))-r<=t}catch{return!1}}function zi(e,t=Ib){return Eb(e,t)}function A1(e,t,r){try{return Hd(e,t,{flag:"wx"}),!0}catch(s){if(s.code!=="EEXIST")throw s}if(Eb(e,r))return!1;let n=`${e}.${crypto.randomUUID()}.stale`;try{L9(e,n)}catch{return!1}if(Eb(n,r)){try{N9(n,e)}catch{}return Zd(n,{force:!0}),!1}Zd(n,{force:!0});try{return Hd(e,t,{flag:"wx"}),!0}catch{return!1}}function R1(e,t,r){let n=setInterval(()=>{try{if(P1(e,"utf8")===t)Hd(e,t)}catch{}},r);return n.unref?.(),()=>{clearInterval(n);try{if(P1(e,"utf8")===t)Zd(e)}catch{}}}function Mi(e,t={}){let r=t.owner??crypto.randomUUID();if(!A1(e,r,t.staleMs??Ib))return null;return R1(e,r,t.heartbeatMs??I1)}async function Ab(e,t,r,n={}){let s=crypto.randomUUID(),o=n.staleMs??Ib;for(;;){if(t.throwIfAborted(),A1(e,s,o))break;await n.onWait?.(),await Bun.sleep(n.pollMs??U9)}let i=R1(e,s,n.heartbeatMs??I1);try{return await r()}finally{i()}}var Ib=30000,I1=5000,U9=1000;var Rb=()=>{};import{existsSync as M1}from"fs";import{homedir as q9}from"os";import{join as Wc,posix as Ni,win32 as ns}from"path";function C1(e,t,r,n){let s=t.join(e,Ds),o=t.join(e,es),i=(a)=>n.some((c)=>r(t.join(a,c)));return!i(s)&&i(o)?o:s}function Cb(e,t,r){let n=t.join(e,Ds),s=t.join(e,es);if(r(t.join(n,`${Ds}.sqlite`)))return n;if(r(t.join(s,`${es}.sqlite`)))return s;return r(s)?s:n}function Qt(e=process.platform,t=process.env,r=q9(),n=M1){let s=lt(t,"DATA_DIR");if(s)return s;if(e==="win32")return Cb(t.APPDATA??ns.join(r,"AppData","Roaming"),ns,n);if(e==="darwin")return Cb(Wc(r,"Library","Application Support"),Ni,n);return Cb(t.XDG_DATA_HOME??Wc(r,".local","share"),Ni,n)}function Jc(e){return/^\\\\\?\\[A-Za-z]:\\/.test(e)?e.slice(4):e}async function z1(e){try{let t=Bun.spawn(e,{stdout:"pipe",stderr:"ignore"}),[r,n]=await Promise.all([new Response(t.stdout).text(),t.exited]);return n===0?r.replaceAll("\r","").trim():null}catch{return null}}async function N1(e,t=process.platform,r=process.env,n=M1){let s=lt(r,"MODELS_DIR");if(s)return s;if(t==="win32")return r.LOCALAPPDATA?ns.join(C1(r.LOCALAPPDATA,ns,n,O1),"models"):ns.join(e,"models");if(t==="linux"&&(await qd({run:async()=>null})).wsl){let o=await z1(["cmd.exe","/c","echo","%LOCALAPPDATA%"]),i=o&&!o.includes("%")?await z1(["wslpath","-u",o]):null;if(i)return Wc(C1(i,Ni,n,O1),"models")}return Wc(e,"models")}function L1(e,t=process.platform,r=process.env){let n=lt(r,"TRAINER_DIR");if(n)return n;if(t==="win32"&&r.LOCALAPPDATA)return ns.join(r.LOCALAPPDATA,Ds,"trainer");return Wc(e,"trainer")}function Ob(e){let t=/^[A-Za-z]:\\/.test(e)?ns:Ni;return t.join(t.dirname(e),"models-location.json")}function Gd(e,t=process.platform){let r=e.match(/^([A-Za-z]):[\\/](.*)$/),n=e.match(/^\/mnt\/([a-z])(?:\/(.*))?$/);if(t==="win32"){if(r)return e;if(n)return ns.join(`${n[1]?.toUpperCase()}:\\`,...(n[2]??"").split("/").filter(Boolean));return null}if(r)return t==="linux"?Ni.join(`/mnt/${r[1]?.toLowerCase()}`,...(r[2]??"").split(/[\\/]/).filter(Boolean)):null;return Ni.isAbsolute(e)?e:null}function D1(e){let t=e.match(/^\/mnt\/([a-z])(?:\/(.*))?$/);if(!t)return e;return ns.join(`${t[1]?.toUpperCase()}:\\`,...(t[2]??"").split("/").filter(Boolean))}async function j1(e,t=process.platform){return await Bun.file(Ob(e)).json().then((s)=>typeof s.path==="string"?Gd(s.path,t):null).catch(()=>null)??e}var O1;var zb=b(()=>{Gc();O1=["models","models-location.json"]});import{mkdirSync as Mb,readdirSync as F9,readFileSync as V9,rmSync as Li,statSync as Nb,writeFileSync as Kd}from"fs";import{join as Lb}from"path";class Db{dir;owner=crypto.randomUUID();holds=new Set;heartbeat;capacity;known=null;staleMs;heartbeatMs;pollMs;constructor(e){this.dir=Lb(e.root,"gpu"),this.capacity=e.capacity,this.staleMs=e.staleMs??Z9,this.heartbeatMs=e.heartbeatMs??K9,this.pollMs=e.pollMs??W9}moveTo(e){if(this.dir=Lb(e,"gpu"),this.holds.size>0)try{this.publish()}catch{}}inUse(){if(this.holds.size>0)return!0;try{Mb(this.dir,{recursive:!0});let e=this.look(this.now(),!1);return e.others>0||e.waiters.length>0}catch{return!1}}othersReserved(){try{Mb(this.dir,{recursive:!0});let{others:e}=this.look(this.now(),!1);return Number.isFinite(e)?e:0}catch{return 0}}get reserved(){let e=0;for(let t of this.holds)e+=t.bytes;return e}file(e){return Lb(this.dir,e)}now(){let e=this.file(`clock-${this.owner}`);return Kd(e,""),Nb(e).mtimeMs}fits(e,t){return e<=0||e+t<=(this.known??0)}exclusive(e){let t=this.file("mutex");try{Kd(t,"",{flag:"wx"})}catch(r){if(r.code!=="EEXIST")throw r;try{if(this.now()-Nb(t).mtimeMs>G9)Li(t,{force:!0})}catch{}return null}try{return e(this.now())}finally{Li(t,{force:!0})}}look(e,t){let r=0,n=[];for(let s of F9(this.dir)){if(s==="mutex")continue;let o=this.file(s);try{let i=e-Nb(o).mtimeMs,a=s.startsWith("wait-");if(i>(a?H9:this.staleMs)){if(t)Li(o,{force:!0});continue}if(s.startsWith("clock-"))continue;let c=V9(o,"utf8");if(a){let[l,u]=c.split(":").map(Number);if(l&&Number.isFinite(u))n.push({id:s.slice(5),since:l,bytes:u??0})}else if(s!==this.owner){let l=Number(c);r+=c&&Number.isFinite(l)?l:1/0}}catch{}}return{others:r,waiters:n}}publish(){if(this.holds.size===0){Li(this.file(this.owner),{force:!0}),clearInterval(this.heartbeat),this.heartbeat=void 0;return}if(Kd(this.file(this.owner),String(this.reserved)),!this.heartbeat)this.heartbeat=setInterval(()=>this.beat(),this.heartbeatMs),this.heartbeat.unref?.()}beat(){try{this.publish(),this.letGoFor(this.look(this.now(),!1))}catch{}}letGoFor(e){let t=this.reserved+e.others;for(let r of[...this.holds]){if(!r.onWanted)continue;if(e.waiters.some((n)=>this.fits(t-r.bytes,n.bytes)))r.onWanted()}}wanted(e){try{let t=this.look(this.now(),!1),r=this.reserved+t.others-e;return t.waiters.some((n)=>this.fits(r,n.bytes))}catch{return!1}}async*acquire(e,t,r={}){Mb(this.dir,{recursive:!0}),this.known=await this.capacity().catch(()=>null);let n={bytes:e,onWanted:r.onWanted},s=crypto.randomUUID(),o=this.file(`wait-${s}`),i=null,a=0;try{for(;;){t.throwIfAborted();let l,u={others:0,waiters:[]};try{l=this.exclusive((d)=>{u=this.look(d,!0);let p=this.reserved+u.others;if(!this.fits(p,e))return!1;if(u.waiters.some((m)=>m.id!==s&&(i==null||m.since<i)&&this.fits(p,m.bytes)))return!1;this.holds.add(n);try{this.publish()}catch(m){throw this.holds.delete(n),m}return!0}),a=0}catch(d){if(++a>=U1)throw d;l=null}if(l)break;if(l===null){await Bun.sleep(J9);continue}try{if(i==null)i=this.now(),yield{type:"progress",message:"Waiting for the GPU",stage:"waitingGpu"};Kd(o,`${i}:${e}`),this.letGoFor({others:u.others,waiters:[{id:s,since:i,bytes:e}]})}catch(d){if(++a>=U1)throw d}await Bun.sleep(this.pollMs)}}finally{try{Li(o,{force:!0})}catch{}}let c=!1;return{release:()=>{if(c)return;c=!0,this.holds.delete(n);try{this.publish()}catch{}}}}close(){this.holds.clear();try{this.publish(),Li(this.file(`clock-${this.owner}`),{force:!0})}catch{}}}var Z9=30000,H9=5000,G9=5000,K9=5000,W9=1000,J9=20,U1=10;var B1=()=>{};import{copyFile as Q9,link as X9,mkdir as jb,readdir as Wd,rename as Ub,rm as Qc,rmdir as Y9,stat as Di}from"fs/promises";import{dirname as Bb,join as Lo}from"path";async function Qd(e){let t=await Di(e).catch(()=>null);if(!t)return 0;if(!t.isDirectory())return t.size;let r=0;for(let n of await Wd(e))r+=await Qd(Lo(e,n));return r}function qb(e){return e.endsWith(".lock")||e.endsWith(".stale")||e.endsWith(".moving")||e.endsWith(".tmp")||e.startsWith(".clock-")}async function Jd(e,t,r,n){n.signal?.throwIfAborted();let s=await Di(e,{bigint:!0}).catch(()=>null);if(!s)return;let o=await Di(t,{bigint:!0}).catch(()=>null);if(o&&o.dev===s.dev&&o.ino===s.ino){if(s.isDirectory())throw Error(`${t} is ${e} itself`);r.old.push(e),n.report(Number(s.size));return}if(s.isDirectory()){if(o&&!o.isDirectory())throw Error(`${t} is in the way`);if(o&&n.whole?.(e)){if(await q1(e,t)){r.old.push(e),n.report(await Qd(e));return}await Qc(t,{recursive:!0,force:!0}),o=null}if(!o&&n.whole?.(e)){let c=`${t}.${crypto.randomUUID()}.moving`,l={made:[],old:[]};try{await jb(c,{recursive:!0});for(let u of await Wd(e)){if(qb(u))continue;await Jd(Lo(e,u),Lo(c,u),l,n)}await Ub(c,t)}catch(u){throw await Qc(c,{recursive:!0,force:!0}),u}r.made.push(t),r.old.push(e);return}await jb(t,{recursive:!0});for(let c of await Wd(e)){if(qb(c))continue;await Jd(Lo(e,c),Lo(t,c),r,n)}return}let i=e.endsWith(".part")&&o&&s.size>o.size;if(o&&n.keep(e)&&!i){r.old.push(e),n.report(Number(s.size));return}let a=`${t}.${crypto.randomUUID()}.moving`;await jb(Bb(t),{recursive:!0});try{try{await X9(e,a)}catch{await Q9(e,a)}if(o)await Ub(a,t);else await Ub(a,t),r.made.push(t)}catch(c){throw await Qc(a,{force:!0}),c}r.old.push(e),n.report(Number(s.size))}async function q1(e,t){let[r,n]=await Promise.all([Di(e),Di(t)]);if(r.isDirectory()!==n.isDirectory())return!1;if(!r.isDirectory())return r.size===n.size;let s=(a)=>Wd(a).then((c)=>c.filter((l)=>!qb(l)).sort()),[o,i]=await Promise.all([s(e),s(t)]);if(o.join("/")!==i.join("/"))return!1;for(let a of o)if(!await q1(Lo(e,a),Lo(t,a)))return!1;return!0}async function F1(e){let t=[];for(let r of[...e.made].reverse())await Qc(r,{recursive:!0,force:!0}).catch(()=>{t.push(r)});return t}async function V1(e,t){let r=new Set;for(let n of e.old){let s=await Di(n).catch(()=>null);if(!s)continue;await Qc(n,{recursive:s.isDirectory(),force:!0}).catch(()=>{});for(let o=Bb(n);o.startsWith(t)&&o!==t;)r.add(o),o=Bb(o)}for(let n of[...r].sort((s,o)=>o.length-s.length))await Y9(n).catch(()=>{})}var Z1=()=>{};import{createReadStream as G1,createWriteStream as K1}from"fs";import{chmod as e5,mkdir as Xd,rename as W1,rm as Fb,stat as t5,symlink as r5}from"fs/promises";import{dirname as H1,join as n5,resolve as s5,sep as J1}from"path";import{Readable as Q1}from"stream";import{pipeline as Vb}from"stream/promises";import{createGunzip as o5,createGzip as i5}from"zlib";class X1{chunks;rest=Buffer.alloc(0);constructor(e){this.chunks=e[Symbol.asyncIterator]()}async next(e){while(this.rest.length===0){let{value:r,done:n}=await this.chunks.next();if(n)return null;this.rest=r}let t=this.rest.subarray(0,e);return this.rest=this.rest.subarray(t.length),t}async*take(e){for(let t=e;t>0;){let r=await this.next(t);if(!r)throw Error("The archive is truncated");t-=r.length,yield r}}async read(e){let t=[];for await(let r of this.take(e))t.push(r);return Buffer.concat(t,e)}async block(){let e=await this.next(Vr);if(!e)return null;if(e.length===Vr)return e;return Buffer.concat([e,await this.read(Vr-e.length)])}async skip(e){for await(let t of this.take(e));}async drain(){this.rest=Buffer.alloc(0);while(!(await this.chunks.next()).done);}}function Us(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return n.toString("utf8",0,s===-1?r:s)}function Yd(e,t,r){let n=e.subarray(t,t+r),s=n[0]??0;if(s&128){let i=s&127;for(let a of n.subarray(1))i=i*256+a;return i}let o=Us(e,t,r).trim();if(o==="")return 0;if(!/^[0-7]+$/.test(o))throw Error("The archive is damaged");return Number.parseInt(o,8)}function c5(e){let t=0;for(let r=0;r<Vr;r++)t+=r>=148&&r<156?32:e[r]??0;return t===Yd(e,148,8)}function l5(e){let t=new Map,r=0;while(r<e.length){let n=e.indexOf(32,r),s=Number(e.toString("utf8",r,n));if(n===-1||!Number.isInteger(s)||s<=0)break;let o=e.toString("utf8",n+1,r+s-1),i=o.indexOf("=");if(i>0)t.set(o.slice(0,i),o.slice(i+1));r+=s}return t}function u5(e,t){let r=t.split("/");if(t.startsWith("/")||t.includes("\\")||r.some((s)=>s===".."))throw Error(`The archive holds an unsafe path: ${t}`);let n=n5(e,...r.filter((s)=>s!==""&&s!=="."));if(n!==e&&!n.startsWith(e+J1))throw Error(`The archive holds an unsafe path: ${t}`);return n}async function ep(e,t){await Xd(t,{recursive:!0}),await eI(e,t)}async function Y1(e){return eI(e,null)}async function eI(e,t){let r=[];return await Vb(G1(e),o5(),async(n)=>{let s=new X1(n);await p5(s,t,r),await s.drain()}),r}async function p5(e,t,r){let n={};for(;;){let s=await e.block();if(!s||s.every((g)=>g===0))break;if(!c5(s))throw Error("The archive is damaged");let o=String.fromCharCode(s[156]??0),i=o==="x"||o==="g"||o==="L"||o==="K",a=i?Yd(s,124,12):n.size??Yd(s,124,12);if(!Number.isSafeInteger(a)||a<0)throw Error("The archive is damaged");let c=(Vr-a%Vr)%Vr;if(i){if(a>a5)throw Error("The archive holds an extended header too large");let g=await e.read(a);if(await e.skip(c),o==="x"){let w=l5(g),v=w.get("path"),_=w.get("linkpath"),C=w.get("size");n={...n,...v!=null&&{path:v},..._!=null&&{linkpath:_},...C!=null&&{size:Number(C)}}}else if(o==="L")n={...n,path:Us(g,0,g.length)};else if(o==="K")n={...n,linkpath:Us(g,0,g.length)};continue}let l=Us(s,257,5)==="ustar"?Us(s,345,155):"",u=n.path??(l?`${l}/${Us(s,0,100)}`:Us(s,0,100)),d=n.linkpath??Us(s,157,100);n={};let p=t??d5,f=u5(p,u);if(f===p&&o!=="5")throw Error(`The archive holds an unsafe path: ${u}`);let m=!d||d.includes("/")||d.includes("\\")||d==="."||d==="..",h=o==="0"||o==="\x00"||o==="7";if(o==="2"&&m)throw Error(`The archive holds an unsafe link: ${u}`);if(o!=="5"&&o!=="2"&&!h)throw Error(`${u} is a kind of file that is not supported`);if(f!==p)r.push({name:f.slice(p.length+1).split(J1).join("/"),type:o==="5"?"directory":o==="2"?"link":"file",size:h?a:0});if(t===null){await e.skip(a+c);continue}if(o==="5")await Xd(f,{recursive:!0}),await e.skip(a+c);else if(h){await Xd(H1(f),{recursive:!0});let g=`${f}.${crypto.randomUUID()}.tmp`;try{await Vb(Q1.from(e.take(a)),K1(g))}catch(w){throw await Fb(g,{force:!0}),w}await e.skip(c),await e5(g,Yd(s,100,8)&493),await W1(g,f)}else await Xd(H1(f),{recursive:!0}),await Fb(f,{force:!0}),await r5(d,f),await e.skip(a+c)}}function tI(e,t,r,n="0"){let s=Buffer.alloc(Vr),o=(c,l,u)=>{s.write(c,l,u,"utf8")},i=(c,l,u)=>o(`${c.toString(8).padStart(u-1,"0")}\x00`,l,u);o(e,0,100),i(r,100,8),i(0,108,8),i(0,116,8),i(t,124,12),i(Math.floor(Date.now()/1000),136,12),o(n,156,1),o("ustar\x00",257,6),o("00",263,2),s.fill(32,148,156);let a=0;for(let c of s)a+=c;return i(a,148,7),s}function f5(e){let t=` path=${e}
|
|
81
81
|
`,r=Buffer.byteLength(t)+1;while(Buffer.byteLength(`${r}${t}`)!==r)r++;let n=Buffer.from(`${r}${t}`);return[tI("PaxHeader",n.length,420,"x"),n,rI(n.length)]}async function nI(e,t,r={}){async function*n(){for(let o of t){let i=await t5(o.source),a=o.name.replaceAll("\\","/");if(Buffer.byteLength(a)>100)yield*f5(a);yield tI(Buffer.byteLength(a)>100?a.slice(-100):a,i.size,i.mode&493);let c=0;if(i.size>0)for await(let l of G1(o.source,{start:0,end:i.size-1}))c+=l.length,yield l;if(c!==i.size)throw Error(`${o.source} changed while it was being saved`);yield rI(i.size)}yield Buffer.alloc(Vr*2)}let s=`${e}.${crypto.randomUUID()}.tmp`;try{await Vb(Q1.from(n()),i5(),K1(s,{mode:r.mode??420})),await W1(s,e)}catch(o){throw await Fb(s,{force:!0}),o}}var Vr=512,a5=1048576,d5,rI=(e)=>Buffer.alloc((Vr-e%Vr)%Vr);var Zb=b(()=>{d5=s5("/nowhere")});import{mkdir as Hb,open as sI,rename as m5,rm as h5}from"fs/promises";import{dirname as g5,join as y5,sep as w5}from"path";import{Readable as b5,Transform as v5}from"stream";import{pipeline as _5}from"stream/promises";import{crc32 as x5,createInflateRaw as S5}from"zlib";async function Xc(e,t,r){let n=Buffer.alloc(r),{bytesRead:s}=await e.read(n,0,r,t);if(s!==r)throw Error("The archive is truncated");return n}async function I5(e,t){let r=Math.min(t,65557),n=await Xc(e,t-r,r),s=-1;for(let p=n.length-22;p>=0;p--)if(n.readUInt32LE(p)===$5){s=p;break}if(s===-1)throw Error("Not a zip archive");let o=n.readUInt16LE(s+10),i=n.readUInt32LE(s+12),a=n.readUInt32LE(s+16),c=s-20;if(c>=0&&n.readUInt32LE(c)===k5){let p=Number(n.readBigUInt64LE(c+8)),f=await Xc(e,p,56);if(f.readUInt32LE(0)!==T5)throw Error("The archive's zip64 record is damaged");o=Number(f.readBigUInt64LE(32)),i=Number(f.readBigUInt64LE(40)),a=Number(f.readBigUInt64LE(48))}if(a+i>t)throw Error("The archive is truncated");let l=await Xc(e,a,i),u=[],d=0;for(let p=0;p<o;p++){if(l.readUInt32LE(d)!==P5)throw Error("The archive's file list is damaged");let f=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),h=l.readUInt16LE(d+32),g=l.readUInt32LE(d+20),w=l.readUInt32LE(d+24),v=l.readUInt32LE(d+42),_=d+46+f,C=_+m;while(_+4<=C){let k=l.readUInt16LE(_),P=l.readUInt16LE(_+2);if(k===1){let y=_+4,x=()=>{let T=Number(l.readBigUInt64LE(y));return y+=8,T};if(w===Gb)w=x();if(g===Gb)g=x();if(v===Gb)v=x()}_+=4+P}u.push({name:l.toString("utf8",d+46,d+46+f),method:l.readUInt16LE(d+10),crc:l.readUInt32LE(d+16),compressedSize:g,size:w,headerOffset:v}),d+=46+f+m+h}return u}function A5(e,t){let r=t.replaceAll("\\","/").split("/");if(t.startsWith("/")||/^[a-zA-Z]:/.test(t)||r.some((s)=>s===".."))throw Error(`The archive holds an unsafe path: ${t}`);let n=y5(e,...r.filter((s)=>s!==""&&s!=="."));if(n!==e&&!n.startsWith(e+w5))throw Error(`The archive holds an unsafe path: ${t}`);return n}function oI(e){let t=0,r=0;return new v5({transform(n,s,o){if(t=x5(n,t),r+=n.length,r>e.size){o(Error(`${e.name} is larger than the archive says`));return}o(null,n)},flush(n){if(r!==e.size||t!==e.crc){n(Error(`${e.name} is damaged in the archive`));return}n()}})}async function Yc(e,t){let r=await sI(e,"r");try{let{size:n}=await r.stat(),s=await I5(r,n);await Hb(t,{recursive:!0});for(let o of s){let i=A5(t,o.name);if(o.name.endsWith("/")){await Hb(i,{recursive:!0});continue}if(o.method!==0&&o.method!==8)throw Error(`${o.name} uses a compression method that is not supported`);let a=await Xc(r,o.headerOffset,30);if(a.readUInt32LE(0)!==E5)throw Error("The archive is damaged");let c=o.headerOffset+30+a.readUInt16LE(26)+a.readUInt16LE(28);if(c+o.compressedSize>n)throw Error("The archive is truncated");await Hb(g5(i),{recursive:!0});let l=`${i}.${crypto.randomUUID()}.tmp`,u=await sI(l,"w");try{let d=b5.from(async function*(){for(let m=0;m<o.compressedSize;m+=1048576){let h=Math.min(1048576,o.compressedSize-m);yield await Xc(r,c+m,h)}}()),p=o.method===8?[S5(),oI(o)]:[oI(o)];await _5(d,...p,u.createWriteStream())}catch(d){throw await h5(l,{force:!0}),d}finally{await u.close().catch(()=>{})}await m5(l,i)}}finally{await r.close()}}var $5=101010256,k5=117853008,T5=101075792,P5=33639248,E5=67324752,Gb=4294967295;var Kb=()=>{};import{chmod as R5,mkdir as Bs,open as C5,readdir as ji,rename as el,rm as Sr,stat as tl,statfs as iI}from"fs/promises";import{dirname as tp,join as Ae,resolve as Xb}from"path";function O5(e,t){let r=(n)=>{let s=Xb(n);return process.platform==="win32"||s.startsWith("/mnt/")?s.toLowerCase():s};return r(e)===r(t)}async function cI(e,t){for(let r=tp(Xb(e));;r=tp(r)){let n=await tl(r,{bigint:!0}).catch(()=>null);if(n&&n.dev===t.dev&&n.ino===t.ino)return!0;if(r===tp(r))return!1}}function Wb(){return new O("Models are moving to another folder; try again once they are there","modelsMoving")}async function M5(e){try{let t=Bun.spawn([e,"--help"],{stdin:"ignore",stdout:"ignore",stderr:"pipe"}),r=setTimeout(()=>t.kill(),z5),[n,s]=await Promise.all([t.exited,new Response(t.stderr).text()]);if(clearTimeout(r),n===0)return null;return s.trim().split(/\r?\n/).at(-1)||`it stopped with code ${n}`}catch(t){return t instanceof Error?t.message:String(t)}}function Do(e){if(e<1000)return`${e} B`;if(e<1e6)return`${Math.round(e/1000)} kB`;if(e<1e9)return`${Math.round(e/1e6)} MB`;return`${(e/1e9).toFixed(e<10000000000?2:1)} GB`}function dI(e,t){if(e.length===0)throw Error(`${t} has no files`);if(new Set(e.map((r)=>r.name)).size!==e.length)throw Error(`Repeated file name in ${t}`);for(let r of e){if(!r.url.startsWith("https://"))throw Error(`Not an HTTPS URL: ${r.url}`);if(!/^[a-f0-9]{64}$/.test(r.sha256))throw Error(`Invalid hash for ${r.name} of ${t}`);if(!Number.isInteger(r.size)||r.size<=0)throw Error(`Invalid size for ${r.name} of ${t}`)}}function N5(e,t){let r=new Map,n=(i,a)=>{for(let c of i){if((r.get(c.sha256)??c.size)!==c.size)throw Error(`One hash, two sizes: ${c.name} of ${a}`);r.set(c.sha256,c.size)}},s=new Set;for(let i of t)for(let a of i.builds){if(!Jb.test(a.id)||s.has(a.id))throw Error(`Invalid or repeated engine build id: ${a.id}`);if(s.add(a.id),a.engine!==i.id)throw Error(`Build ${a.id} belongs to another engine`);let c=a.executable.split(/[\\/]/);if(a.executable.startsWith("/")||c.includes(".."))throw Error(`Unsafe executable path in build ${a.id}`);dI(a.files,`build ${a.id}`),n(a.files,`build ${a.id}`)}let o=new Set;for(let i of e){if(!Jb.test(i.id)||o.has(i.id))throw Error(`Invalid or repeated local model id: ${i.id}`);if(o.add(i.id),i.variants.length===0)throw Error(`Local model without variants: ${i.id}`);let a=new Set;for(let c of i.variants){let l=`${i.id} (${c.id})`;if(!Jb.test(c.id)||a.has(c.id))throw Error(`Invalid or repeated variant id: ${l}`);if(a.add(c.id),!t.some((u)=>u.id===c.engine))throw Error(`Unknown engine ${c.engine} for ${l}`);dI(c.files,l),n(c.files,l)}for(let c of i.demos)if(!c.url.startsWith("https://"))throw Error(`Not an HTTPS URL: ${c.url}`)}}async function L5(e,t,r){let n=await new Bun.Image(Bun.file(e)).resize(r,r,{fit:"inside",withoutEnlargement:!0}).webp({quality:82}).bytes(),s=`${t}.${crypto.randomUUID()}.tmp`;try{await Bun.write(s,n),await el(s,t)}catch(o){throw await Sr(s,{force:!0}),o}return!0}async function mI(e){let t=0;for(let r of await ji(e,{withFileTypes:!0}).catch(()=>[])){let n=Ae(e,r.name);t+=r.isDirectory()?await mI(n):await Ui(n)}return t}class Yb{root;catalog;engines;fetch;detect;gpuMemory;memoryRead=null;hardware=null;checkEngine;broken=new Set;providedBroken=new Set;lastReady=null;listeners=new Set;installs=new Map;errors=new Map;demos=new Map;unshrinkable=new Set;queue=Promise.resolve();gpu;loras;checkpoints;locationFile;enginesDir;moving=null;moveTask=Promise.resolve();relocating=!1;holders=new Set;moveError=null;constructor(e){N5(e.catalog,e.engines),this.root=e.root,this.locationFile=e.locationFile??null,this.enginesDir=e.enginesDir?Xb(e.enginesDir):null,this.catalog=e.catalog,this.engines=e.engines,this.fetch=e.fetch??globalThis.fetch,this.detect=e.hardware??(()=>qd()),this.gpuMemory=e.gpuMemory??(e.hardware?async()=>null:()=>Bd()),this.checkEngine=e.checkEngine??M5,this.loras=new lb({root:()=>this.root,check:()=>this.notMoving(),changed:()=>this.emit({type:"loras.changed"})}),this.checkpoints=new pb({root:()=>this.root,check:()=>this.notMoving(),changed:()=>this.emit({type:"models.changed"}),release:()=>this.letGo()}),this.gpu=new Db({root:this.root,capacity:async()=>{let{gpus:t}=await this.machine();return t.length>0?Math.max(...t.map((r)=>r.memoryBytes))*D5:null}})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){console.error("A local model listener failed",r)}}machine(){return this.hardware??=Promise.all([this.detect(),this.loadBroken(),this.checkProvided()]).then(([e])=>e),this.hardware}freeMemory(){let e=Date.now();if(!this.memoryRead||e-this.memoryRead.at>j5)this.memoryRead={at:e,memory:this.gpuMemory().catch(()=>null)};return this.memoryRead.memory}async listWithMemory(){let e=await this.list(),t=e.hardware.gpus[0];if(t?.vendor!=="nvidia")return e;let r=await this.freeMemory();if(!r)return e;return{...e,hardware:{...e.hardware,gpus:[{...t,freeBytes:r.freeBytes},...e.hardware.gpus.slice(1)]}}}async checkProvided(){for(let e of this.engines.flatMap((t)=>t.builds)){let t=await this.providedEngineDir(e);if(!t)continue;let r=await this.checkEngine(Ae(t,...e.executable.split(/[\\/]/)));if(r)console.warn(`${e.id} from ${this.enginesDir} does not run: ${r}`),this.providedBroken.add(e.id)}}brokenFile(){return Ae(this.root,"broken-engines.json")}async loadBroken(){let e=await Bun.file(this.brokenFile()).json().catch(()=>[]);if(Array.isArray(e)){for(let t of e)if(typeof t==="string")this.broken.add(t)}}async markBroken(e){this.broken.add(e),await Bs(this.root,{recursive:!0}),await Bun.write(this.brokenFile(),JSON.stringify([...this.broken]))}spec(e){let t=this.catalog.find((r)=>r.id===e);if(!t)throw new Ee(`Unknown local model: ${e}`,"unknownLocalModel",{model:e});return t}blob(e){return Ae(this.root,"blobs",e)}marker(e){return Ae(this.root,"installed",e)}engineDir(e){return Ae(this.root,"engines",e)}async providedEngineDir(e){if(!this.enginesDir||this.providedBroken.has(e.id))return null;let t=Ae(this.enginesDir,e.id);return(await tl(Ae(t,...e.executable.split(/[\\/]/))).catch(()=>null))?.isFile()?t:null}async installedEngineDir(e){return await this.providedEngineDir(e)??this.engineDir(e.id)}chooser(e){let t=new Map;return(r)=>{if(!t.has(r)){let n=(this.engines.find((s)=>s.id===r)?.builds??[]).filter((s)=>!this.broken.has(s.id)&&!this.providedBroken.has(s.id));t.set(r,p1(r,n,e))}return t.get(r)??null}}async onDisk(){let e=new Set,t=new Map,r=Ae(this.root,"blobs");for(let n of await ji(r).catch(()=>[]))if(/^[a-f0-9]{64}$/.test(n))e.add(n);else if(/^[a-f0-9]{64}\.part$/.test(n))t.set(n.slice(0,64),await Ui(Ae(r,n)));return{complete:e,partial:t}}async installedVariants(e){let t=new Map;for(let r of await ji(Ae(this.root,"installed")).catch(()=>[])){let n=this.catalog.find((a)=>a.id===r);if(!n)continue;let s=await Bun.file(this.marker(r)).text().catch(()=>""),o;try{o=JSON.parse(s).variant}catch{}let i=n.variants.find((a)=>a.id===o)??n.variants.find((a)=>a.files.every((c)=>e.has(c.sha256)));if(i)t.set(r,i)}return t}async installedBuilds(){let e=this.engines.flatMap((s)=>s.builds),t=new Set(e.map((s)=>s.id)),r=await ji(Ae(this.root,"engines")).catch(()=>[]),n=new Set(r.filter((s)=>t.has(s)));for(let s of e)if(await this.providedEngineDir(s))n.add(s.id);return n}async neededHashes(){let e=await this.onDisk(),t=new Set,r=[...(await this.installedVariants(e.complete)).values(),...[...this.installs.values()].map((s)=>s.variant)],n=Ae(this.root,"installed");for(let s of await ji(n).catch(()=>[])){if(!s.endsWith(".lock")||!zi(Ae(n,s)))continue;let o=this.catalog.find((i)=>`${i.id}.lock`===s);if(o)r.push(...o.variants)}for(let s of r)for(let o of s.files)t.add(o.sha256);return t}async list(){await this.follow();let e=await this.machine(),t=await this.onDisk(),[r,n]=await Promise.all([this.installedVariants(t.complete),this.installedBuilds()]),s=this.chooser(e),o=(m)=>{if(t.complete.has(m.sha256))return m.size;for(let h of this.installs.values())if(h.current?.sha256===m.sha256)return h.current.bytes;return Math.min(t.partial.get(m.sha256)??0,m.size)},i=new Map;for(let m of n)i.set(m,await mI(this.engineDir(m)));let a=(m,h)=>[...r,...[...this.installs].map(([g,w])=>[g,w.variant])].filter(([g,w])=>g!==h&&w.engine===m).map(([g])=>g),c=(m)=>{let h=fb(m,e,s),g=fb(m.filter((w)=>w.files.every((v)=>t.complete.has(v.sha256))),e,s);return(g&&g.fit===h?.fit?g:h)?.variant},l=this.catalog.map((m)=>{let{variants:h,demos:g,defaults:w,...v}=m,_=this.installs.get(m.id),C=_?.variant??r.get(m.id),k=C??c(h)??null,P=k?s(k.engine)?.build:void 0,y=P!=null&&!n.has(P.id),x=k?ss(k.files):[],T=y&&P?ss(P.files):[],I=new Set;for(let[de,qe]of r)if(de!==m.id)for(let Ye of qe.files)I.add(Ye.sha256);for(let[de,qe]of this.installs)if(de!==m.id)for(let Ye of qe.variant.files)I.add(Ye.sha256);let j=ss(h.flatMap((de)=>de.files)).filter((de)=>!I.has(de.sha256)),se=C!=null&&P!=null&&n.has(P.id)&&a(C.engine,m.id).length===0,we=this.errors.get(m.id);return{...v,state:_?.state??(r.has(m.id)?"installed":"available"),variants:h.map(({files:de,...qe})=>({...qe,fit:Oi(qe,e,s(qe.engine)),size:En(ss(de).map((Ye)=>Ye.size)),files:de.map((Ye)=>({name:Ye.name,size:Ye.size,present:t.complete.has(Ye.sha256)}))})),variant:k?.id??null,installed:r.has(m.id),ready:r.has(m.id)&&P!=null&&!y,demos:g.map(({url:de,...qe})=>qe),size:En([...x,...T].map((de)=>de.size)),receivedBytes:En([...x,...T].map(o)),reclaimableBytes:En(j.map(o))+(se&&P?i.get(P.id)??0:0),...we&&{error:we.message,...we.code&&{errorCode:we.code},...we.params&&{errorParams:we.params}}}}),u=this.engines.flatMap((m)=>{let h=s(m.id);if(!h)return[];let{build:g,throughWindows:w}=h,v=n.has(g.id);return[{engine:m.id,name:m.name,build:g.id,version:g.version,backend:g.backend,throughWindows:w,installed:v,size:v?i.get(g.id)??0:En(ss(g.files).map((_)=>_.size)),usedBy:a(m.id)}]}),d=new Map([...this.catalog.flatMap((m)=>m.variants.flatMap((h)=>h.files)),...this.engines.flatMap((m)=>m.builds.flatMap((h)=>h.files))].map((m)=>[m.sha256,m.size])),p=En([...i.values()]);for(let m of t.complete)p+=d.get(m)??await Ui(this.blob(m));for(let m of t.partial.values())p+=m;let f=l.filter((m)=>m.ready).map((m)=>m.id).join();if(this.lastReady!=null&&f!==this.lastReady)this.lastReady=f,this.emit({type:"models.changed"});return this.lastReady=f,{hardware:e,engines:u,models:l,disk:{path:this.root,freeBytes:await this.freeBytes(),usedBytes:p,changeable:this.locationFile!=null,moving:this.moving,moveError:this.moveError}}}async freeBytes(){await Bs(this.root,{recursive:!0});let e=await iI(this.root);return e.bavail*e.bsize}async relocate(e){if(this.moving||this.relocating)throw Wb();this.relocating=!0;try{await this.startMove(e)}finally{this.relocating=!1}}async startMove(e){let t=this.locationFile;if(!t)throw new O("The models folder is set from outside Hatchlight","modelsFolderFixed");let r=Gd(e.trim());if(!r)throw new O(`Not a full path: ${e}`,"folderNotAbsolute",{path:e});if(process.platform==="linux"&&t.startsWith("/mnt/")&&!/^\/mnt\/[a-z](\/|$)/.test(r))throw new O(`Windows cannot reach ${r}`,"folderNotShared",{path:r});try{await Bs(r,{recursive:!0});let c=Ae(r,`.hatchlight-${crypto.randomUUID()}`);await Bun.write(c,""),await Sr(c)}catch{throw new O(`Cannot write to ${r}`,"folderNotWritable",{path:r})}await Bs(this.root,{recursive:!0});let[n,s]=await Promise.all([tl(this.root,{bigint:!0}),tl(r,{bigint:!0})]);if(n.dev===s.dev&&n.ino===s.ino)return;if(await cI(r,n)||await cI(this.root,s))throw new O("The new folder cannot hold the current one, nor sit inside it","folderInside",{path:r});let o=Mi(Ae(this.root,"moving.lock")),i=o&&Mi(Ae(r,"moving.lock")),a=()=>{o?.(),i?.()};if(!o||!i)throw a(),Wb();await this.letGo();try{let c=async(p)=>(await ji(Ae(this.root,p)).catch(()=>[])).some((f)=>f.endsWith(".lock")&&zi(Ae(this.root,p,f)));if(this.installs.size>0||this.gpu.inUse()||this.loras.busy||this.checkpoints.busy||await c("blobs")||await c("engines")||await c("installed"))throw new O("Models are in use; try again once nothing is installing or generating","modelsBusy");let u=0;for(let p of aI)u+=await Qd(Ae(this.root,p));if(n.dev!==s.dev){let p=await iI(r),f=p.bavail*p.bsize;if(u>f)throw new O(`Not enough disk space: ${Do(u)} needed, ${Do(f)} free`,"notEnoughDisk",{neededBytes:u,freeBytes:f})}let d={to:r,movedBytes:0,totalBytes:u};this.moving=d,this.moveError=null,this.emit({type:"models.moving",...d}),this.moveTask=this.move(r,t,d,a)}catch(c){throw a(),c}}async move(e,t,r,n){let s=this.root,o=0,i=(c)=>{r.movedBytes+=c;let l=Date.now();if(l-o<uI)return;o=l,this.emit({type:"models.moving",...r})},a={made:[],old:[]};try{for(let l of aI)await Jd(Ae(s,l),Ae(e,l),a,{report:i,keep:(u)=>!u.startsWith(Ae(s,"installed"))&&!u.endsWith("broken-engines.json"),whole:(u)=>tp(u)===Ae(s,"engines")});let c=`${t}.${crypto.randomUUID()}.tmp`;await Bun.write(c,JSON.stringify({path:D1(e)})),await el(c,t)}catch(c){let l=await F1(a),u=c instanceof Error?c.message:String(c);this.moveError=$s(new le(`Could not move the models: ${u}`,l.length>0?"modelsMoveLeftCopies":"modelsMoveFailed",{reason:u,path:e})),this.moving=null,n(),this.emit({type:"models.changed"});return}this.switchTo(e),await V1(a,s),this.moving=null,n(),this.emit({type:"models.changed"})}notMoving(){if(this.moving||this.relocating||zi(Ae(this.root,"moving.lock")))throw Wb()}async follow(){if(!this.locationFile||this.moving||this.relocating||this.installs.size>0||this.gpu.reserved>0)return;let e=await Bun.file(this.locationFile).json().then((t)=>typeof t.path==="string"?Gd(t.path):null).catch(()=>null);if(e&&!O5(e,this.root))this.switchTo(e)}switchTo(e){this.root=e,this.gpu.moveTo(e),this.emit({type:"models.changed"})}async runtime(e){let t=this.spec(e);await this.follow(),this.notMoving();let r=await this.onDisk(),n=(await this.installedVariants(r.complete)).get(e);if(!n)throw new O(`${t.name} is not installed`,"notInstalled",{model:t.name});let s=await this.machine(),o=this.chooser(s)(n.engine);if(!o||!(await this.installedBuilds()).has(o.build.id))throw new O(`The engine for ${t.name} is not installed. Install the model again.`,"engineMissing",{model:t.name});let i=await this.installedEngineDir(o.build);return{model:t,variant:n,build:o.build,executable:Ae(i,...o.build.executable.split(/[\\/]/)),throughWindows:o.throughWindows,fit:Oi(n,s,o),...o.gpu&&{gpuMemoryBytes:o.gpu.memoryBytes},scratch:Ae(this.root,"tmp"),files:Object.fromEntries(n.files.map((a)=>[a.role??a.name,this.blob(a.sha256)]))}}async checkpointRuntime(e,t){await this.follow(),this.notMoving();let[r]=t.variants;if(await this.checkpoints.get(e),!r)throw Error(`${t.name} has no variant`);let n=await this.machine(),s=this.chooser(n)(r.engine);if(!s||!(await this.installedBuilds()).has(s.build.id))throw new O(`${t.name} needs the engine of the Stable Diffusion models. Install one of them first.`,"checkpointNeedsEngine",{model:t.name});let o=await this.installedEngineDir(s.build);return{model:t,variant:r,build:s.build,executable:Ae(o,...s.build.executable.split(/[\\/]/)),throughWindows:s.throughWindows,fit:Oi(r,n,s),...s.gpu&&{gpuMemoryBytes:s.gpu.memoryBytes},scratch:Ae(this.root,"tmp"),files:{model:this.checkpoints.path(e)}}}async install(e,t){let r=this.spec(e);if(this.installs.has(e))return;this.notMoving();let n=await this.list(),s=n.models.find((w)=>w.id===e);if(s.ready)return;let o=await this.machine(),i=this.chooser(o),a;if(s.installed){if(a=r.variants.find((w)=>w.id===s.variant),!a)throw Error(`${r.name} has no variant installed`)}else if(t){if(a=r.variants.find((w)=>w.id===t),!a)throw new Ee(`Unknown variant: ${t}`,"unknownVariant",{variant:t});if(Oi(a,o,i(a.engine))==="none")throw new O(`${r.name} (${a.label}) does not run on this machine`,"variantDoesNotRun",{model:r.name,variant:a.label})}else if(a=r.variants.find((w)=>w.id===s.variant),!a)throw new O(`${r.name} does not run on this machine`,"modelDoesNotRun",{model:r.name});let c=i(a.engine)?.build,l=await this.installedBuilds(),u=await this.onDisk(),d=new Set([...this.installs.values()].map((w)=>i(w.variant.engine)?.build.id)),p=(w)=>w.size-Math.min(u.partial.get(w.sha256)??0,w.size),m=(l.has(c.id)||d.has(c.id)?0:En(ss(c.files).map(p))+En(ss(c.files).map((w)=>w.size))*2)+En(ss(a.files).filter((w)=>!u.complete.has(w.sha256)).map(p))+En(n.models.filter((w)=>this.installs.has(w.id)).map((w)=>w.size-w.receivedBytes));if(m>n.disk.freeBytes)throw new O(`Not enough disk space: ${Do(m)} needed, ${Do(n.disk.freeBytes)} free`,"notEnoughDisk",{neededBytes:m,freeBytes:n.disk.freeBytes});let h={state:"queued",controller:new AbortController,variant:a,current:null,startedAt:0,transferred:0,lastProgress:0};this.installs.set(e,h),this.errors.delete(e),this.emit({type:"models.changed"});let g=async()=>{if(this.installs.get(e)!==h)return;let w=null;try{await Bs(Ae(this.root,"installed"),{recursive:!0}),w=Mi(Ae(this.root,"installed",`${e}.lock`)),h.state="downloading",h.startedAt=Date.now(),this.emit({type:"models.changed"});let v=c;while(!(await this.installedBuilds()).has(v.id))try{await this.installEngine(r,v,h)}catch(_){if(!(_ instanceof Qb))throw _;await this.markBroken(v.id);let C=this.chooser(await this.machine())(a.engine);if(!C)throw new le(`The engine does not run on this computer: ${_.message}`,"engineDoesNotRun",{reason:_.message});v=C.build}for(let _ of a.files)await this.download(r,_,h);await Bun.write(this.marker(e),JSON.stringify({variant:a.id}))}catch(v){if(!h.controller.signal.aborted)this.errors.set(e,$s(v))}finally{w?.(),this.installs.delete(e),this.emit({type:"models.changed"})}};this.queue=this.queue.then(g)}async installEngine(e,t,r){await Bs(Ae(this.root,"engines"),{recursive:!0}),await Ab(`${this.engineDir(t.id)}.lock`,r.controller.signal,async()=>{if((await this.installedBuilds()).has(t.id))return;await this.unpackEngine(e,t,r)})}async unpackEngine(e,t,r){for(let i of t.files)await this.download(e,i,r);r.state="verifying",this.progress(e,r,!0);let n=this.engineDir(t.id),s=`${n}.${crypto.randomUUID()}.tmp`;try{for(let i of t.files)r.controller.signal.throwIfAborted(),await(/\.(tar\.gz|tgz)$/.test(i.name)?ep:Yc)(this.blob(i.sha256),s).catch((c)=>{throw new le(c instanceof Error?c.message:String(c),"engineUnpackFailed")});await R5(Ae(s,...t.executable.split(/[\\/]/)),493),await el(s,n)}finally{await Sr(s,{recursive:!0,force:!0})}let o=await this.checkEngine(Ae(n,...t.executable.split(/[\\/]/)));if(o){await Sr(n,{recursive:!0,force:!0});for(let i of t.files)await Sr(this.blob(i.sha256),{force:!0});throw new Qb(o)}for(let i of t.files)await Sr(this.blob(i.sha256),{force:!0})}progress(e,t,r=!1){let n=Date.now();if(!r&&n-t.lastProgress<uI)return;t.lastProgress=n,this.list().catch(()=>null).then((s)=>{if(!s)return;let o=s.models.find((a)=>a.id===e.id);if(!o||this.installs.get(e.id)!==t)return;let i=Math.max((n-t.startedAt)/1000,0.001);this.emit({type:"model.progress",id:e.id,state:t.state,receivedBytes:o.receivedBytes,size:o.size,bytesPerSecond:Math.round(t.transferred/i)})})}async download(e,t,r){let n=this.blob(t.sha256);if(await Bun.file(n).exists())return;this.notMoving(),await Bs(Ae(this.root,"blobs"),{recursive:!0}),await Ab(`${n}.lock`,r.controller.signal,async()=>{if(await Bun.file(n).exists())return;await this.fetchFile(e,t,r)},{onWait:async()=>{r.state="downloading",r.current={sha256:t.sha256,bytes:await Ui(`${n}.part`)},this.progress(e,r,!0)}})}async fetchFile(e,t,r){let{signal:n}=r.controller,s=this.blob(t.sha256),o=`${s}.part`,i=await Ui(o);if(i>t.size)await Sr(o,{force:!0}),i=0;if(r.state="downloading",r.current={sha256:t.sha256,bytes:i},i<t.size){let c=await this.fetch(t.url,{headers:i>0?{range:`bytes=${i}-`}:{},signal:n});if(!c.ok||!c.body)throw new le(`Could not download ${t.name} (HTTP ${c.status})`,"downloadFailed",{file:t.name,status:c.status});let l=c.status===206;if(!l)r.current.bytes=0;let u=await C5(o,l?"r+":"w");try{for await(let d of c.body){if(r.current.bytes+d.byteLength>t.size)throw new le(`${t.name} is larger than expected`,"downloadTooLarge",{file:t.name});await u.write(d,0,d.byteLength,r.current.bytes),r.current.bytes+=d.byteLength,r.transferred+=d.byteLength,this.progress(e,r)}}finally{await u.close()}if(n.throwIfAborted(),r.current.bytes!==t.size||await Ui(o)!==t.size)throw new le(`The download of ${t.name} was cut short`,"downloadCutShort",{file:t.name})}r.state="verifying",this.progress(e,r,!0);let a=new Bun.CryptoHasher("sha256");for await(let c of Bun.file(o).stream())n.throwIfAborted(),a.update(c);if(a.digest("hex")!==t.sha256)throw await Sr(o,{force:!0}),new le(`${t.name} did not match its expected hash`,"hashMismatch",{file:t.name});await el(o,s),r.current=null,r.state="downloading"}async cancel(e){this.spec(e);let t=this.installs.get(e);if(!t)return;if(t.controller.abort(),t.state==="queued"){this.installs.delete(e),this.emit({type:"models.changed"});return}await this.settled(e)}async settled(e){while(this.installs.has(e))await new Promise((t)=>{let r=this.subscribe((n)=>{if(n.type!=="models.changed")return;r(),t()})})}onLetGo(e){this.holders.add(e)}async letGo(){for(let e of this.holders)await e().catch(()=>{})}async remove(e){let t=this.spec(e);this.notMoving(),await this.cancel(e),await this.letGo(),this.errors.delete(e),await Sr(this.marker(e),{force:!0});let r=await this.neededHashes();for(let n of ss(t.variants.flatMap((s)=>s.files))){if(r.has(n.sha256))continue;if(zi(`${this.blob(n.sha256)}.lock`))continue;await Sr(this.blob(n.sha256),{force:!0}),await Sr(`${this.blob(n.sha256)}.part`,{force:!0})}await this.removeUnusedEngines(),this.emit({type:"models.changed"})}async removeUnusedEngines(){let e=await this.onDisk(),t=new Set([...(await this.installedVariants(e.complete)).values(),...[...this.installs.values()].map((r)=>r.variant)].map((r)=>r.engine));for(let r of this.engines){if(t.has(r.id))continue;for(let n of r.builds){if(zi(`${this.engineDir(n.id)}.lock`))continue;await Sr(this.engineDir(n.id),{recursive:!0,force:!0});for(let s of n.files)await Sr(this.blob(s.sha256),{force:!0}),await Sr(`${this.blob(s.sha256)}.part`,{force:!0})}}}async demo(e,t,r="original"){let n=this.spec(e).demos[t];if(!n)throw new Ee("Demo not found");let s=new Bun.CryptoHasher("sha256").update(n.url).digest("hex"),o=Ae(this.root,"demos",s);if(!await Bun.file(o).exists())await this.once(s,()=>this.fetchDemo(n.url,o));let i=Bun.file(o),a=Yn(await i.slice(0,32).bytes());if(!a)throw Error("The stored demo is not an image or a video");let c=`${s}.${r}`;if(r==="original"||!a.startsWith("image/")||a==="image/gif"||this.unshrinkable.has(c))return{blob:i,mime:a};let l=`${o}.${r}.webp`;if(!await Bun.file(l).exists()){if(!await this.once(c,()=>L5(o,l,pI[r])).catch(()=>!1))return this.unshrinkable.add(c),{blob:i,mime:a}}return{blob:Bun.file(l),mime:"image/webp"}}once(e,t){let r=this.demos.get(e);if(!r)r=t().finally(()=>this.demos.delete(e)),this.demos.set(e,r);return r}async fetchDemo(e,t){let r=await this.fetch(e,{signal:AbortSignal.timeout(120000)});if(!r.ok)throw Error(`Could not download the demo (HTTP ${r.status})`);if(Number(r.headers.get("content-length"))>lI)throw Error("The demo is too large");let n=await r.bytes();if(n.byteLength>lI||!Yn(n))throw Error("The demo is not an image or a video");await Bs(Ae(this.root,"demos"),{recursive:!0});let s=`${t}.${crypto.randomUUID()}.tmp`;return await Bun.write(s,n),await el(s,t),t}async idle(){await this.moveTask;while(this.installs.size>0)await this.queue}async close(){for(let e of this.installs.values())e.controller.abort();await this.idle()}}var aI,lI=67108864,uI=250,Jb,Qb,z5=30000,pI,fI=(e)=>e==="original"||Object.hasOwn(pI,e),Ui=(e)=>tl(e).then((t)=>t.size,()=>0),ss=(e)=>[...new Map(e.map((t)=>[t.sha256,t])).values()],En=(e)=>e.reduce((t,r)=>t+r,0),D5=0.9,j5=3000;var hI=b(()=>{Ar();zb();Ud();mb();Rb();B1();Gc();jd();Z1();Zb();Kb();aI=["blobs","installed","engines","demos","loras","checkpoints","broken-engines.json"];Jb=/^[a-z0-9][a-z0-9.-]*$/;Qb=class Qb extends Error{};pI={card:960,large:2560}});import{copyFile as U5,link as B5,mkdir as gI,readdir as ev,readFile as q5,rename as tv,rm as Xt,stat as rv}from"fs/promises";import{freemem as F5}from"os";import{dirname as V5,join as Ot}from"path";function nB(e){return Math.max(100,Math.round(e/4/50)*50)}function sB(e,t,r=eB){let n=(t.find((o)=>o.trim())??"").trim();return[(n?`${e}, ${n}`:e).replace(/-{2,}/g,"-").replace(/\s+/g," "),`--w ${r} --h ${r} --s ${tB} --l 6 --d ${rB}`,"--n blurry, low quality"].join(" ")}function oB(e,t){if(t.step>0||!(e instanceof le))return!1;if(e.code!=="trainingFailed")return!1;return/out of memory|OUT_OF_MEMORY|Cannot allocate memory/i.test(String(e.params?.reason??""))}async function aB(){if(process.platform==="linux"){let t=(await q5("/proc/meminfo","utf8").catch(()=>"")).match(/MemAvailable:\s+(\d+)/)?.[1];if(t)return Number(t)*1024}return F5()}function lB(e){let t=e.split(":").map(Number);if(t.some((r)=>Number.isNaN(r)))return null;return t.reduce((r,n)=>r*60+n,0)}function Bi(e,t,r){let n=t;while(n<e.length&&r.includes(e[n]??""))n++;return n}function uB(e,t){let r=Bi(e,t," \t"),n=Bi(e,r,rp);if(n===r||e[n]!=="/")return null;let s=e.slice(r,n);r=n+1;let o=Bi(e,r,rp);if(o===r)return null;let i=e.slice(r,o);if(r=Bi(e,o," \t"),e[r]!=="[")return null;let a=Bi(e,r+1,`${rp}:`);if(a===r+1||e[a]!=="<")return null;let c=Bi(e,a+1,`${rp}:?`);if(c===a+1)return null;return[s,i,e.slice(a+1,c)]}function dB(e){let t=e.indexOf("steps:");if(t<0)return null;for(let r=e.indexOf("|",t);r>=0;r=e.indexOf("|",r+1)){let n=uB(e,r+1);if(n)return n}return null}function pB(e){let t=dB(e);if(!t)return null;let[r,n,s]=t,o=Number(n);if(!(o>0))return null;return{step:Math.min(Number(r),o),steps:o,secondsLeft:s.includes("?")?null:lB(s)}}function fB(e){if(/caching (latents|text encoder)/i.test(e))return"caching";if(/saving (model|checkpoint)|model saved/i.test(e))return"saving";if(/loading|load (state dict|vae|unet|text encoder)|building/i.test(e))return"loading";return null}class nv{options;listeners=new Set;installing=null;installError=null;ready=null;training=null;trainingController=null;starting=!1;lastEmit=0;pending=null;finishing=null;leftovers;constructor(e){this.options={platform:process.platform,fetch:globalThis.fetch,run:iB,freeMemory:aB,memoryCheckMs:Y5,...e,letGo:e.letGo??(async()=>{})},this.leftovers=Promise.all(["runs","samples"].map((t)=>Xt(this.path(t),{recursive:!0,force:!0}).catch(()=>{}))).then(()=>{})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get windows(){return this.options.platform==="win32"}path(...e){return Ot(this.options.dir,...e)}get python(){return this.windows?this.path("venv","Scripts","python.exe"):this.path("venv","bin","python")}get scripts(){return this.path("sd-scripts")}get uvEnv(){return{UV_PYTHON_INSTALL_DIR:this.path("python"),UV_CACHE_DIR:this.path("cache"),UV_NO_CONFIG:"1",UV_PYTHON_PREFERENCE:"only-managed",PYTHONUNBUFFERED:"1",PYTHONIOENCODING:"utf-8"}}async isReady(){if(this.ready==null){let e=await Bun.file(this.path("ready.json")).json().catch(()=>null);this.ready=e?.version===yI}return this.ready}async status(){return{state:this.installing?"installing":await this.isReady()?"ready":"missing",install:this.installing&&{step:this.installing.step,receivedBytes:this.installing.receivedBytes,totalBytes:this.installing.totalBytes},error:this.installError,downloadBytes:J5,training:this.training&&{...this.training}}}changed(e=!1){let t=()=>{this.pending=null,this.lastEmit=Date.now(),this.status().then((r)=>{for(let n of this.listeners)try{n({type:"trainer.changed",trainer:r})}catch(s){console.error("A trainer listener failed",s)}})};if(e||Date.now()-this.lastEmit>=wI){if(this.pending)clearTimeout(this.pending);t()}else if(!this.pending)this.pending=setTimeout(t,wI)}async download(e,t,r){let n=e.url.split("/").at(-1)??e.url,s=await this.options.fetch(e.url,{signal:r}).catch((l)=>{if(r.aborted)throw l;throw new le(`Could not download ${n}: ${l instanceof Error?l.message:l}`,"noConnection")});if(!s.ok||!s.body)throw new le(`Could not download the trainer (HTTP ${s.status})`,"downloadFailed",{file:e.url.split("/").at(-1)??e.url,status:s.status});let o=`${t}.part`,i=Bun.file(o).writer(),a=new Bun.CryptoHasher("sha256"),c=0;try{for await(let l of s.body){if(c+=l.byteLength,c>e.size)throw new le("The download is larger than expected","downloadTooLarge",{file:e.url.split("/").at(-1)??e.url});if(a.update(l),i.write(l),this.installing)this.installing.receivedBytes=c,this.installing.totalBytes=e.size;this.changed()}}finally{await i.end()}if(a.digest("hex")!==e.sha256)throw await Xt(o,{force:!0}),new le("The trainer did not match its expected hash","hashMismatch",{file:e.url.split("/").at(-1)??e.url});await tv(o,t)}async step(e,t,r){t.throwIfAborted();let n=this.options.run(e,{cwd:r,env:this.uvEnv}),s=()=>n.kill();t.addEventListener("abort",s,{once:!0});let o=[];try{for await(let a of n.output){if(a.trim())o.push(a.trim());if(o.length>20)o.shift()}let i=await n.exited;if(t.throwIfAborted(),i!==0){let a=o.filter((c)=>/error|fail|not found|no matching/i.test(c)).at(-1)??o.at(-1)??`it stopped with code ${i}`;throw new le(`Installing the trainer failed: ${a}`,"trainerInstallFailed",{reason:a,exitCode:i})}}finally{t.removeEventListener("abort",s)}}async find(e,t){for(let r of await ev(e,{recursive:!0}).catch(()=>[]))if(r.split(/[\\/]/).at(-1)===t)return Ot(e,r);return null}async install(){if(this.installing||this.starting||this.training?.state==="running")throw new O("The trainer is busy","trainerBusy");if(process.arch!=="x64")throw new O("The trainer runs on 64-bit Intel and AMD processors only","trainerNoCuda");let e=this.windows?"win32":this.options.platform==="linux"?"linux":null;if(!e)throw new O("The trainer runs on Windows and Linux only","trainerNoCuda");let t=new AbortController;this.installing={step:"uv",receivedBytes:null,totalBytes:null,controller:t},this.installError=null,this.ready=!1,this.changed(!0),this.installNow(e,t.signal).then(()=>{this.ready=!0}).catch(async(r)=>{if(!t.signal.aborted)this.installError=$s(r);for(let n of["cache","downloads"])await Xt(this.path(n),{recursive:!0,force:!0}).catch(()=>{})}).finally(()=>{this.installing=null,this.changed(!0)})}setStep(e){if(!this.installing)return;this.installing.step=e,this.installing.receivedBytes=null,this.installing.totalBytes=null,this.changed(!0)}async installNow(e,t){let r=this.options.dir;await Xt(this.path("ready.json"),{force:!0}),await Bun.write(this.path("downloads",".keep"),"");let n=this.path("downloads",e==="win32"?"uv.zip":"uv.tar.gz");if(await this.download(H5[e],n,t),await Xt(this.path("uv"),{recursive:!0,force:!0}),e==="win32")await Yc(n,this.path("uv"));else await Bun.write(this.path("uv",".keep"),""),await this.step(["tar","-xzf",n,"-C",this.path("uv")],t);let s=await this.find(this.path("uv"),e==="win32"?"uv.exe":"uv");if(!s)throw new le("uv was not in its archive","trainerInstallFailed",{reason:"uv was not in its archive"});this.setStep("scripts");let o=this.path("downloads","sd-scripts.zip");await this.download(Z5,o,t);let i=this.path("sd-scripts.tmp");await Xt(i,{recursive:!0,force:!0}),await Yc(o,i);let[a]=await ev(i);if(!a)throw new le("The training scripts' archive was empty","trainerInstallFailed",{reason:"empty archive"});await Xt(this.scripts,{recursive:!0,force:!0}),await tv(Ot(i,a),this.scripts),await Xt(i,{recursive:!0,force:!0}),this.setStep("python"),await Xt(this.path("venv"),{recursive:!0,force:!0}),await this.step([s,"venv","--python",G5,this.path("venv")],t,r),this.setStep("packages"),await this.step([s,"pip","install","--python",this.python,"-r","requirements.txt",...K5,"--extra-index-url",W5,"--index-strategy","unsafe-best-match"],t,this.scripts),await Xt(this.path("cache"),{recursive:!0,force:!0}),await Xt(this.path("downloads"),{recursive:!0,force:!0}),this.setStep("checking");try{await this.step([this.python,"-c","import sys, torch; sys.exit(0 if torch.cuda.is_available() else 3)"],t)}catch(c){if(t.aborted||!(c instanceof le)||c.params.exitCode!==3)throw c;throw new le("PyTorch cannot use a graphics card here","trainerNoCuda")}await Bun.write(this.path("ready.json"),JSON.stringify({version:yI,installedAt:Date.now()}))}cancelInstall(){this.installing?.controller.abort()}async remove(){if(this.installing||this.training?.state==="running")throw new O("The trainer is busy","trainerBusy");await Xt(this.options.dir,{recursive:!0,force:!0}),this.ready=!1,this.installError=null,this.changed(!0)}async assertCanTrain(){if(!await this.isReady())throw new O("Install the trainer first","trainerMissing");if(this.starting||this.training?.state==="running"||this.installing)throw new O("The trainer is busy","trainerBusy")}async train(e){await this.assertCanTrain(),this.starting=!0;try{return await this.start(e)}finally{this.starting=!1}}async start(e){let t=e.name.trim(),r=e.trigger.trim();if(!t||t.length>80)throw new O("Give the LoRA a name of at most 80 characters","trainingBadName",{max:80});if(!cB.test(r))throw new O("The trigger must be one word of 2 to 40 letters or digits","trainingBadTrigger",{min:2,max:40});if(e.pictures.length<jo||e.pictures.length>Uo)throw new O(`Training needs ${jo} to ${Uo} pictures`,"trainingNeedsPictures",{min:jo,max:Uo});let n=Math.round(e.steps);if(!(n>=qi&&n<=Fi))throw new O(`Steps must be between ${qi} and ${Fi}`,"trainingBadSteps",{min:qi,max:Fi});let s=await this.options.baseModel(),o=crypto.randomUUID(),i=new AbortController;this.trainingController=i,this.training={id:o,name:t,trigger:r,startedBy:e.startedBy??null,state:"running",stage:"waitingGpu",step:0,steps:n,secondsLeft:null,startedAt:Date.now(),finishedAt:null,freeMemoryBytes:null,loraId:null,samples:[],savedStep:null,keptStep:null,error:null},this.changed(!0);let a=this.training;return this.trainNow(a,{...e,name:t,trigger:r,steps:n},s,i.signal).then((c)=>{a.state="done",a.loraId=c}).catch((c)=>{if(i.signal.aborted)a.state="canceled";else a.state="failed",a.error=$s(c)}).finally(()=>{if(a.finishedAt=Date.now(),a.secondsLeft=null,this.trainingController===i)this.trainingController=null;this.changed(!0)}),{...a}}cancelTraining(){this.trainingController?.abort()}finishTraining(){let e=this.training;if(e?.state!=="running"||e.savedStep==null)throw new O("Nothing is saved to keep yet","trainingNothingSaved");if(e.step>=e.steps)return;this.finishing?.()}sampleFile(e,t){let r=this.training;if(!r||r.id!==e||!r.samples.includes(t))return null;return this.path("samples",e,`${t}.png`)}async trainNow(e,t,r,n){let s=this.path("runs",e.id);await this.leftovers;try{let o=Ot(s,"dataset","10_subject");await Xt(this.path("samples"),{recursive:!0,force:!0});for(let[l,u]of t.pictures.entries()){let d=Ot(o,String(l).padStart(3,"0"));await Bun.write(`${d}.${u.extension}`,u.data);let p=u.caption.replace(/\s+/g," ").trim();await Bun.write(`${d}.txt`,p?`${t.trigger}, ${p}`:t.trigger)}await Bun.write(Ot(s,"dataset.toml"),["[general]",'caption_extension = ".txt"',"shuffle_caption = false","keep_tokens = 1","","[[datasets]]","resolution = 1024","batch_size = 1","enable_bucket = true",""," [[datasets.subsets]]",` image_dir = ${mB(o)}`," num_repeats = 10",""].join(`
|
|
82
|
-
`)),await Bun.write(Ot(s,"samples.txt"),sB(t.trigger,t.pictures.map((l)=>l.caption)));let i=this.options.gpu.acquire(Q5,n),a=await i.next();while(!a.done)a=await i.next();let c=a.value;try{await this.options.letGo().catch(()=>{});let l=await this.named(await this.options.baseModel().catch(()=>r),e.id,s);try{try{return await this.runTraining(e,t,l.file,s,n)}catch(u){if(n.aborted||!oB(u,e))throw u;return await Xt(Ot(s,"out"),{recursive:!0,force:!0}),e.stage="loading",this.changed(!0),await this.runTraining(e,t,l.file,s,n)}}finally{if(l.made)await Xt(l.file,{force:!0}).catch(()=>{})}}finally{c.release()}}finally{await Xt(s,{recursive:!0,force:!0}).catch(()=>{})}}async named(e,t,r){if(e.file.toLowerCase().endsWith(".safetensors"))return{file:e.file,made:!1};let n=Ot(e.scratch,`train-${t}.safetensors`);try{return await gI(e.scratch,{recursive:!0}),await B5(e.file,n),{file:n,made:!0}}catch{let s=Ot(r,"base.safetensors");return await U5(e.file,s),{file:s,made:!1}}}async collectSamples(e,t,r=!1){try{await this.moveSamples(e,t,r)}catch{}}async moveSamples(e,t,r){let n=Ot(t,"sample"),s=await ev(n).catch(()=>[]);for(let o of s){let i=Number(o.match(/^lora_(\d{6})_/)?.[1]);if(!i||e.samples.includes(i))continue;if(!r&&i>=e.step)continue;let a=this.path("samples",e.id,`${i}.png`);if(await gI(V5(a),{recursive:!0}),await tv(Ot(n,o),a).then(()=>!0,()=>!1))e.samples=[...e.samples,i].sort((c,l)=>c-l)}}async runTraining(e,t,r,n,s){e.stage="loading",this.changed(!0);let o=Ot(n,"out"),i=nB(t.steps),a=this.options.run([this.python,"sdxl_train_network.py","--pretrained_model_name_or_path",r,"--dataset_config",Ot(n,"dataset.toml"),"--output_dir",o,"--output_name","lora","--save_model_as","safetensors","--metadata_title",t.name,"--network_module","networks.lora","--network_dim","16","--network_alpha","8","--network_train_unet_only","--learning_rate","1e-4","--optimizer_type","AdamW8bit","--lr_scheduler","constant","--max_train_steps",String(t.steps),"--mixed_precision","bf16","--full_bf16","--lowram","--save_precision","fp16","--no_half_vae","--cache_latents","--cache_text_encoder_outputs","--gradient_checkpointing","--sdpa","--seed","42","--max_data_loader_n_workers","0","--save_every_n_steps",String(i),"--sample_every_n_steps",String(i),"--sample_prompts",Ot(n,"samples.txt"),"--sample_sampler","euler_a"],{cwd:this.scripts,env:this.uvEnv}),c=!1,l=!1,u=()=>a.kill();s.addEventListener("abort",u,{once:!0}),this.finishing=()=>{l=!0,a.kill()};let d=!0,p=!1,f=setInterval(async()=>{if(p)return;p=!0;try{await m()}finally{p=!1}},this.options.memoryCheckMs),m=async()=>{let v=await this.options.freeMemory().catch(()=>null);if(!d)return;if(e.freeMemoryBytes=v,v!=null&&v<X5&&!c)c=!0,a.kill();if(await this.collectSamples(e,o),d)this.changed()},h=[];try{for await(let C of a.output){if(C.trim())h.push(C.trim());if(h.length>30)h.shift();let k=pB(C);if(k){e.stage=k.step>=k.steps?"saving":"training",e.step=k.step,e.secondsLeft=k.secondsLeft;let y=Math.floor((k.step-1)/i)*i;if(y>(e.savedStep??0)&&await rv(Ot(o,bI(y))).catch(()=>null))e.savedStep=y;this.changed();continue}let P=fB(C);if(P&&e.stage!=="training")e.stage=P,this.changed()}let v=await a.exited;s.throwIfAborted(),d=!1,await this.collectSamples(e,o,!0);let _=v===0&&!c&&await rv(Ot(o,"lora.safetensors")).catch(()=>null)!=null;if(l&&!_&&e.savedStep!=null){e.stage="saving",this.changed(!0);let C=await this.options.loras.add(Bun.file(Ot(o,bI(e.savedStep))),`${t.name}.safetensors`);return e.keptStep=e.savedStep,C.id}if(c)throw new le("Training stopped before the computer ran out of memory","trainingOutOfMemory");if(v!==0){let C=h.filter((k)=>/error|exception|out of memory/i.test(k)).at(-1)??h.at(-1)??`it stopped with code ${v}`;throw new le(`Training failed: ${C}`,"trainingFailed",{reason:C})}}finally{d=!1,clearInterval(f),s.removeEventListener("abort",u),this.finishing=null,a.kill()}e.stage="saving",this.changed(!0);let g=Ot(o,"lora.safetensors");if(!await rv(g).catch(()=>null))throw new le("Training made no LoRA","trainingFailed",{reason:"no file was written"});return(await this.options.loras.add(Bun.file(g),`${t.name}.safetensors`)).id}}var yI="sd-scripts-cb70b96+torch-2.14.1-cu130+py3.11",Z5,H5,G5="3.11",K5,W5="https://download.pytorch.org/whl/cu130",J5=6442450944,Q5,X5=1610612736,Y5=5000,wI=1000,jo=3,Uo=200,qi=100,Fi=4000,eB=768,tB=20,rB=42,bI=(e)=>`lora-step${String(e).padStart(8,"0")}.safetensors`,iB=(e,t)=>{let r=Bun.spawn(e,{cwd:t.cwd,env:{...process.env,...t.env},stdin:"ignore",stdout:"pipe",stderr:"pipe"});async function*n(){let s=[],o={wake:null},i=2;for(let a of[r.stdout,r.stderr])(async()=>{let c="";try{for await(let l of a.pipeThrough(new TextDecoderStream)){let u=(c+l).split(/[\r\n]/);c=u.pop()??"",s.push(...u),o.wake?.()}}catch{}if(c)s.push(c);i--,o.wake?.()})();while(i>0||s.length>0){let a=s.shift();if(a!=null){yield a;continue}await new Promise((c)=>{o.wake=c}),o.wake=null}}return{output:n(),exited:r.exited,kill:()=>{if(r.exitCode!=null||r.signalCode!=null)return;if(process.platform==="win32")Bun.spawn(["taskkill","/T","/F","/PID",String(r.pid)],{stdout:"ignore",stderr:"ignore"});else r.kill()}}},cB,rp="0123456789",mB=(e)=>JSON.stringify(e);var vI=b(()=>{Ar();Kb();Z5={url:"https://github.com/kohya-ss/sd-scripts/archive/cb70b96858477e716a2096292ab8aab433277f38.zip",sha256:"13587ab358c5ecb878a991a391ca924cb37ff1d427805b1476f41bbf23fcc493",size:6689584},H5={linux:{url:"https://github.com/astral-sh/uv/releases/download/0.9.30/uv-x86_64-unknown-linux-gnu.tar.gz",sha256:"8b3762374972daa7a74bbc6896cc73229ca69a07403dd9f9ea3805a51ffd7582",size:22237571},win32:{url:"https://github.com/astral-sh/uv/releases/download/0.9.30/uv-x86_64-pc-windows-msvc.zip",sha256:"875981be7908295937dee09532bb66d576986d4f223259e171b0c767c885897a",size:21763186}},K5=["torch==2.14.1+cu130","torchvision==0.29.1+cu130"],Q5=Number.MAX_SAFE_INTEGER;cB=/^[\p{L}\p{N}_-]{2,40}$/u});class sv{adapters=new Map;models=new Map;register(e){if(this.adapters.has(e.id))throw Error(`Provider already registered: ${e.id}`);this.adapters.set(e.id,e);for(let t of e.listModels())this.models.set(t.id,t);return this}refresh(e){let t=this.adapters.get(e);if(!t)return;for(let[r,n]of this.models)if(n.providerId===e)this.models.delete(r);for(let r of t.listModels())this.models.set(r.id,r)}adapter(e){return this.adapters.get(e)}listAdapters(){return[...this.adapters.values()]}model(e){return this.models.get(e)}listModels(){return[...this.models.values()]}}import{readFile as hB,rename as gB,rm as yB,writeFile as wB}from"fs/promises";import{basename as bB,join as _I}from"path";async function xI(e,t){for(let r of[np(e),iv(e)]){let n=`${r}.${process.pid}.tmp`;await wB(n,JSON.stringify(t)),await gB(n,r)}}async function SI(e){for(let t of[np(e),iv(e)])if((await ov(t,()=>!0))?.pid===process.pid)await yB(t,{force:!0})}async function $I(e,t=vB){return await ov(np(e),t)??await ov(iv(e),t)}async function ov(e,t){try{let r=JSON.parse(await hB(e,"utf8"));if(typeof r.pid!=="number"||typeof r.url!=="string"||!/^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+$/.test(r.url))return null;return t(r.pid)?{pid:r.pid,url:r.url}:null}catch{return null}}var np=(e)=>_I(e,"hatchlight.server.json"),iv=(e)=>_I(e,Vc(bB(np(e)))),vB=(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}};var kI=()=>{};function xB(e,t){let r=e.capabilities;if(t.referenceAssetIds.length>r.maxReferenceImages)throw r.maxReferenceImages===0?new O(`${e.name} does not accept reference images`,"noReferences",{model:e.name}):new O(`${e.name} accepts at most ${r.maxReferenceImages} reference images`,"tooManyReferences",{model:e.name,count:r.maxReferenceImages});if(r.upscale!=null&&t.referenceAssetIds.length===0)throw new O(`${e.name} needs a picture to work on`,"needsPicture",{model:e.name});if(t.maskAssetId!=null){if(t.referenceAssetIds.length!==1)throw new O("A mask needs exactly one reference image to redraw","maskWithoutReference");if(r.mask==null)throw new O(`${e.name} cannot redraw only part of a picture`,"noMask",{model:e.name})}let n=r.durations??[],s=t.durationSeconds??n[0];return{...t,count:Math.min(t.count,r.maxCount),durationSeconds:s==null||n.length===0?void 0:n.reduce((o,i)=>Math.abs(i-s)<Math.abs(o-s)?i:o),aspectRatio:t.aspectRatio&&r.aspectRatios.includes(t.aspectRatio)&&!(r.strength!=null&&t.referenceAssetIds.length>0)?t.aspectRatio:void 0,seed:r.seed?t.seed:void 0,strength:r.strength!=null&&t.referenceAssetIds.length>0?t.strength??(t.maskAssetId!=null?r.mask:void 0)??r.strength:void 0,loras:r.loraBase&&t.loras?.length?t.loras:void 0}}class av{deps;constructor(e){this.deps=e}listModels(){return this.deps.registry.listModels()}async listProviders(e){let t=await this.deps.keys.list(e),r=await this.deps.keys.sources?.(e)??null;return this.deps.registry.listAdapters().map((n)=>({id:n.id,name:n.name,requiresKey:n.requiresKey,hasKey:t.includes(n.id)||Boolean(n.keyEnv&&process.env[n.keyEnv]),...r&&{keys:{personal:r.personal.includes(n.id),server:r.server.includes(n.id)||Boolean(n.keyEnv&&process.env[n.keyEnv])}}}))}async setProviderKey(e,t,r){if(this.requireProvider(t),!r.trim())throw new O("The key is empty","emptyKey");await this.deps.keys.set(e,t,r.trim())}async deleteProviderKey(e,t){this.requireProvider(t),await this.deps.keys.delete(e,t)}requireProvider(e){if(!this.deps.registry.adapter(e))throw new Ee(`Unknown provider: ${e}`,"unknownProvider",{provider:e})}listSessions(e){return this.deps.repo.listSessions(e)}async getSession(e,t){let r=await this.deps.repo.getSession(e,t);if(!r)throw new Ee("Session not found","sessionNotFound");return{...r,turns:await this.deps.repo.listTurns(e,t)}}async startSession(e,t){let r=Date.now(),n={id:Ft("ses"),userId:e.userId,title:t.slice(0,80),createdAt:r,updatedAt:r};return await this.deps.repo.createSession(n),n}async deleteSession(e,t){let r=await this.getSession(e,t);for(let n of r.turns.flatMap((s)=>s.jobs))await this.deps.engine.cancel(n.id);await this.deps.repo.deleteSession(e,t)}assertRoom(e){let t=this.deps.storageRefusal?.(e.userId);if(t)throw t}async createTurn(e,t){this.assertRoom(e);let{sessionId:r,modelIds:n,...s}=t,o=RT.safeParse(s);if(!o.success)throw new O(o.error.issues[0]?.message??"Invalid input");let i=o.data;if(n.length===0)throw new O("Choose at least one model","noModel");let a=[...new Set(n)].map((h)=>{let g=this.deps.registry.model(h);if(!g)throw new O(`Unknown model: ${h}`,"unknownModel",{model:h});return g}),c=[...i.referenceAssetIds,...i.maskAssetId!=null?[i.maskAssetId]:[]],l=await this.deps.repo.getAssets(e,c);if(l.length!==new Set(c).size)throw new O("A reference image was not found","referenceNotFound");if(l.some((h)=>!h.mime.startsWith("image/")))throw new O("Only images can be used as references","referenceNotImage");let u=a.map((h)=>xB(h,i)),d=Date.now(),p;if(r){let h=await this.deps.repo.getSession(e,r);if(!h)throw new Ee("Session not found","sessionNotFound");p={...h,updatedAt:d}}else p={id:Ft("ses"),userId:e.userId,title:i.prompt.slice(0,80),createdAt:d,updatedAt:d},await this.deps.repo.createSession(p);let f={id:Ft("trn"),sessionId:p.id,userId:e.userId,prompt:i.prompt,referenceAssetIds:i.referenceAssetIds,createdAt:d},m=a.map((h,g)=>({id:Ft("job"),turnId:f.id,position:g,userId:e.userId,providerId:h.providerId,modelId:h.id,params:u[g],status:"queued",handle:null,error:null,errorCode:null,errorParams:null,costUsd:null,createdAt:d,startedAt:null,finishedAt:null,tokenId:e.tokenId??null}));await this.deps.repo.createTurn(f,m);for(let h of m)this.deps.engine.enqueue(h);return{session:p,turn:{...f,jobs:m.map((h)=>({...h,assets:[]}))}}}async cancelJob(e,t){let r=await this.deps.repo.findJob(t);if(!r||r.userId!==e.userId)throw new Ee("Job not found","jobNotFound");await this.deps.engine.cancel(t)}async retryJob(e,t){this.assertRoom(e);let r=await this.deps.repo.findJob(t);if(!r||r.userId!==e.userId)throw new Ee("Job not found","jobNotFound");await this.deps.engine.retry(r,e.tokenId??null)}jobPreview(e,t){let r=this.deps.engine.preview(e.userId,t);if(!r)throw new Ee("No preview","jobNotFound");return r}async deleteAsset(e,t){let[r]=await this.deps.repo.getAssets(e,[t]);if(!r)throw new Ee("Asset not found","assetNotFound");let{sharing:n}=await this.deps.repo.deleteAsset(e,t);if(n===0)await this.deps.assets.remove(e,r.hash)}async uploadAsset(e,t){this.assertRoom(e);let r=Yn(t);if(!r||!_B.includes(r))throw new O("Only PNG, JPEG and WebP images can be uploaded","uploadType");let n=await this.deps.assets.put(e,t),s={id:Ft("ast"),userId:e.userId,kind:"upload",jobId:null,hash:n.hash,mime:r,size:n.size,prompt:null,modelId:null,params:null,createdAt:Date.now()};return await this.deps.repo.createAsset(s),s}async getAssetFile(e,t){let[r]=await this.deps.repo.getAssets(e,[t]),n=r&&await this.deps.assets.get(e,r.hash);if(!r||!n)throw new Ee("Asset not found","assetNotFound");return{asset:r,blob:n}}listGallery(e,t){return this.deps.repo.listGallery(e,t)}}var _B;var TI=b(()=>{Ar();Br();_B=["image/png","image/jpeg","image/webp"]});import{mkdir as PI,rename as EI,writeFile as II}from"fs/promises";import{dirname as AI}from"path";class lv{path;pending=Promise.resolve();constructor(e){this.path=e}async read(){let e=Bun.file(this.path);if(!await e.exists())return{};return await e.json().catch(()=>({}))}async get(e){let t=(await this.read())[e.userId]??{};return{translateWith:xc(t.translateWith)?t.translateWith:cv.translateWith,improveWith:Rs(t.improveWith)?t.improveWith:cv.improveWith,assistantWith:Rs(t.assistantWith)?t.assistantWith:cv.assistantWith}}set(e,t){let r=this.pending.then(async()=>{let n=await this.read();n[e.userId]={...n[e.userId],...t},await PI(AI(this.path),{recursive:!0});let s=`${this.path}.${crypto.randomUUID()}.tmp`;return await II(s,JSON.stringify(n,null,2)),await EI(s,this.path),this.get(e)});return this.pending=r.catch(()=>{}),r}moveUser(e,t){let r=this.pending.then(async()=>{let n=await this.read();if(!Object.hasOwn(n,e)||Object.hasOwn(n,t))return;n[t]=n[e],delete n[e],await PI(AI(this.path),{recursive:!0});let s=`${this.path}.${crypto.randomUUID()}.tmp`;await II(s,JSON.stringify(n,null,2)),await EI(s,this.path)});return this.pending=r.catch(()=>{}),r}}var cv;var RI=b(()=>{Br();cv={translateWith:"local",improveWith:"auto",assistantWith:"auto"}});function CI(e,t="1:1"){let[r=1,n=1]=t.split(":").map(Number),s=96/Math.max(r,n),o=Math.max(1,Math.round(r*s)),i=Math.max(1,Math.round(n*s)),a=new Bun.CryptoHasher("sha256").update(e).digest(),c=Math.ceil(o*3/4)*4,l=new Uint8Array(54+c*i),u=new DataView(l.buffer);l.set([66,77]),u.setUint32(2,l.length,!0),u.setUint32(10,54,!0),u.setUint32(14,40,!0),u.setInt32(18,o,!0),u.setInt32(22,i,!0),u.setUint16(26,1,!0),u.setUint16(28,24,!0);for(let d=0;d<i;d++){let p=d/Math.max(1,i-1);for(let f=0;f<o;f++)for(let m=0;m<3;m++){let h=a[m]??0,g=a[m+3]??0;l[54+d*c+f*3+m]=h+(g-h)*p}}return l}class sp{id;modelNames;name;requiresKey=!1;resumable=!1;maxConcurrency;gate=null;failWith=null;failures=[];delayMs=0;outputUrl=null;submitted=[];canceled=[];constructor(e="fake",t=["alpha","beta"]){this.id=e;this.modelNames=t;this.name=`Fake (${e})`}listModels(){return this.modelNames.map((e)=>({id:`${this.id}/${e}`,providerId:this.id,providerModelId:e,name:`Fake ${e}`,media:"image",operations:["generate","edit"],capabilities:{aspectRatios:["1:1","16:9"],seed:!0,maxCount:2,maxReferenceImages:e==="alpha"?2:0,...e==="alpha"&&{mask:0.85},...e==="beta"&&{englishPrompts:!0}},pricing:{usdPerOutput:0.01}}))}keysUsed=[];async submit(e,t){this.keysUsed.push(t?.apiKey);let r={model:e.model.id,prompt:e.params.prompt,count:e.params.count,aspectRatio:e.params.aspectRatio,...e.mask&&{mask:e.mask.data}};return this.submitted.push(r),r}async*events(e,t){yield{type:"progress",fraction:0.5,preview:{data:CI(`${e.model} ${e.prompt} 0`,e.aspectRatio),mime:"image/bmp"}};let r=[];if(this.gate)r.push(this.gate);if(this.delayMs>0)r.push(Bun.sleep(this.delayMs));await Promise.race([Promise.all(r),new Promise((s,o)=>{if(t.signal.aborted)o(t.signal.reason);t.signal.addEventListener("abort",()=>o(t.signal.reason))})]);let n=this.failures.shift();if(n){yield n;return}if(this.failWith){yield{type:"failed",error:this.failWith};return}if(this.outputUrl){yield{type:"completed",outputs:[{url:this.outputUrl}]};return}yield{type:"completed",outputs:Array.from({length:e.count},(s,o)=>({data:CI(`${e.model} ${e.prompt} ${o}`,e.aspectRatio),mime:"image/bmp"}))}}async cancel(e){this.canceled.push(e)}}var zI;var OI=b(()=>{zI={name:"@hatchlight/desktop",version:"0.4.1",private:!0,type:"module",scripts:{"prepare-bundle":"bun run --cwd ../web build && bun scripts/sidecar.ts",dev:"tauri dev",build:"tauri build",icons:"tauri icon icon.svg",typecheck:"tsc -p ."},devDependencies:{"@tauri-apps/cli":"2.12.5"}}});var MI;var NI=b(()=>{OI();MI=zI.version});var Pt=b(()=>{jT();qT();Xw();BE();KE();Ar();t1();i1();Ud();mb();T1();Rb();Gc();jd();Vd();Dd();hI();Zb();vI();Tb();zb();rb();kI();TI();RI();Gm();Fc();Br();NI()});var LI=b(()=>{Xu()});var DI=b(()=>{LI()});function YI(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function eA(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var uv="2025-11-25",jI="2025-03-26",Zi,qs="io.modelcontextprotocol/related-task",ip="2.0",zt,UI,BI,Nue,kB,TB,dv,Mr,rl,qI=(e)=>rl.safeParse(e).success,Ht,Zr,Hr,Gt,ap,FI,os=(e)=>FI.safeParse(e).success,VI,ZI=(e)=>VI.safeParse(e).success,pv,is=(e)=>pv.safeParse(e).success,ne,fv,Hi=(e)=>fv.safeParse(e).success,nl,Lue,cp,PB,lp,EB,sl,Vi,HI,IB,AB,RB,CB,OB,zB,up,mv=(e)=>up.safeParse(e).success,MB,NB,hv,dp,LB,DB,pp,jB,ol,il,UB,al,Gi,BB,cl,fp,mp,hp,Due,gp,yp,wp,GI,KI,WI,gv,JI,ll,Ki,QI,qB,bp,FB,vp,VB,yv,ZB,_p,HB,GB,KB,WB,JB,QB,XB,YB,eq,tq,xp,rq,nq,Sp,wv,bv,vv,sq,oq,iq,_v,aq,cq,lq,uq,dq,XI,$p,pq,kp,jue,fq,Wi,mq,Uue,ul,hq,xv,gq,yq,wq,bq,vq,_q,xq,op,Sq,$q,kq,dl,Sv,Tq,Pq,Eq,Iq,Aq,Rq,Cq,Oq,zq,Mq,Nq,Lq,Dq,jq,Uq,Bq,qq,Fq,Ji,Vq,Zq,Hq,Tp,Gq,Kq,Wq,$v,Jq,Bue,que,Fue,Vue,Zue,Hue,te,tA;var Bo=b(()=>{DI();Zi=[uv,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],zt=ST((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),UI=Xe([E(),xe().int()]),BI=E(),Nue=sr({ttl:xe().optional(),pollInterval:xe().optional()}),kB=Z({ttl:xe().optional()}),TB=Z({taskId:E()}),dv=sr({progressToken:UI.optional(),[qs]:TB.optional()}),Mr=Z({_meta:dv.optional()}),rl=Mr.extend({task:kB.optional()}),Ht=Z({method:E(),params:Mr.loose().optional()}),Zr=Z({_meta:dv.optional()}),Hr=Z({method:E(),params:Zr.loose().optional()}),Gt=sr({_meta:dv.optional()}),ap=Xe([E(),xe().int()]),FI=Z({jsonrpc:oe(ip),id:ap,...Ht.shape}).strict(),VI=Z({jsonrpc:oe(ip),...Hr.shape}).strict(),pv=Z({jsonrpc:oe(ip),id:ap,result:Gt}).strict();(function(e){e[e.ConnectionClosed=-32000]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ne||(ne={}));fv=Z({jsonrpc:oe(ip),id:ap.optional(),error:Z({code:xe().int(),message:E(),data:Qe().optional()})}).strict(),nl=Xe([FI,VI,pv,fv]),Lue=Xe([pv,fv]),cp=Gt.strict(),PB=Zr.extend({requestId:ap.optional(),reason:E().optional()}),lp=Hr.extend({method:oe("notifications/cancelled"),params:PB}),EB=Z({src:E(),mimeType:E().optional(),sizes:$e(E()).optional(),theme:or(["light","dark"]).optional()}),sl=Z({icons:$e(EB).optional()}),Vi=Z({name:E(),title:E().optional()}),HI=Vi.extend({...Vi.shape,...sl.shape,version:E(),websiteUrl:E().optional(),description:E().optional()}),IB=Wu(Z({applyDefaults:St().optional()}),Ke(E(),Qe())),AB=Dy((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},Wu(Z({form:IB.optional(),url:zt.optional()}),Ke(E(),Qe()).optional())),RB=sr({list:zt.optional(),cancel:zt.optional(),requests:sr({sampling:sr({createMessage:zt.optional()}).optional(),elicitation:sr({create:zt.optional()}).optional()}).optional()}),CB=sr({list:zt.optional(),cancel:zt.optional(),requests:sr({tools:sr({call:zt.optional()}).optional()}).optional()}),OB=Z({experimental:Ke(E(),zt).optional(),sampling:Z({context:zt.optional(),tools:zt.optional()}).optional(),elicitation:AB.optional(),roots:Z({listChanged:St().optional()}).optional(),tasks:RB.optional(),extensions:Ke(E(),zt).optional()}),zB=Mr.extend({protocolVersion:E(),capabilities:OB,clientInfo:HI}),up=Ht.extend({method:oe("initialize"),params:zB}),MB=Z({experimental:Ke(E(),zt).optional(),logging:zt.optional(),completions:zt.optional(),prompts:Z({listChanged:St().optional()}).optional(),resources:Z({subscribe:St().optional(),listChanged:St().optional()}).optional(),tools:Z({listChanged:St().optional()}).optional(),tasks:CB.optional(),extensions:Ke(E(),zt).optional()}),NB=Gt.extend({protocolVersion:E(),capabilities:MB,serverInfo:HI,instructions:E().optional()}),hv=Hr.extend({method:oe("notifications/initialized"),params:Zr.optional()}),dp=Ht.extend({method:oe("ping"),params:Mr.optional()}),LB=Z({progress:xe(),total:et(xe()),message:et(E())}),DB=Z({...Zr.shape,...LB.shape,progressToken:UI}),pp=Hr.extend({method:oe("notifications/progress"),params:DB}),jB=Mr.extend({cursor:BI.optional()}),ol=Ht.extend({params:jB.optional()}),il=Gt.extend({nextCursor:BI.optional()}),UB=or(["working","input_required","completed","failed","cancelled"]),al=Z({taskId:E(),status:UB,ttl:Xe([xe(),hT()]),createdAt:E(),lastUpdatedAt:E(),pollInterval:et(xe()),statusMessage:et(E())}),Gi=Gt.extend({task:al}),BB=Zr.merge(al),cl=Hr.extend({method:oe("notifications/tasks/status"),params:BB}),fp=Ht.extend({method:oe("tasks/get"),params:Mr.extend({taskId:E()})}),mp=Gt.merge(al),hp=Ht.extend({method:oe("tasks/result"),params:Mr.extend({taskId:E()})}),Due=Gt.loose(),gp=ol.extend({method:oe("tasks/list")}),yp=il.extend({tasks:$e(al)}),wp=Ht.extend({method:oe("tasks/cancel"),params:Mr.extend({taskId:E()})}),GI=Gt.merge(al),KI=Z({uri:E(),mimeType:et(E()),_meta:Ke(E(),Qe()).optional()}),WI=KI.extend({text:E()}),gv=E().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),JI=KI.extend({blob:gv}),ll=or(["user","assistant"]),Ki=Z({audience:$e(ll).optional(),priority:xe().min(0).max(1).optional(),lastModified:$j({offset:!0}).optional()}),QI=Z({...Vi.shape,...sl.shape,uri:E(),description:et(E()),mimeType:et(E()),size:et(xe()),annotations:Ki.optional(),_meta:et(sr({}))}),qB=Z({...Vi.shape,...sl.shape,uriTemplate:E(),description:et(E()),mimeType:et(E()),annotations:Ki.optional(),_meta:et(sr({}))}),bp=ol.extend({method:oe("resources/list")}),FB=il.extend({resources:$e(QI)}),vp=ol.extend({method:oe("resources/templates/list")}),VB=il.extend({resourceTemplates:$e(qB)}),yv=Mr.extend({uri:E()}),ZB=yv,_p=Ht.extend({method:oe("resources/read"),params:ZB}),HB=Gt.extend({contents:$e(Xe([WI,JI]))}),GB=Hr.extend({method:oe("notifications/resources/list_changed"),params:Zr.optional()}),KB=yv,WB=Ht.extend({method:oe("resources/subscribe"),params:KB}),JB=yv,QB=Ht.extend({method:oe("resources/unsubscribe"),params:JB}),XB=Zr.extend({uri:E()}),YB=Hr.extend({method:oe("notifications/resources/updated"),params:XB}),eq=Z({name:E(),description:et(E()),required:et(St())}),tq=Z({...Vi.shape,...sl.shape,description:et(E()),arguments:et($e(eq)),_meta:et(sr({}))}),xp=ol.extend({method:oe("prompts/list")}),rq=il.extend({prompts:$e(tq)}),nq=Mr.extend({name:E(),arguments:Ke(E(),E()).optional()}),Sp=Ht.extend({method:oe("prompts/get"),params:nq}),wv=Z({type:oe("text"),text:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),bv=Z({type:oe("image"),data:gv,mimeType:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),vv=Z({type:oe("audio"),data:gv,mimeType:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),sq=Z({type:oe("tool_use"),name:E(),id:E(),input:Ke(E(),Qe()),_meta:Ke(E(),Qe()).optional()}),oq=Z({type:oe("resource"),resource:Xe([WI,JI]),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),iq=QI.extend({type:oe("resource_link")}),_v=Xe([wv,bv,vv,iq,oq]),aq=Z({role:ll,content:_v}),cq=Gt.extend({description:E().optional(),messages:$e(aq)}),lq=Hr.extend({method:oe("notifications/prompts/list_changed"),params:Zr.optional()}),uq=Z({title:E().optional(),readOnlyHint:St().optional(),destructiveHint:St().optional(),idempotentHint:St().optional(),openWorldHint:St().optional()}),dq=Z({taskSupport:or(["required","optional","forbidden"]).optional()}),XI=Z({...Vi.shape,...sl.shape,description:E().optional(),inputSchema:Z({type:oe("object"),properties:Ke(E(),zt).optional(),required:$e(E()).optional()}).catchall(Qe()),outputSchema:Z({type:oe("object"),properties:Ke(E(),zt).optional(),required:$e(E()).optional()}).catchall(Qe()).optional(),annotations:uq.optional(),execution:dq.optional(),_meta:Ke(E(),Qe()).optional()}),$p=ol.extend({method:oe("tools/list")}),pq=il.extend({tools:$e(XI)}),kp=Gt.extend({content:$e(_v).default([]),structuredContent:Ke(E(),Qe()).optional(),isError:St().optional()}),jue=kp.or(Gt.extend({toolResult:Qe()})),fq=rl.extend({name:E(),arguments:Ke(E(),Qe()).optional()}),Wi=Ht.extend({method:oe("tools/call"),params:fq}),mq=Hr.extend({method:oe("notifications/tools/list_changed"),params:Zr.optional()}),Uue=Z({autoRefresh:St().default(!0),debounceMs:xe().int().nonnegative().default(300)}),ul=or(["debug","info","notice","warning","error","critical","alert","emergency"]),hq=Mr.extend({level:ul}),xv=Ht.extend({method:oe("logging/setLevel"),params:hq}),gq=Zr.extend({level:ul,logger:E().optional(),data:Qe()}),yq=Hr.extend({method:oe("notifications/message"),params:gq}),wq=Z({name:E().optional()}),bq=Z({hints:$e(wq).optional(),costPriority:xe().min(0).max(1).optional(),speedPriority:xe().min(0).max(1).optional(),intelligencePriority:xe().min(0).max(1).optional()}),vq=Z({mode:or(["auto","required","none"]).optional()}),_q=Z({type:oe("tool_result"),toolUseId:E().describe("The unique identifier for the corresponding tool call."),content:$e(_v).default([]),structuredContent:Z({}).loose().optional(),isError:St().optional(),_meta:Ke(E(),Qe()).optional()}),xq=Ly("type",[wv,bv,vv]),op=Ly("type",[wv,bv,vv,sq,_q]),Sq=Z({role:ll,content:Xe([op,$e(op)]),_meta:Ke(E(),Qe()).optional()}),$q=rl.extend({messages:$e(Sq),modelPreferences:bq.optional(),systemPrompt:E().optional(),includeContext:or(["none","thisServer","allServers"]).optional(),temperature:xe().optional(),maxTokens:xe().int(),stopSequences:$e(E()).optional(),metadata:zt.optional(),tools:$e(XI).optional(),toolChoice:vq.optional()}),kq=Ht.extend({method:oe("sampling/createMessage"),params:$q}),dl=Gt.extend({model:E(),stopReason:et(or(["endTurn","stopSequence","maxTokens"]).or(E())),role:ll,content:xq}),Sv=Gt.extend({model:E(),stopReason:et(or(["endTurn","stopSequence","maxTokens","toolUse"]).or(E())),role:ll,content:Xe([op,$e(op)])}),Tq=Z({type:oe("boolean"),title:E().optional(),description:E().optional(),default:St().optional()}),Pq=Z({type:oe("string"),title:E().optional(),description:E().optional(),minLength:xe().optional(),maxLength:xe().optional(),format:or(["email","uri","date","date-time"]).optional(),default:E().optional()}),Eq=Z({type:or(["number","integer"]),title:E().optional(),description:E().optional(),minimum:xe().optional(),maximum:xe().optional(),default:xe().optional()}),Iq=Z({type:oe("string"),title:E().optional(),description:E().optional(),enum:$e(E()),default:E().optional()}),Aq=Z({type:oe("string"),title:E().optional(),description:E().optional(),oneOf:$e(Z({const:E(),title:E()})),default:E().optional()}),Rq=Z({type:oe("string"),title:E().optional(),description:E().optional(),enum:$e(E()),enumNames:$e(E()).optional(),default:E().optional()}),Cq=Xe([Iq,Aq]),Oq=Z({type:oe("array"),title:E().optional(),description:E().optional(),minItems:xe().optional(),maxItems:xe().optional(),items:Z({type:oe("string"),enum:$e(E())}),default:$e(E()).optional()}),zq=Z({type:oe("array"),title:E().optional(),description:E().optional(),minItems:xe().optional(),maxItems:xe().optional(),items:Z({anyOf:$e(Z({const:E(),title:E()}))}),default:$e(E()).optional()}),Mq=Xe([Oq,zq]),Nq=Xe([Rq,Cq,Mq]),Lq=Xe([Nq,Tq,Pq,Eq]),Dq=rl.extend({mode:oe("form").optional(),message:E(),requestedSchema:Z({type:oe("object"),properties:Ke(E(),Lq),required:$e(E()).optional()})}),jq=rl.extend({mode:oe("url"),message:E(),elicitationId:E(),url:E().url()}),Uq=Xe([Dq,jq]),Bq=Ht.extend({method:oe("elicitation/create"),params:Uq}),qq=Zr.extend({elicitationId:E()}),Fq=Hr.extend({method:oe("notifications/elicitation/complete"),params:qq}),Ji=Gt.extend({action:or(["accept","decline","cancel"]),content:Dy((e)=>e===null?void 0:e,Ke(E(),Xe([E(),xe(),St(),$e(E())])).optional())}),Vq=Z({type:oe("ref/resource"),uri:E()}),Zq=Z({type:oe("ref/prompt"),name:E()}),Hq=Mr.extend({ref:Xe([Zq,Vq]),argument:Z({name:E(),value:E()}),context:Z({arguments:Ke(E(),E()).optional()}).optional()}),Tp=Ht.extend({method:oe("completion/complete"),params:Hq});Gq=Gt.extend({completion:sr({values:$e(E()).max(100),total:et(xe().int()),hasMore:et(St())})}),Kq=Z({uri:E().startsWith("file://"),name:E().optional(),_meta:Ke(E(),Qe()).optional()}),Wq=Ht.extend({method:oe("roots/list"),params:Mr.optional()}),$v=Gt.extend({roots:$e(Kq)}),Jq=Hr.extend({method:oe("notifications/roots/list_changed"),params:Zr.optional()}),Bue=Xe([dp,up,Tp,xv,Sp,xp,bp,vp,_p,WB,QB,Wi,$p,fp,hp,gp,wp]),que=Xe([lp,pp,hv,Jq,cl]),Fue=Xe([cp,dl,Sv,Ji,$v,mp,yp,Gi]),Vue=Xe([dp,kq,Bq,Wq,fp,hp,gp,wp]),Zue=Xe([lp,pp,yq,YB,GB,mq,lq,cl,Fq]),Hue=Xe([cp,NB,Gq,cq,rq,FB,VB,HB,kp,pq,mp,yp,Gi]);te=class te extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`);this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===ne.UrlElicitationRequired&&r){let n=r;if(n.elicitations)return new tA(n.elicitations,t)}return new te(e,t,r)}};tA=class tA extends te{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(ne.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});class kv{constructor(e){this._maxBufferSize=e?.maxBufferSize??Qq}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
82
|
+
`)),await Bun.write(Ot(s,"samples.txt"),sB(t.trigger,t.pictures.map((l)=>l.caption)));let i=this.options.gpu.acquire(Q5,n),a=await i.next();while(!a.done)a=await i.next();let c=a.value;try{await this.options.letGo().catch(()=>{});let l=await this.named(await this.options.baseModel().catch(()=>r),e.id,s);try{try{return await this.runTraining(e,t,l.file,s,n)}catch(u){if(n.aborted||!oB(u,e))throw u;return await Xt(Ot(s,"out"),{recursive:!0,force:!0}),e.stage="loading",this.changed(!0),await this.runTraining(e,t,l.file,s,n)}}finally{if(l.made)await Xt(l.file,{force:!0}).catch(()=>{})}}finally{c.release()}}finally{await Xt(s,{recursive:!0,force:!0}).catch(()=>{})}}async named(e,t,r){if(e.file.toLowerCase().endsWith(".safetensors"))return{file:e.file,made:!1};let n=Ot(e.scratch,`train-${t}.safetensors`);try{return await gI(e.scratch,{recursive:!0}),await B5(e.file,n),{file:n,made:!0}}catch{let s=Ot(r,"base.safetensors");return await U5(e.file,s),{file:s,made:!1}}}async collectSamples(e,t,r=!1){try{await this.moveSamples(e,t,r)}catch{}}async moveSamples(e,t,r){let n=Ot(t,"sample"),s=await ev(n).catch(()=>[]);for(let o of s){let i=Number(o.match(/^lora_(\d{6})_/)?.[1]);if(!i||e.samples.includes(i))continue;if(!r&&i>=e.step)continue;let a=this.path("samples",e.id,`${i}.png`);if(await gI(V5(a),{recursive:!0}),await tv(Ot(n,o),a).then(()=>!0,()=>!1))e.samples=[...e.samples,i].sort((c,l)=>c-l)}}async runTraining(e,t,r,n,s){e.stage="loading",this.changed(!0);let o=Ot(n,"out"),i=nB(t.steps),a=this.options.run([this.python,"sdxl_train_network.py","--pretrained_model_name_or_path",r,"--dataset_config",Ot(n,"dataset.toml"),"--output_dir",o,"--output_name","lora","--save_model_as","safetensors","--metadata_title",t.name,"--network_module","networks.lora","--network_dim","16","--network_alpha","8","--network_train_unet_only","--learning_rate","1e-4","--optimizer_type","AdamW8bit","--lr_scheduler","constant","--max_train_steps",String(t.steps),"--mixed_precision","bf16","--full_bf16","--lowram","--save_precision","fp16","--no_half_vae","--cache_latents","--cache_text_encoder_outputs","--gradient_checkpointing","--sdpa","--seed","42","--max_data_loader_n_workers","0","--save_every_n_steps",String(i),"--sample_every_n_steps",String(i),"--sample_prompts",Ot(n,"samples.txt"),"--sample_sampler","euler_a"],{cwd:this.scripts,env:this.uvEnv}),c=!1,l=!1,u=()=>a.kill();s.addEventListener("abort",u,{once:!0}),this.finishing=()=>{l=!0,a.kill()};let d=!0,p=!1,f=setInterval(async()=>{if(p)return;p=!0;try{await m()}finally{p=!1}},this.options.memoryCheckMs),m=async()=>{let v=await this.options.freeMemory().catch(()=>null);if(!d)return;if(e.freeMemoryBytes=v,v!=null&&v<X5&&!c)c=!0,a.kill();if(await this.collectSamples(e,o),d)this.changed()},h=[];try{for await(let C of a.output){if(C.trim())h.push(C.trim());if(h.length>30)h.shift();let k=pB(C);if(k){e.stage=k.step>=k.steps?"saving":"training",e.step=k.step,e.secondsLeft=k.secondsLeft;let y=Math.floor((k.step-1)/i)*i;if(y>(e.savedStep??0)&&await rv(Ot(o,bI(y))).catch(()=>null))e.savedStep=y;this.changed();continue}let P=fB(C);if(P&&e.stage!=="training")e.stage=P,this.changed()}let v=await a.exited;s.throwIfAborted(),d=!1,await this.collectSamples(e,o,!0);let _=v===0&&!c&&await rv(Ot(o,"lora.safetensors")).catch(()=>null)!=null;if(l&&!_&&e.savedStep!=null){e.stage="saving",this.changed(!0);let C=await this.options.loras.add(Bun.file(Ot(o,bI(e.savedStep))),`${t.name}.safetensors`);return e.keptStep=e.savedStep,C.id}if(c)throw new le("Training stopped before the computer ran out of memory","trainingOutOfMemory");if(v!==0){let C=h.filter((k)=>/error|exception|out of memory/i.test(k)).at(-1)??h.at(-1)??`it stopped with code ${v}`;throw new le(`Training failed: ${C}`,"trainingFailed",{reason:C})}}finally{d=!1,clearInterval(f),s.removeEventListener("abort",u),this.finishing=null,a.kill()}e.stage="saving",this.changed(!0);let g=Ot(o,"lora.safetensors");if(!await rv(g).catch(()=>null))throw new le("Training made no LoRA","trainingFailed",{reason:"no file was written"});return(await this.options.loras.add(Bun.file(g),`${t.name}.safetensors`)).id}}var yI="sd-scripts-cb70b96+torch-2.14.1-cu130+py3.11",Z5,H5,G5="3.11",K5,W5="https://download.pytorch.org/whl/cu130",J5=6442450944,Q5,X5=1610612736,Y5=5000,wI=1000,jo=3,Uo=200,qi=100,Fi=4000,eB=768,tB=20,rB=42,bI=(e)=>`lora-step${String(e).padStart(8,"0")}.safetensors`,iB=(e,t)=>{let r=Bun.spawn(e,{cwd:t.cwd,env:{...process.env,...t.env},stdin:"ignore",stdout:"pipe",stderr:"pipe"});async function*n(){let s=[],o={wake:null},i=2;for(let a of[r.stdout,r.stderr])(async()=>{let c="";try{for await(let l of a.pipeThrough(new TextDecoderStream)){let u=(c+l).split(/[\r\n]/);c=u.pop()??"",s.push(...u),o.wake?.()}}catch{}if(c)s.push(c);i--,o.wake?.()})();while(i>0||s.length>0){let a=s.shift();if(a!=null){yield a;continue}await new Promise((c)=>{o.wake=c}),o.wake=null}}return{output:n(),exited:r.exited,kill:()=>{if(r.exitCode!=null||r.signalCode!=null)return;if(process.platform==="win32")Bun.spawn(["taskkill","/T","/F","/PID",String(r.pid)],{stdout:"ignore",stderr:"ignore"});else r.kill()}}},cB,rp="0123456789",mB=(e)=>JSON.stringify(e);var vI=b(()=>{Ar();Kb();Z5={url:"https://github.com/kohya-ss/sd-scripts/archive/cb70b96858477e716a2096292ab8aab433277f38.zip",sha256:"13587ab358c5ecb878a991a391ca924cb37ff1d427805b1476f41bbf23fcc493",size:6689584},H5={linux:{url:"https://github.com/astral-sh/uv/releases/download/0.9.30/uv-x86_64-unknown-linux-gnu.tar.gz",sha256:"8b3762374972daa7a74bbc6896cc73229ca69a07403dd9f9ea3805a51ffd7582",size:22237571},win32:{url:"https://github.com/astral-sh/uv/releases/download/0.9.30/uv-x86_64-pc-windows-msvc.zip",sha256:"875981be7908295937dee09532bb66d576986d4f223259e171b0c767c885897a",size:21763186}},K5=["torch==2.14.1+cu130","torchvision==0.29.1+cu130"],Q5=Number.MAX_SAFE_INTEGER;cB=/^[\p{L}\p{N}_-]{2,40}$/u});class sv{adapters=new Map;models=new Map;register(e){if(this.adapters.has(e.id))throw Error(`Provider already registered: ${e.id}`);this.adapters.set(e.id,e);for(let t of e.listModels())this.models.set(t.id,t);return this}refresh(e){let t=this.adapters.get(e);if(!t)return;for(let[r,n]of this.models)if(n.providerId===e)this.models.delete(r);for(let r of t.listModels())this.models.set(r.id,r)}adapter(e){return this.adapters.get(e)}listAdapters(){return[...this.adapters.values()]}model(e){return this.models.get(e)}listModels(){return[...this.models.values()]}}import{readFile as hB,rename as gB,rm as yB,writeFile as wB}from"fs/promises";import{basename as bB,join as _I}from"path";async function xI(e,t){for(let r of[np(e),iv(e)]){let n=`${r}.${process.pid}.tmp`;await wB(n,JSON.stringify(t)),await gB(n,r)}}async function SI(e){for(let t of[np(e),iv(e)])if((await ov(t,()=>!0))?.pid===process.pid)await yB(t,{force:!0})}async function $I(e,t=vB){return await ov(np(e),t)??await ov(iv(e),t)}async function ov(e,t){try{let r=JSON.parse(await hB(e,"utf8"));if(typeof r.pid!=="number"||typeof r.url!=="string"||!/^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+$/.test(r.url))return null;return t(r.pid)?{pid:r.pid,url:r.url}:null}catch{return null}}var np=(e)=>_I(e,"hatchlight.server.json"),iv=(e)=>_I(e,Vc(bB(np(e)))),vB=(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}};var kI=()=>{};function xB(e,t){let r=e.capabilities;if(t.referenceAssetIds.length>r.maxReferenceImages)throw r.maxReferenceImages===0?new O(`${e.name} does not accept reference images`,"noReferences",{model:e.name}):new O(`${e.name} accepts at most ${r.maxReferenceImages} reference images`,"tooManyReferences",{model:e.name,count:r.maxReferenceImages});if(r.upscale!=null&&t.referenceAssetIds.length===0)throw new O(`${e.name} needs a picture to work on`,"needsPicture",{model:e.name});if(t.maskAssetId!=null){if(t.referenceAssetIds.length!==1)throw new O("A mask needs exactly one reference image to redraw","maskWithoutReference");if(r.mask==null)throw new O(`${e.name} cannot redraw only part of a picture`,"noMask",{model:e.name})}let n=r.durations??[],s=t.durationSeconds??n[0];return{...t,count:Math.min(t.count,r.maxCount),durationSeconds:s==null||n.length===0?void 0:n.reduce((o,i)=>Math.abs(i-s)<Math.abs(o-s)?i:o),aspectRatio:t.aspectRatio&&r.aspectRatios.includes(t.aspectRatio)&&!(r.strength!=null&&t.referenceAssetIds.length>0)?t.aspectRatio:void 0,seed:r.seed?t.seed:void 0,strength:r.strength!=null&&t.referenceAssetIds.length>0?t.strength??(t.maskAssetId!=null?r.mask:void 0)??r.strength:void 0,loras:r.loraBase&&t.loras?.length?t.loras:void 0}}class av{deps;constructor(e){this.deps=e}listModels(){return this.deps.registry.listModels()}async listProviders(e){let t=await this.deps.keys.list(e),r=await this.deps.keys.sources?.(e)??null;return this.deps.registry.listAdapters().map((n)=>({id:n.id,name:n.name,requiresKey:n.requiresKey,hasKey:t.includes(n.id)||Boolean(n.keyEnv&&process.env[n.keyEnv]),...r&&{keys:{personal:r.personal.includes(n.id),server:r.server.includes(n.id)||Boolean(n.keyEnv&&process.env[n.keyEnv])}}}))}async setProviderKey(e,t,r){if(this.requireProvider(t),!r.trim())throw new O("The key is empty","emptyKey");await this.deps.keys.set(e,t,r.trim())}async deleteProviderKey(e,t){this.requireProvider(t),await this.deps.keys.delete(e,t)}requireProvider(e){if(!this.deps.registry.adapter(e))throw new Ee(`Unknown provider: ${e}`,"unknownProvider",{provider:e})}listSessions(e){return this.deps.repo.listSessions(e)}async getSession(e,t){let r=await this.deps.repo.getSession(e,t);if(!r)throw new Ee("Session not found","sessionNotFound");return{...r,turns:await this.deps.repo.listTurns(e,t)}}async startSession(e,t){let r=Date.now(),n={id:Ft("ses"),userId:e.userId,title:t.slice(0,80),createdAt:r,updatedAt:r};return await this.deps.repo.createSession(n),n}async deleteSession(e,t){let r=await this.getSession(e,t);for(let n of r.turns.flatMap((s)=>s.jobs))await this.deps.engine.cancel(n.id);await this.deps.repo.deleteSession(e,t)}assertRoom(e){let t=this.deps.storageRefusal?.(e.userId);if(t)throw t}async createTurn(e,t){this.assertRoom(e);let{sessionId:r,modelIds:n,...s}=t,o=RT.safeParse(s);if(!o.success)throw new O(o.error.issues[0]?.message??"Invalid input");let i=o.data;if(n.length===0)throw new O("Choose at least one model","noModel");let a=[...new Set(n)].map((h)=>{let g=this.deps.registry.model(h);if(!g)throw new O(`Unknown model: ${h}`,"unknownModel",{model:h});return g}),c=[...i.referenceAssetIds,...i.maskAssetId!=null?[i.maskAssetId]:[]],l=await this.deps.repo.getAssets(e,c);if(l.length!==new Set(c).size)throw new O("A reference image was not found","referenceNotFound");if(l.some((h)=>!h.mime.startsWith("image/")))throw new O("Only images can be used as references","referenceNotImage");let u=a.map((h)=>xB(h,i)),d=Date.now(),p;if(r){let h=await this.deps.repo.getSession(e,r);if(!h)throw new Ee("Session not found","sessionNotFound");p={...h,updatedAt:d}}else p={id:Ft("ses"),userId:e.userId,title:i.prompt.slice(0,80),createdAt:d,updatedAt:d},await this.deps.repo.createSession(p);let f={id:Ft("trn"),sessionId:p.id,userId:e.userId,prompt:i.prompt,referenceAssetIds:i.referenceAssetIds,createdAt:d},m=a.map((h,g)=>({id:Ft("job"),turnId:f.id,position:g,userId:e.userId,providerId:h.providerId,modelId:h.id,params:u[g],status:"queued",handle:null,error:null,errorCode:null,errorParams:null,costUsd:null,createdAt:d,startedAt:null,finishedAt:null,tokenId:e.tokenId??null}));await this.deps.repo.createTurn(f,m);for(let h of m)this.deps.engine.enqueue(h);return{session:p,turn:{...f,jobs:m.map((h)=>({...h,assets:[]}))}}}async cancelJob(e,t){let r=await this.deps.repo.findJob(t);if(!r||r.userId!==e.userId)throw new Ee("Job not found","jobNotFound");await this.deps.engine.cancel(t)}async retryJob(e,t){this.assertRoom(e);let r=await this.deps.repo.findJob(t);if(!r||r.userId!==e.userId)throw new Ee("Job not found","jobNotFound");await this.deps.engine.retry(r,e.tokenId??null)}jobPreview(e,t){let r=this.deps.engine.preview(e.userId,t);if(!r)throw new Ee("No preview","jobNotFound");return r}async deleteAsset(e,t){let[r]=await this.deps.repo.getAssets(e,[t]);if(!r)throw new Ee("Asset not found","assetNotFound");let{sharing:n}=await this.deps.repo.deleteAsset(e,t);if(n===0)await this.deps.assets.remove(e,r.hash)}async uploadAsset(e,t){this.assertRoom(e);let r=Yn(t);if(!r||!_B.includes(r))throw new O("Only PNG, JPEG and WebP images can be uploaded","uploadType");let n=await this.deps.assets.put(e,t),s={id:Ft("ast"),userId:e.userId,kind:"upload",jobId:null,hash:n.hash,mime:r,size:n.size,prompt:null,modelId:null,params:null,createdAt:Date.now()};return await this.deps.repo.createAsset(s),s}async getAssetFile(e,t){let[r]=await this.deps.repo.getAssets(e,[t]),n=r&&await this.deps.assets.get(e,r.hash);if(!r||!n)throw new Ee("Asset not found","assetNotFound");return{asset:r,blob:n}}listGallery(e,t){return this.deps.repo.listGallery(e,t)}}var _B;var TI=b(()=>{Ar();Br();_B=["image/png","image/jpeg","image/webp"]});import{mkdir as PI,rename as EI,writeFile as II}from"fs/promises";import{dirname as AI}from"path";class lv{path;pending=Promise.resolve();constructor(e){this.path=e}async read(){let e=Bun.file(this.path);if(!await e.exists())return{};return await e.json().catch(()=>({}))}async get(e){let t=(await this.read())[e.userId]??{};return{translateWith:xc(t.translateWith)?t.translateWith:cv.translateWith,improveWith:Rs(t.improveWith)?t.improveWith:cv.improveWith,assistantWith:Rs(t.assistantWith)?t.assistantWith:cv.assistantWith}}set(e,t){let r=this.pending.then(async()=>{let n=await this.read();n[e.userId]={...n[e.userId],...t},await PI(AI(this.path),{recursive:!0});let s=`${this.path}.${crypto.randomUUID()}.tmp`;return await II(s,JSON.stringify(n,null,2)),await EI(s,this.path),this.get(e)});return this.pending=r.catch(()=>{}),r}moveUser(e,t){let r=this.pending.then(async()=>{let n=await this.read();if(!Object.hasOwn(n,e)||Object.hasOwn(n,t))return;n[t]=n[e],delete n[e],await PI(AI(this.path),{recursive:!0});let s=`${this.path}.${crypto.randomUUID()}.tmp`;await II(s,JSON.stringify(n,null,2)),await EI(s,this.path)});return this.pending=r.catch(()=>{}),r}}var cv;var RI=b(()=>{Br();cv={translateWith:"local",improveWith:"auto",assistantWith:"auto"}});function CI(e,t="1:1"){let[r=1,n=1]=t.split(":").map(Number),s=96/Math.max(r,n),o=Math.max(1,Math.round(r*s)),i=Math.max(1,Math.round(n*s)),a=new Bun.CryptoHasher("sha256").update(e).digest(),c=Math.ceil(o*3/4)*4,l=new Uint8Array(54+c*i),u=new DataView(l.buffer);l.set([66,77]),u.setUint32(2,l.length,!0),u.setUint32(10,54,!0),u.setUint32(14,40,!0),u.setInt32(18,o,!0),u.setInt32(22,i,!0),u.setUint16(26,1,!0),u.setUint16(28,24,!0);for(let d=0;d<i;d++){let p=d/Math.max(1,i-1);for(let f=0;f<o;f++)for(let m=0;m<3;m++){let h=a[m]??0,g=a[m+3]??0;l[54+d*c+f*3+m]=h+(g-h)*p}}return l}class sp{id;modelNames;name;requiresKey=!1;resumable=!1;maxConcurrency;gate=null;failWith=null;failures=[];delayMs=0;outputUrl=null;submitted=[];canceled=[];constructor(e="fake",t=["alpha","beta"]){this.id=e;this.modelNames=t;this.name=`Fake (${e})`}listModels(){return this.modelNames.map((e)=>({id:`${this.id}/${e}`,providerId:this.id,providerModelId:e,name:`Fake ${e}`,media:"image",operations:["generate","edit"],capabilities:{aspectRatios:["1:1","16:9"],seed:!0,maxCount:2,maxReferenceImages:e==="alpha"?2:0,...e==="alpha"&&{mask:0.85},...e==="beta"&&{englishPrompts:!0}},pricing:{usdPerOutput:0.01}}))}keysUsed=[];async submit(e,t){this.keysUsed.push(t?.apiKey);let r={model:e.model.id,prompt:e.params.prompt,count:e.params.count,aspectRatio:e.params.aspectRatio,...e.mask&&{mask:e.mask.data}};return this.submitted.push(r),r}async*events(e,t){yield{type:"progress",fraction:0.5,preview:{data:CI(`${e.model} ${e.prompt} 0`,e.aspectRatio),mime:"image/bmp"}};let r=[];if(this.gate)r.push(this.gate);if(this.delayMs>0)r.push(Bun.sleep(this.delayMs));await Promise.race([Promise.all(r),new Promise((s,o)=>{if(t.signal.aborted)o(t.signal.reason);t.signal.addEventListener("abort",()=>o(t.signal.reason))})]);let n=this.failures.shift();if(n){yield n;return}if(this.failWith){yield{type:"failed",error:this.failWith};return}if(this.outputUrl){yield{type:"completed",outputs:[{url:this.outputUrl}]};return}yield{type:"completed",outputs:Array.from({length:e.count},(s,o)=>({data:CI(`${e.model} ${e.prompt} ${o}`,e.aspectRatio),mime:"image/bmp"}))}}async cancel(e){this.canceled.push(e)}}var zI;var OI=b(()=>{zI={name:"@hatchlight/desktop",version:"0.4.2",private:!0,type:"module",scripts:{"prepare-bundle":"bun run --cwd ../web build && bun scripts/sidecar.ts",dev:"tauri dev",build:"tauri build",icons:"tauri icon icon.svg",typecheck:"tsc -p ."},devDependencies:{"@tauri-apps/cli":"2.12.5"}}});var MI;var NI=b(()=>{OI();MI=zI.version});var Pt=b(()=>{jT();qT();Xw();BE();KE();Ar();t1();i1();Ud();mb();T1();Rb();Gc();jd();Vd();Dd();hI();Zb();vI();Tb();zb();rb();kI();TI();RI();Gm();Fc();Br();NI()});var LI=b(()=>{Xu()});var DI=b(()=>{LI()});function YI(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function eA(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var uv="2025-11-25",jI="2025-03-26",Zi,qs="io.modelcontextprotocol/related-task",ip="2.0",zt,UI,BI,Nue,kB,TB,dv,Mr,rl,qI=(e)=>rl.safeParse(e).success,Ht,Zr,Hr,Gt,ap,FI,os=(e)=>FI.safeParse(e).success,VI,ZI=(e)=>VI.safeParse(e).success,pv,is=(e)=>pv.safeParse(e).success,ne,fv,Hi=(e)=>fv.safeParse(e).success,nl,Lue,cp,PB,lp,EB,sl,Vi,HI,IB,AB,RB,CB,OB,zB,up,mv=(e)=>up.safeParse(e).success,MB,NB,hv,dp,LB,DB,pp,jB,ol,il,UB,al,Gi,BB,cl,fp,mp,hp,Due,gp,yp,wp,GI,KI,WI,gv,JI,ll,Ki,QI,qB,bp,FB,vp,VB,yv,ZB,_p,HB,GB,KB,WB,JB,QB,XB,YB,eq,tq,xp,rq,nq,Sp,wv,bv,vv,sq,oq,iq,_v,aq,cq,lq,uq,dq,XI,$p,pq,kp,jue,fq,Wi,mq,Uue,ul,hq,xv,gq,yq,wq,bq,vq,_q,xq,op,Sq,$q,kq,dl,Sv,Tq,Pq,Eq,Iq,Aq,Rq,Cq,Oq,zq,Mq,Nq,Lq,Dq,jq,Uq,Bq,qq,Fq,Ji,Vq,Zq,Hq,Tp,Gq,Kq,Wq,$v,Jq,Bue,que,Fue,Vue,Zue,Hue,te,tA;var Bo=b(()=>{DI();Zi=[uv,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],zt=ST((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),UI=Xe([E(),xe().int()]),BI=E(),Nue=sr({ttl:xe().optional(),pollInterval:xe().optional()}),kB=Z({ttl:xe().optional()}),TB=Z({taskId:E()}),dv=sr({progressToken:UI.optional(),[qs]:TB.optional()}),Mr=Z({_meta:dv.optional()}),rl=Mr.extend({task:kB.optional()}),Ht=Z({method:E(),params:Mr.loose().optional()}),Zr=Z({_meta:dv.optional()}),Hr=Z({method:E(),params:Zr.loose().optional()}),Gt=sr({_meta:dv.optional()}),ap=Xe([E(),xe().int()]),FI=Z({jsonrpc:oe(ip),id:ap,...Ht.shape}).strict(),VI=Z({jsonrpc:oe(ip),...Hr.shape}).strict(),pv=Z({jsonrpc:oe(ip),id:ap,result:Gt}).strict();(function(e){e[e.ConnectionClosed=-32000]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ne||(ne={}));fv=Z({jsonrpc:oe(ip),id:ap.optional(),error:Z({code:xe().int(),message:E(),data:Qe().optional()})}).strict(),nl=Xe([FI,VI,pv,fv]),Lue=Xe([pv,fv]),cp=Gt.strict(),PB=Zr.extend({requestId:ap.optional(),reason:E().optional()}),lp=Hr.extend({method:oe("notifications/cancelled"),params:PB}),EB=Z({src:E(),mimeType:E().optional(),sizes:$e(E()).optional(),theme:or(["light","dark"]).optional()}),sl=Z({icons:$e(EB).optional()}),Vi=Z({name:E(),title:E().optional()}),HI=Vi.extend({...Vi.shape,...sl.shape,version:E(),websiteUrl:E().optional(),description:E().optional()}),IB=Wu(Z({applyDefaults:St().optional()}),Ke(E(),Qe())),AB=Dy((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},Wu(Z({form:IB.optional(),url:zt.optional()}),Ke(E(),Qe()).optional())),RB=sr({list:zt.optional(),cancel:zt.optional(),requests:sr({sampling:sr({createMessage:zt.optional()}).optional(),elicitation:sr({create:zt.optional()}).optional()}).optional()}),CB=sr({list:zt.optional(),cancel:zt.optional(),requests:sr({tools:sr({call:zt.optional()}).optional()}).optional()}),OB=Z({experimental:Ke(E(),zt).optional(),sampling:Z({context:zt.optional(),tools:zt.optional()}).optional(),elicitation:AB.optional(),roots:Z({listChanged:St().optional()}).optional(),tasks:RB.optional(),extensions:Ke(E(),zt).optional()}),zB=Mr.extend({protocolVersion:E(),capabilities:OB,clientInfo:HI}),up=Ht.extend({method:oe("initialize"),params:zB}),MB=Z({experimental:Ke(E(),zt).optional(),logging:zt.optional(),completions:zt.optional(),prompts:Z({listChanged:St().optional()}).optional(),resources:Z({subscribe:St().optional(),listChanged:St().optional()}).optional(),tools:Z({listChanged:St().optional()}).optional(),tasks:CB.optional(),extensions:Ke(E(),zt).optional()}),NB=Gt.extend({protocolVersion:E(),capabilities:MB,serverInfo:HI,instructions:E().optional()}),hv=Hr.extend({method:oe("notifications/initialized"),params:Zr.optional()}),dp=Ht.extend({method:oe("ping"),params:Mr.optional()}),LB=Z({progress:xe(),total:et(xe()),message:et(E())}),DB=Z({...Zr.shape,...LB.shape,progressToken:UI}),pp=Hr.extend({method:oe("notifications/progress"),params:DB}),jB=Mr.extend({cursor:BI.optional()}),ol=Ht.extend({params:jB.optional()}),il=Gt.extend({nextCursor:BI.optional()}),UB=or(["working","input_required","completed","failed","cancelled"]),al=Z({taskId:E(),status:UB,ttl:Xe([xe(),hT()]),createdAt:E(),lastUpdatedAt:E(),pollInterval:et(xe()),statusMessage:et(E())}),Gi=Gt.extend({task:al}),BB=Zr.merge(al),cl=Hr.extend({method:oe("notifications/tasks/status"),params:BB}),fp=Ht.extend({method:oe("tasks/get"),params:Mr.extend({taskId:E()})}),mp=Gt.merge(al),hp=Ht.extend({method:oe("tasks/result"),params:Mr.extend({taskId:E()})}),Due=Gt.loose(),gp=ol.extend({method:oe("tasks/list")}),yp=il.extend({tasks:$e(al)}),wp=Ht.extend({method:oe("tasks/cancel"),params:Mr.extend({taskId:E()})}),GI=Gt.merge(al),KI=Z({uri:E(),mimeType:et(E()),_meta:Ke(E(),Qe()).optional()}),WI=KI.extend({text:E()}),gv=E().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),JI=KI.extend({blob:gv}),ll=or(["user","assistant"]),Ki=Z({audience:$e(ll).optional(),priority:xe().min(0).max(1).optional(),lastModified:$j({offset:!0}).optional()}),QI=Z({...Vi.shape,...sl.shape,uri:E(),description:et(E()),mimeType:et(E()),size:et(xe()),annotations:Ki.optional(),_meta:et(sr({}))}),qB=Z({...Vi.shape,...sl.shape,uriTemplate:E(),description:et(E()),mimeType:et(E()),annotations:Ki.optional(),_meta:et(sr({}))}),bp=ol.extend({method:oe("resources/list")}),FB=il.extend({resources:$e(QI)}),vp=ol.extend({method:oe("resources/templates/list")}),VB=il.extend({resourceTemplates:$e(qB)}),yv=Mr.extend({uri:E()}),ZB=yv,_p=Ht.extend({method:oe("resources/read"),params:ZB}),HB=Gt.extend({contents:$e(Xe([WI,JI]))}),GB=Hr.extend({method:oe("notifications/resources/list_changed"),params:Zr.optional()}),KB=yv,WB=Ht.extend({method:oe("resources/subscribe"),params:KB}),JB=yv,QB=Ht.extend({method:oe("resources/unsubscribe"),params:JB}),XB=Zr.extend({uri:E()}),YB=Hr.extend({method:oe("notifications/resources/updated"),params:XB}),eq=Z({name:E(),description:et(E()),required:et(St())}),tq=Z({...Vi.shape,...sl.shape,description:et(E()),arguments:et($e(eq)),_meta:et(sr({}))}),xp=ol.extend({method:oe("prompts/list")}),rq=il.extend({prompts:$e(tq)}),nq=Mr.extend({name:E(),arguments:Ke(E(),E()).optional()}),Sp=Ht.extend({method:oe("prompts/get"),params:nq}),wv=Z({type:oe("text"),text:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),bv=Z({type:oe("image"),data:gv,mimeType:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),vv=Z({type:oe("audio"),data:gv,mimeType:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),sq=Z({type:oe("tool_use"),name:E(),id:E(),input:Ke(E(),Qe()),_meta:Ke(E(),Qe()).optional()}),oq=Z({type:oe("resource"),resource:Xe([WI,JI]),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),iq=QI.extend({type:oe("resource_link")}),_v=Xe([wv,bv,vv,iq,oq]),aq=Z({role:ll,content:_v}),cq=Gt.extend({description:E().optional(),messages:$e(aq)}),lq=Hr.extend({method:oe("notifications/prompts/list_changed"),params:Zr.optional()}),uq=Z({title:E().optional(),readOnlyHint:St().optional(),destructiveHint:St().optional(),idempotentHint:St().optional(),openWorldHint:St().optional()}),dq=Z({taskSupport:or(["required","optional","forbidden"]).optional()}),XI=Z({...Vi.shape,...sl.shape,description:E().optional(),inputSchema:Z({type:oe("object"),properties:Ke(E(),zt).optional(),required:$e(E()).optional()}).catchall(Qe()),outputSchema:Z({type:oe("object"),properties:Ke(E(),zt).optional(),required:$e(E()).optional()}).catchall(Qe()).optional(),annotations:uq.optional(),execution:dq.optional(),_meta:Ke(E(),Qe()).optional()}),$p=ol.extend({method:oe("tools/list")}),pq=il.extend({tools:$e(XI)}),kp=Gt.extend({content:$e(_v).default([]),structuredContent:Ke(E(),Qe()).optional(),isError:St().optional()}),jue=kp.or(Gt.extend({toolResult:Qe()})),fq=rl.extend({name:E(),arguments:Ke(E(),Qe()).optional()}),Wi=Ht.extend({method:oe("tools/call"),params:fq}),mq=Hr.extend({method:oe("notifications/tools/list_changed"),params:Zr.optional()}),Uue=Z({autoRefresh:St().default(!0),debounceMs:xe().int().nonnegative().default(300)}),ul=or(["debug","info","notice","warning","error","critical","alert","emergency"]),hq=Mr.extend({level:ul}),xv=Ht.extend({method:oe("logging/setLevel"),params:hq}),gq=Zr.extend({level:ul,logger:E().optional(),data:Qe()}),yq=Hr.extend({method:oe("notifications/message"),params:gq}),wq=Z({name:E().optional()}),bq=Z({hints:$e(wq).optional(),costPriority:xe().min(0).max(1).optional(),speedPriority:xe().min(0).max(1).optional(),intelligencePriority:xe().min(0).max(1).optional()}),vq=Z({mode:or(["auto","required","none"]).optional()}),_q=Z({type:oe("tool_result"),toolUseId:E().describe("The unique identifier for the corresponding tool call."),content:$e(_v).default([]),structuredContent:Z({}).loose().optional(),isError:St().optional(),_meta:Ke(E(),Qe()).optional()}),xq=Ly("type",[wv,bv,vv]),op=Ly("type",[wv,bv,vv,sq,_q]),Sq=Z({role:ll,content:Xe([op,$e(op)]),_meta:Ke(E(),Qe()).optional()}),$q=rl.extend({messages:$e(Sq),modelPreferences:bq.optional(),systemPrompt:E().optional(),includeContext:or(["none","thisServer","allServers"]).optional(),temperature:xe().optional(),maxTokens:xe().int(),stopSequences:$e(E()).optional(),metadata:zt.optional(),tools:$e(XI).optional(),toolChoice:vq.optional()}),kq=Ht.extend({method:oe("sampling/createMessage"),params:$q}),dl=Gt.extend({model:E(),stopReason:et(or(["endTurn","stopSequence","maxTokens"]).or(E())),role:ll,content:xq}),Sv=Gt.extend({model:E(),stopReason:et(or(["endTurn","stopSequence","maxTokens","toolUse"]).or(E())),role:ll,content:Xe([op,$e(op)])}),Tq=Z({type:oe("boolean"),title:E().optional(),description:E().optional(),default:St().optional()}),Pq=Z({type:oe("string"),title:E().optional(),description:E().optional(),minLength:xe().optional(),maxLength:xe().optional(),format:or(["email","uri","date","date-time"]).optional(),default:E().optional()}),Eq=Z({type:or(["number","integer"]),title:E().optional(),description:E().optional(),minimum:xe().optional(),maximum:xe().optional(),default:xe().optional()}),Iq=Z({type:oe("string"),title:E().optional(),description:E().optional(),enum:$e(E()),default:E().optional()}),Aq=Z({type:oe("string"),title:E().optional(),description:E().optional(),oneOf:$e(Z({const:E(),title:E()})),default:E().optional()}),Rq=Z({type:oe("string"),title:E().optional(),description:E().optional(),enum:$e(E()),enumNames:$e(E()).optional(),default:E().optional()}),Cq=Xe([Iq,Aq]),Oq=Z({type:oe("array"),title:E().optional(),description:E().optional(),minItems:xe().optional(),maxItems:xe().optional(),items:Z({type:oe("string"),enum:$e(E())}),default:$e(E()).optional()}),zq=Z({type:oe("array"),title:E().optional(),description:E().optional(),minItems:xe().optional(),maxItems:xe().optional(),items:Z({anyOf:$e(Z({const:E(),title:E()}))}),default:$e(E()).optional()}),Mq=Xe([Oq,zq]),Nq=Xe([Rq,Cq,Mq]),Lq=Xe([Nq,Tq,Pq,Eq]),Dq=rl.extend({mode:oe("form").optional(),message:E(),requestedSchema:Z({type:oe("object"),properties:Ke(E(),Lq),required:$e(E()).optional()})}),jq=rl.extend({mode:oe("url"),message:E(),elicitationId:E(),url:E().url()}),Uq=Xe([Dq,jq]),Bq=Ht.extend({method:oe("elicitation/create"),params:Uq}),qq=Zr.extend({elicitationId:E()}),Fq=Hr.extend({method:oe("notifications/elicitation/complete"),params:qq}),Ji=Gt.extend({action:or(["accept","decline","cancel"]),content:Dy((e)=>e===null?void 0:e,Ke(E(),Xe([E(),xe(),St(),$e(E())])).optional())}),Vq=Z({type:oe("ref/resource"),uri:E()}),Zq=Z({type:oe("ref/prompt"),name:E()}),Hq=Mr.extend({ref:Xe([Zq,Vq]),argument:Z({name:E(),value:E()}),context:Z({arguments:Ke(E(),E()).optional()}).optional()}),Tp=Ht.extend({method:oe("completion/complete"),params:Hq});Gq=Gt.extend({completion:sr({values:$e(E()).max(100),total:et(xe().int()),hasMore:et(St())})}),Kq=Z({uri:E().startsWith("file://"),name:E().optional(),_meta:Ke(E(),Qe()).optional()}),Wq=Ht.extend({method:oe("roots/list"),params:Mr.optional()}),$v=Gt.extend({roots:$e(Kq)}),Jq=Hr.extend({method:oe("notifications/roots/list_changed"),params:Zr.optional()}),Bue=Xe([dp,up,Tp,xv,Sp,xp,bp,vp,_p,WB,QB,Wi,$p,fp,hp,gp,wp]),que=Xe([lp,pp,hv,Jq,cl]),Fue=Xe([cp,dl,Sv,Ji,$v,mp,yp,Gi]),Vue=Xe([dp,kq,Bq,Wq,fp,hp,gp,wp]),Zue=Xe([lp,pp,yq,YB,GB,mq,lq,cl,Fq]),Hue=Xe([cp,NB,Gq,cq,rq,FB,VB,HB,kp,pq,mp,yp,Gi]);te=class te extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`);this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===ne.UrlElicitationRequired&&r){let n=r;if(n.elicitations)return new tA(n.elicitations,t)}return new te(e,t,r)}};tA=class tA extends te{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(ne.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});class kv{constructor(e){this._maxBufferSize=e?.maxBufferSize??Qq}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
83
83
|
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Xq(t)}clear(){this._buffer=void 0}}function Xq(e){return nl.parse(JSON.parse(e))}function rA(e){return JSON.stringify(e)+`
|
|
84
84
|
`}var Qq=10485760;var nA=b(()=>{Bo()});import sA from"process";class Tv{constructor(e=sA.stdin,t=sA.stdout,r){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=(n)=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=(n)=>{this.onerror?.(n)},this._readBuffer=new kv({maxBufferSize:r?.maxBufferSize})}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=rA(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var oA=b(()=>{nA()});class cs{baseUrl;fetch;constructor(e,t=(r,n)=>globalThis.fetch(r,n)){this.baseUrl=e;this.fetch=t}async request(e,t){let r=await this.fetch(`${this.baseUrl}${e}`,t);if(!r.ok){let s=await r.json().catch(()=>null);throw new as(s?.error??`Hatchlight answered ${r.status}`,r.status,s?.code??null)}let n=await r.text();return n?JSON.parse(n):void 0}post=(e)=>this.request(e,{method:"POST"});models=()=>this.request("/api/models");providers=()=>this.request("/api/providers");session=(e)=>this.request(`/api/sessions/${encodeURIComponent(e)}`);createTurn=(e)=>this.request("/api/turns",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)});upload=(e)=>this.request("/api/assets",{method:"POST",body:e});gallery=(e)=>{let t=new URLSearchParams;if(e.query)t.set("query",e.query);return t.set("limit",String(e.limit??20)),this.request(`/api/gallery?${t}`)};async asset(e){let t=await this.fetch(`${this.baseUrl}/api/assets/${encodeURIComponent(e)}`);if(!t.ok)throw new as(`No picture or video with id ${e}`,t.status,"assetNotFound");return{data:new Uint8Array(await t.arrayBuffer()),mime:t.headers.get("content-type")??"application/octet-stream"}}cancelJob=(e)=>this.post(`/api/jobs/${encodeURIComponent(e)}/cancel`);retryJob=(e)=>this.post(`/api/jobs/${encodeURIComponent(e)}/retry`);async*events(e){let t=await this.fetch(`${this.baseUrl}/api/events`,{signal:e});if(!t.ok||!t.body)return;let r="";try{for await(let n of t.body.pipeThrough(new TextDecoderStream)){r=(r+n).replaceAll(`\r
|
|
85
85
|
`,`
|
package/package.json
CHANGED