flintmaker 0.2.6 → 0.5.0

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.
@@ -0,0 +1,32 @@
1
+ import{a as pt,c as ft,d as _,e as gt}from"./chunk-EBWJOG3A.js";import{a as kt,b as Ct}from"./chunk-PRTNH66F.js";import{b as F,c as U,d as W,e as bt,g as j,i as q}from"./chunk-OMZ5ETOR.js";import{b as yt,c as y,d as xt,f as $t,g as St,h as Mt,i as Tt,j as At,k as Pt,l as x,n as It,o as Et,q as w,r as g,s as Ot,t as H,u as J,v as E,w as Rt,x as Dt,y as Nt,z as Lt}from"./chunk-MKJ6MOQH.js";import{b as o}from"./chunk-MQW5CMHG.js";import{a as I}from"./chunk-J5AZ2T4P.js";import{c as M,d as V,e as X,f as tt,g as et,h as st,i as it,k as T,l as K,m as A,n as rt,o as v,p as nt,q as ot,r as at,s as ht,t as lt,u as ct,v as P,w as ut,x as dt,y as mt}from"./chunk-IZWMUOBI.js";import{b as Y,e as wt,g as vt,h as B}from"./chunk-NQ54OCJ5.js";import"./chunk-4IWYTYSQ.js";import{a as p}from"./chunk-X6RLFXRA.js";import"./chunk-FEVGFFVL.js";import"./chunk-6DHFEWGX.js";import{existsSync as oe}from"node:fs";import{homedir as ae}from"node:os";import{join as he}from"node:path";var $=class{text="";cursor=0;set(t,e=t.length){this.text=t,this.cursor=Math.max(0,Math.min(e,t.length))}clear(){this.set("")}insert(t){this.text=this.text.slice(0,this.cursor)+t+this.text.slice(this.cursor),this.cursor+=t.length}prevIndex(t){if(t<=0)return 0;let e=this.text.charCodeAt(t-1);return e>=56320&&e<=57343&&t>=2?t-2:t-1}nextIndex(t){if(t>=this.text.length)return this.text.length;let e=this.text.codePointAt(t);return t+(e>65535?2:1)}backspace(){if(this.cursor===0)return;let t=this.prevIndex(this.cursor);this.text=this.text.slice(0,t)+this.text.slice(this.cursor),this.cursor=t}del(){this.cursor>=this.text.length||(this.text=this.text.slice(0,this.cursor)+this.text.slice(this.nextIndex(this.cursor)))}left(){this.cursor=this.prevIndex(this.cursor)}right(){this.cursor=this.nextIndex(this.cursor)}lineStart(t=this.cursor){return this.text.lastIndexOf(`
2
+ `,t-1)+1}lineEnd(t=this.cursor){let e=this.text.indexOf(`
3
+ `,t);return e<0?this.text.length:e}home(){this.cursor=this.lineStart()}end(){this.cursor=this.lineEnd()}wordLeft(){let t=this.cursor;for(;t>0&&/\s/.test(this.text[t-1]);)t--;for(;t>0&&!/\s/.test(this.text[t-1]);)t--;this.cursor=t}wordRight(){let t=this.cursor;for(;t<this.text.length&&/\s/.test(this.text[t]);)t++;for(;t<this.text.length&&!/\s/.test(this.text[t]);)t++;this.cursor=t}deleteWordBack(){let t=this.cursor;this.wordLeft(),this.text=this.text.slice(0,this.cursor)+this.text.slice(t)}killToEnd(){let t=this.lineEnd();this.text=this.text.slice(0,this.cursor)+this.text.slice(t===this.cursor?t+1:t)}killToStart(){let t=this.lineStart();this.text=this.text.slice(0,t)+this.text.slice(this.cursor),this.cursor=t}get onFirstLine(){return this.text.lastIndexOf(`
4
+ `,this.cursor-1)<0}get onLastLine(){return this.text.indexOf(`
5
+ `,this.cursor)<0}vertical(t){if(t<0?this.onFirstLine:this.onLastLine)return!1;let e=y(this.text.slice(this.lineStart(),this.cursor)),s=t<0?this.lineStart(this.lineStart()-1):this.lineEnd()+1,i=s,r=0,n=this.lineEnd(s);for(;i<n;){let h=yt(this.text.codePointAt(i));if(r+h>e)break;r+=h,i=this.nextIndex(i)}return this.cursor=i,!0}currentToken(){let t=this.cursor;for(;t>0&&!/\s/.test(this.text[t-1]);)t--;return{start:t,text:this.text.slice(t,this.cursor)}}replaceToken(t,e){this.text=this.text.slice(0,t)+e+this.text.slice(this.cursor),this.cursor=t+e.length}layout(t){let e=[],s=0,i=0,r=0;for(let n of this.text.split(`
6
+ `)){let h=$t(n,Math.max(1,t)),a=r;h.forEach((l,u)=>{let c=u===h.length-1,m=a+l.length;this.cursor>=a&&(this.cursor<m||c&&this.cursor===m)&&(s=e.length,i=y(l.slice(0,this.cursor-a))),e.push(l),a=m}),r+=n.length+1}return i>=t&&(s+=1,i=0,s>=e.length&&e.push("")),{rows:e,row:s,col:i}}};import{readFileSync as Kt,statSync as Qt}from"node:fs";import{dirname as Gt,join as Ft,resolve as Ut}from"node:path";function _t(d){let t=Ut(d);for(let e=0;e<40;e++){let s=Ft(t,".git");try{let r=s;if(Qt(s).isFile()){let a=/^gitdir:\s*(.+)$/m.exec(Kt(s,"utf8"));if(!a)return null;r=Ut(t,a[1].trim())}let n=Kt(Ft(r,"HEAD"),"utf8").trim(),h=/^ref: refs\/heads\/(.+)$/.exec(n);return h?h[1]:n.slice(0,7)}catch{}let i=Gt(t);if(i===t)return null;t=i}return null}import{appendFileSync as Zt,mkdirSync as Vt,readFileSync as Xt,writeFileSync as te}from"node:fs";import{homedir as ee}from"node:os";import{dirname as se,join as ie}from"node:path";var re=()=>process.env.FLINT_HISTORY||ie(ee(),".flintmaker","history"),z=500,O=class{constructor(t=re()){this.file=t;if(t)try{this.entries=Xt(t,"utf8").split(`
7
+ `).filter(Boolean).map(e=>{try{let s=JSON.parse(e);return typeof s=="string"?s:null}catch{return null}}).filter(e=>e!==null).slice(-z)}catch{}}file;entries=[];index=-1;draft="";add(t){this.reset();let e=t.trim();if(!(!e||this.entries.at(-1)===e)&&(this.entries.push(e),!!this.file))try{Vt(se(this.file),{recursive:!0,mode:448}),this.entries.length>z*1.5?(this.entries=this.entries.slice(-z),te(this.file,this.entries.map(s=>JSON.stringify(s)).join(`
8
+ `)+`
9
+ `,{mode:384})):Zt(this.file,JSON.stringify(e)+`
10
+ `,{mode:384})}catch{}}prev(t){return this.entries.length===0||(this.index===-1&&(this.draft=t,this.index=this.entries.length),this.index===0)?null:(this.index--,this.entries[this.index])}next(){return this.index===-1?null:(this.index++,this.index>=this.entries.length?(this.index=-1,this.draft):this.entries[this.index])}reset(){this.index=-1,this.draft=""}};var ne={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"},Q={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",Z:"tab"},Wt={13:"enter",9:"tab",27:"escape",127:"backspace",8:"backspace",32:"space"};function G(d){let t=(d??1)-1;return{shift:!!(t&1),meta:!!(t&2)||!!(t&8),ctrl:!!(t&4)}}function jt(d,t){let e=G(t);if(Wt[d])return{name:Wt[d],...e,...d===32&&!e.ctrl&&!e.meta?{text:" "}:{}};let s=String.fromCodePoint(d);return e.ctrl||e.meta?{name:s.toLowerCase(),...e}:{name:s,text:e.shift?s.toUpperCase():s,...e}}var qt="\x1B[200~",Yt="\x1B[201~",R=class{constructor(t={}){this.opts=t}opts;buf="";paste=null;pasteUntil=0;feed(t){if(this.opts.pasteHeuristic&&this.paste===null&&this.buf===""&&t!==""&&!t.includes("\x1B")){let s=(this.opts.now??Date.now)();if(/[\r\n][^\r\n]/.test(t)||s<this.pasteUntil)return this.pasteUntil=s+40,[{name:"paste",text:t.replace(/\r\n?/g,`
11
+ `)}]}this.buf+=t;let e=[];for(;;){if(this.paste!==null){let r=this.buf.indexOf(Yt);if(r<0)return this.paste+=this.buf,this.buf="",e;this.paste+=this.buf.slice(0,r),this.buf=this.buf.slice(r+Yt.length),e.push({name:"paste",text:this.paste.replace(/\r\n?/g,`
12
+ `)}),this.paste=null;continue}if(this.buf==="")return e;if(this.buf.startsWith(qt)){this.buf=this.buf.slice(qt.length),this.paste="";continue}if(this.buf==="\x1B")return e;let[s,i]=this.one(this.buf);if(i===0)return e;this.buf=this.buf.slice(i),s&&e.push(s)}}flush(){if(this.paste!==null||this.buf==="")return[];let t=this.buf;return this.buf="",t.startsWith("\x1B")?[{name:"escape"},...this.feed(t.slice(1))]:this.feed(t)}get pending(){return this.buf!==""&&this.paste===null}one(t){let e=t[0];if(e==="\x1B"){let n=t[1];if(n==="["){let l=/^\x1b\[([0-9;:?<>]*)([ -/]*)([@-~])/.exec(t);if(!l)return t.length<16?[null,0]:[{name:"escape"},1];let[u,c,,m]=l,f=c.split(";").map(b=>Number(b.split(":")[0])||void 0);return m==="u"?[jt(f[0]??0,f[1]),u.length]:m==="~"?f[0]===27&&f[2]!==void 0?[jt(f[2],f[1]),u.length]:[{name:ne[String(f[0])]??"unknown",...G(f[1])},u.length]:m==="Z"?[{name:"tab",shift:!0},u.length]:Q[m]?[{name:Q[m],...G(f[1])},u.length]:m==="I"||m==="O"?[{name:m==="I"?"focusin":"focusout"},u.length]:[{name:"unknown"},u.length]}if(n==="O"&&t.length>=3)return[{name:Q[t[2]]??{P:"f1",Q:"f2",R:"f3",S:"f4"}[t[2]]??"unknown"},3];if(n==="\x1B")return[{name:"escape"},1];if(n==="\r"||n===`
13
+ `)return[{name:"enter",meta:!0},2];if(n==="\x7F"||n==="\b")return[{name:"backspace",meta:!0},2];let h=t.codePointAt(1),a=h>65535?3:2;return[{name:String.fromCodePoint(h).toLowerCase(),meta:!0},a]}if(e==="\r")return[{name:"enter"},t[1]===`
14
+ `?2:1];if(e===`
15
+ `)return[{name:"enter",ctrl:!0},1];if(e===" ")return[{name:"tab"},1];if(e==="\x7F"||e==="\b")return[{name:"backspace"},1];if(e==="\0")return[{name:"space",ctrl:!0},1];let s=e.charCodeAt(0);if(s<32)return[{name:String.fromCharCode(s+96),ctrl:!0},1];let i=t.codePointAt(0),r=String.fromCodePoint(i);return[{name:r,text:r},r.length]}},D=d=>d.name==="enter"&&!!(d.shift||d.meta||d.ctrl);var Bt="\x1B[?2026h",Ht="\x1B[?2026l",S=class{constructor(t){this.out=t;this.lastCols=this.cols}out;lines=[];cursor=null;cursorRow=0;widths=[];lastCols;get cols(){return Math.max(20,this.out.columns||80)}get rows(){return Math.max(10,this.out.rows||24)}eraseSeq(){let t=this.cursorRow;if(this.cols<this.lastCols){t=0;for(let e=0;e<this.cursorRow;e++)t+=Math.max(1,Math.ceil(this.widths[e]/this.cols))}return(t>0?`\x1B[${t}A`:"")+"\r\x1B[J"}drawSeq(){let t=this.cols,e=this.lines.map(r=>y(r)>t-1?xt(r,t-1):r);if(this.widths=e.map(y),this.lastCols=t,e.length===0)return this.cursorRow=0,"";let s=e.join(`\x1B[K\r
16
+ `)+"\x1B[K",i=e.length-1;if(this.cursor){let r=Math.min(this.cursor.row,i);i-r>0&&(s+=`\x1B[${i-r}A`),s+="\r"+(this.cursor.col>0?`\x1B[${this.cursor.col}C`:"")+"\x1B[?25h",this.cursorRow=r}else s+="\x1B[?25l",this.cursorRow=i;return s}render(t,e=null){if(e?.row===this.cursor?.row&&e?.col===this.cursor?.col&&t.length===this.lines.length&&t.every((i,r)=>i===this.lines[r])&&this.cols===this.lastCols)return;let s=this.eraseSeq();this.lines=t,this.cursor=e,this.out.write(Bt+"\x1B[?25l"+s+this.drawSeq()+Ht)}commit(t,e){if(t.length===0)return;let s=this.eraseSeq();e&&(this.lines=e.lines,this.cursor=e.cursor);let i=t.flatMap(r=>r.split(`
17
+ `)).map(r=>r+"\x1B[K").join(`\r
18
+ `)+`\r
19
+ `;this.out.write(Bt+"\x1B[?25l"+s+i+this.drawSeq()+Ht)}clear(){let t=this.eraseSeq();this.lines=[],this.cursor=null,this.widths=[],this.cursorRow=0,this.out.write(t+"\x1B[?25h")}};var N=["ask","auto","plan"],le=new Set(["write_file","edit_file"]),ce=d=>d.deleted?"Delete":d.created?"Create":d.renamedFrom?"Move and edit":"Edit",Z=class{constructor(t){this.opts=t;this.checkpoints=new I(t.ws,t.resume?.checkpoints),this.customCommands=it(t.ws),t.ws.mcp.restore(t.resume?.mcpTools),this.history=new O(t.privacy?null:void 0),this.session=t.resume?{id:t.resume.id,created:t.resume.created,title:t.resume.title}:{id:Y(),created:new Date().toISOString(),title:""},t.resume&&(this.conversation=t.resume.messages),this.model=t.model,this.mode=t.mode??"ask",this.client=t.client,this.branch=_t(t.ws.root),this.cwdShort=Lt(t.ws.root,ae(),28),this.md=new Ct(()=>this.screen.cols-1)}opts;screen=new S(process.stdout);editor=new $;feedback=new $;history;parser=new R({pasteHeuristic:process.platform==="win32"});escTimer;mode="ask";model;client;me=null;usage=null;branch;cwdShort;checkpoints;customCommands;conversation=[];busy=null;sessionCredits=0;frame=0;spinTimer;md;assistantStarted=!1;running=null;headerShown=!1;lastStats=null;prompt=null;suggestions=null;suggestionsDismissed=!1;queue=[];pastedImages=[];hint=null;statusNote=null;updateRequested=!1;exitArmedUntil=0;allowedKinds=new Set;welcomePending=!0;renderQueued=!1;finished;closed=!1;session;run(){let t=process.stdin;t.setRawMode(!0),t.setEncoding("utf8"),t.resume(),process.stdout.write("\x1B[?2004h\x1B[>1u"),t.on("data",this.onData),process.stdout.on("resize",this.onResize),process.on("exit",this.restoreTerminal);for(let e of["SIGTERM","SIGHUP"])process.on(e,()=>this.exit());return this.render(),setTimeout(()=>{import("./highlight-2UNDOBIV.js").then(e=>kt(e.highlight)).catch(()=>{})},50),this.loadAccount(),new Promise(e=>this.finished=e)}restoreTerminal=()=>{if(!this.closed){this.closed=!0;try{process.stdout.write("\x1B[<u\x1B[?2004l\x1B[?25h"),process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}}};exit(t="Bye."){this.opts.ws.jobs.stopAll(),this.opts.ws.mcp.closeAll(),this.busy?.controller.abort(),this.stopSpinner(),this.prompt=null,this.screen.clear();let e=this.sessionCredits?o.grey(` ${K(this.sessionCredits)} credits used this session.`):"";process.stdout.write(`${o.ember("\u2726")} ${o.grey(t)}${e}\r
20
+ `),this.restoreTerminal(),j(null),q(null),process.stdin.off("data",this.onData),process.stdout.off("resize",this.onResize),process.stdin.pause(),this.finished?.()}async loadAccount(){try{this.me=await this.client.me(),this.usage=this.me.usage,this.commitWelcome()}catch(t){this.commitWelcome(),this.showError(t,!1)}}commitWelcome(){this.welcomePending&&(this.welcomePending=!1,this.commit(["",...this.welcomeLines()]),j(t=>this.commit(["",`${o.ember("\u2726")} ${o.grey(t)}`])),q(t=>{this.statusNote=t,this.schedule()}),this.opts.privacy&&this.note("Privacy mode: no history or conversation is saved on this computer; web tools are off"),this.opts.resume&&this.note(`Continuing "${p(this.opts.resume.title)}" \xB7 ${this.opts.resume.messages.length} messages \xB7 ${B(this.opts.resume.updated)}`),this.opts.pickSession&&this.resumeCommand())}welcomeLines(){return Pt({version:this.opts.version,email:this.me?.user.email,plan:this.me?.user.plan,credits:this.usage?A(this.usage):void 0,model:this.model,cwd:this.cwdShort,status:this.me?void 0:"connecting\u2026",updated:this.opts.updated},this.screen.cols)}schedule=()=>{this.renderQueued||this.closed||(this.renderQueued=!0,setTimeout(()=>{this.renderQueued=!1,this.render()},16))};onResize=()=>this.render();render(){if(this.closed)return;let{lines:t,cursor:e}=this.compose();this.screen.render(t,e)}compose(){let t=this.screen.cols,e=[],s=[],i=null;if(this.welcomePending&&e.push("",...this.welcomeLines()),this.running&&e.push("",w(this.running.name,this.running.detail,"running",t)),this.busy&&!this.prompt&&e.push("",It(this.frame,Date.now()-this.busy.start,this.busy.credits,t,this.busy.verb)),this.prompt?.kind==="menu")s.push("",...Rt(this.prompt.question,this.prompt.options,this.prompt.selected,t,this.prompt.esc));else{for(let b of this.queue)s.push(o.grey(` \u23F5 queued: ${b.text.split(`
21
+ `)[0]}`));s.push("");let l=this.prompt?.kind==="feedback"?this.feedback:this.editor,u=this.prompt?.kind==="feedback"?"\u270E ":"\u276F ",c=l.layout(Nt(t,u)),m=this.prompt?.kind==="feedback"?"Tell flint what to do differently (enter to send \xB7 esc to skip)":this.busy?"Type to queue a follow-up\u2026":this.conversation.length===0?'Describe a task, or try "explain this project" \xB7 @ to attach a file':"Reply, or describe the next task\u2026",f=Dt(c.rows,c,t,{placeholder:m,prefix:u,maxRows:Math.max(3,Math.min(10,this.screen.rows-12))});if(i={row:s.length+f.cursorRow,col:f.cursorCol},s.push(...f.lines),this.suggestions&&!this.prompt){let{items:b,selected:k}=this.suggestions,L=Math.max(0,Math.min(k-3,b.length-7));b.slice(L,L+7).forEach((C,Jt)=>{let zt=L+Jt===k?o.ember(`\u276F ${C.label}`):` ${C.label}`;s.push(` ${zt}${C.hint?o.grey(` ${C.hint}`):""}`)}),b.length>7&&s.push(o.grey(` ${b.length} matches \xB7 tab to complete`))}}s.push(this.footerLine());let r=this.screen.rows-1-e.length-s.length,n=this.previewLines(),h=r>0?n.slice(Math.max(0,n.length-r)):[],a=[...h,...e,...s];return i&&(i={row:i.row+h.length+e.length,col:i.col}),{lines:a,cursor:this.prompt?.kind==="menu"?null:i}}previewLines(){if(!this.md.started)return[];let t=this.md.preview();return t.length===0?[]:this.assistantStarted?["",...t]:["",this.marker(t[0]),...t.slice(1)]}footerLine(){let t=Date.now();return this.hint&&this.hint.until<t&&(this.hint=null),Et({model:this.model,mode:this.mode,credits:this.usage?A(this.usage):void 0,cwd:this.cwdShort,branch:this.branch,hint:this.hint?.text,note:this.statusNote??void 0},this.screen.cols)}flash(t,e=2500){this.hint={text:t,until:Date.now()+e},this.schedule(),setTimeout(this.schedule,e+20)}commit(t){this.closed||this.screen.commit(t,this.compose())}marker(t){return t.startsWith(" ")?o.gold("\u2726")+" "+t.slice(2):t}commitAssistant(t){t.length!==0&&(this.assistantStarted||(this.assistantStarted=!0,t=["",this.marker(t[0]),...t.slice(1)]),this.commit(t))}flushMarkdown(){this.commitAssistant(this.md.end()),this.assistantStarted=!1}showError(t,e=!0){if(t instanceof F&&t.reason==="update_required"&&this.opts.onUpdateRequired)return this.updateRequested?void 0:(this.updateRequested=!0,this.opts.onUpdateRequired(),this.exit(`${t.message} Updating flint\u2026`));let s=bt(t,{interactive:!0,retry:e?"Press \u2191 then enter to try again.":void 0});this.commit(["",...E(s.title,s.lines,this.screen.cols,s.tone)]),this.render()}info(t,e){this.commit(["",...E(t,e,this.screen.cols,"info")])}note(t,e=o.grey){this.commit([` ${o.grey("\u23BF")} ${e(t)}`])}startSpinner(t){let e=new AbortController;this.busy={start:Date.now(),credits:0,verb:t??x[Math.floor(Math.random()*x.length)],controller:e};let s=!t,i=0;return this.spinTimer=setInterval(()=>{this.frame++,s&&++i%40===0&&this.busy&&(this.busy.verb=x[(x.indexOf(this.busy.verb)+1)%x.length]),this.schedule()},100),e}stopSpinner(){this.spinTimer&&clearInterval(this.spinTimer),this.spinTimer=void 0,this.busy=null}onData=t=>{this.escTimer&&clearTimeout(this.escTimer);for(let e of this.parser.feed(t))this.safeKey(e);this.parser.pending&&(this.escTimer=setTimeout(()=>this.parser.flush().forEach(e=>this.safeKey(e)),30))};safeKey(t){try{this.onKey(t)}catch(e){this.showError(e,!1)}}onKey(t){if(t.name==="c"&&t.ctrl)return this.ctrlC();if(this.prompt?.kind==="menu")return this.menuKey(t,this.prompt);if(this.prompt?.kind==="feedback"){let s=this.prompt;return t.name==="escape"?s.resolve(null):t.name==="enter"&&!D(t)?s.resolve(this.feedback.text.trim()):(this.editKey(this.feedback,t),this.schedule())}if(t.name==="tab"&&t.shift)return this.cycleMode();if(t.name==="escape")return this.busy?this.interrupt():this.suggestions?(this.suggestions=null,this.suggestionsDismissed=!0,this.schedule()):void 0;if(t.name==="enter"&&!D(t))return this.enter();if(t.name==="tab")return this.complete();if((t.name==="up"||t.name==="down")&&!t.shift&&!t.meta)return this.upDown(t.name==="up"?-1:1);if(t.name==="d"&&t.ctrl&&this.editor.text==="")return this.exit();if(t.name==="l"&&t.ctrl)return process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),this.screen=new S(process.stdout),this.render();if(t.name==="paste")try{let s=lt(this.opts.ws,t.text??"");if(s?.image){if(this.pastedImages.length>=4)throw new Error("At most 4 pasted images may be attached");return this.pastedImages.push(s.image),this.note(`Pasted image attached (${this.pastedImages.length}); enter sends it with your task`),this.schedule()}if(s?.reference)return this.editor.insert(s.reference),this.schedule()}catch(s){return this.note(s.message,o.gold),this.schedule()}let e=this.editor.text;this.editKey(this.editor,t),this.editor.text!==e&&(this.history.reset(),this.suggestionsDismissed=!1),this.updateSuggestions(),this.schedule()}editKey(t,e){if(e.name==="paste")return t.insert(p(e.text??"").replace(/\t/g," "));if(D(e))return t.insert(`
22
+ `);let s=e.ctrl||e.meta;switch(e.name){case"backspace":return s?t.deleteWordBack():t.backspace();case"delete":return t.del();case"left":return s?t.wordLeft():t.left();case"right":return s?t.wordRight():t.right();case"home":return t.home();case"end":return t.end()}if(e.ctrl){switch(e.name){case"a":return t.home();case"e":return t.end();case"b":return t.left();case"f":return t.right();case"k":return t.killToEnd();case"u":return t.killToStart();case"w":return t.deleteWordBack();case"d":return t.del();case"h":return t.backspace()}return}if(e.meta)return e.name==="b"?t.wordLeft():e.name==="f"?t.wordRight():e.name==="d"?t.deleteWordBack():void 0;e.text&&t.insert(e.text)}ctrlC(){if(this.opts.ws.jobs.stopAll(),this.opts.ws.mcp.closeAll(),this.prompt?.kind==="menu")return this.prompt.resolve(null);if(this.prompt?.kind==="feedback")return this.prompt.resolve(null);if(this.busy)return this.interrupt();if(this.editor.text||this.pastedImages.length)return this.pastedImages=[],this.editor.clear(),this.suggestions=null,this.schedule();if(Date.now()<this.exitArmedUntil)return this.exit();this.exitArmedUntil=Date.now()+2e3,this.flash("Press Ctrl+C again to exit",2e3)}interrupt(){!this.busy||this.busy.controller.signal.aborted||(this.busy.controller.abort(),this.flash("Interrupting\u2026",1500))}cycleMode(){this.mode=N[(N.indexOf(this.mode)+1)%N.length],this.schedule()}upDown(t){if(this.suggestions){let s=this.suggestions.items.length;return this.suggestions.selected=(this.suggestions.selected+t+s)%s,this.schedule()}if(this.editor.vertical(t))return this.schedule();let e=t<0?this.history.prev(this.editor.text):this.history.next();e!==null&&this.editor.set(e),this.updateSuggestions(),this.schedule()}updateSuggestions(){if(this.suggestionsDismissed)return void(this.suggestions=null);let t=this.editor.text;if(/^\/[\w-]*$/.test(t)&&this.editor.cursor===t.length){let s=tt(t,[...M,...this.customCommands]).map(r=>({value:`/${r.name}`,label:`/${r.name}${r.args?" "+r.args:""}`,hint:r.description})),i=this.suggestions?.kind==="slash"?this.suggestions.selected:0;this.suggestions=s.length?{items:s,selected:Math.min(i,s.length-1),kind:"slash",start:0}:null;return}let e=this.editor.currentToken();if(e.text.startsWith("@")){let s=st(this.opts.ws.root,e.text.slice(1)).map(i=>({value:`@${i}`,label:i}));this.suggestions=s.length?{items:s,selected:0,kind:"path",start:e.start}:null;return}this.suggestions=null}complete(){if(!this.suggestions&&(this.updateSuggestions(),!this.suggestions))return;let t=this.suggestions;if(t.kind==="slash")this.editor.set(t.items[t.selected].value+" "),this.suggestions=null;else{let e=this.editor.currentToken(),s=t.items.map(n=>n.value),i=et(s),r=i.length>e.text.length?i:t.items[t.selected].value;this.editor.replaceToken(e.start,r+(r.endsWith("/")||s.length>1&&r===i?"":" ")),this.updateSuggestions()}this.schedule()}enter(){let t=this.editor;if(t.cursor===t.text.length&&t.text.endsWith("\\"))return t.backspace(),t.insert(`
23
+ `),this.schedule();if(this.suggestions?.kind==="slash"){let i=this.suggestions.items[this.suggestions.selected].value;M.some(r=>`/${r.name}`===t.text.trim())||t.set(i)}let e=t.text.trim()||(this.pastedImages.length?"Describe the attached image.":"");if(!e)return;let s=this.pastedImages.splice(0);if(this.history.add(e),t.clear(),this.suggestions=null,this.busy)return this.queue.push({text:e,images:s}),this.schedule();this.submit(e,s)}async submit(t,e=[]){try{let i=V(t);if(e.length&&i?.command)throw new Error("Send pasted images with a task or custom command");e.length?await this.turn(t,t,e):i?await this.command(i.name,i.args,!!i.command):await this.turn(t)}catch(i){this.stopSpinner(),this.showError(i,!1)}let s=this.queue.shift();s!==void 0&&!this.closed&&this.submit(s.text,s.images)}menuKey(t,e){let s=e.options.length;if(t.name==="up"||t.name==="tab"&&t.shift)e.selected=(e.selected-1+s)%s;else if(t.name==="down"||t.name==="tab")e.selected=(e.selected+1)%s;else{if(t.name==="enter")return e.resolve(e.selected);if(t.name==="escape")return e.resolve(null);if(/^[1-9]$/.test(t.name)&&Number(t.name)<=s)return e.resolve(Number(t.name)-1);if(t.name==="y")return e.resolve(0);if(t.name==="n")return e.resolve(s-1)}this.schedule()}ask(t,e,s=0,i="cancel"){return new Promise(r=>{this.prompt={kind:"menu",question:t,options:e,selected:s,esc:i,resolve:n=>{this.prompt=null,this.render(),r(n)}},this.render()})}askFeedback(){return this.feedback.clear(),new Promise(t=>{this.prompt={kind:"feedback",resolve:e=>{this.prompt=null,this.render(),t(e)}},this.render()})}echo(t){let e=t.split(`
24
+ `);this.commit(["",...e.map((s,i)=>`${i===0?o.ember("\u276F"):" "} ${o.bold(p(s))}`)])}stepper(t){return this.client.stepper(()=>this.model,()=>t.signal,(e,s)=>{this.busy&&(this.busy.credits+=e),this.sessionCredits+=e,this.usage=s})}async turn(t,e=t,s=[]){this.echo(e);let i=this.startSpinner(),r=Date.now(),n=s.length||ct(this.opts.ws,t)?await this.client.supportsImages(this.model,i.signal):!1,h=await at(this.opts.ws,t,{imageInput:n,images:s,approveRead:async c=>await this.agentUI(i).approveCommand(`Attach image ${c}`,"ask","ask")===!0,first:this.conversation.length===0,mode:this.mode});h.memory&&this.note(`Using ${T} project memory`);for(let c of h.attachments)c.error?this.note(`Could not attach ${c.path}: ${c.error}`,o.gold):c.image?this.note(`Attached ${c.path} (image)`):this.note(`Attached ${c.path} (${c.lines} line${c.lines===1?"":"s"})`);let a=[...this.conversation,{role:"user",content:h.content,...h.images?.length?{images:h.images}:{}}],l=!1;try{this.session.title||(this.session.title=e.split(`
25
+ `)[0].slice(0,120)),this.conversation=await mt(this.opts.ws,a,this.stepper(i),this.agentUI(i),{signal:i.signal,policy:this.opts.policy,plan:this.mode==="plan",privacy:this.opts.privacy,checkpoints:this.checkpoints})}catch(c){l=!0,this.flushMarkdown();let m=c.partial;m&&m.length>a.length&&(this.conversation=m),this.showError(c),c instanceof F&&c.reason==="signed_out"&&_()}this.flushMarkdown(),this.running=null,this.saveConversation();let u=this.busy?.credits??0;if(this.stopSpinner(),this.hint?.text==="Interrupting\u2026"&&(this.hint=null),i.signal.aborted)this.commit(["",` ${o.gold("\u23F9")} ${o.grey("Interrupted \xB7 tell flint what to do instead")}`]);else if(!l){let m=[`${Math.max(1,Math.round((Date.now()-r)/1e3))}s`,`${u} credit${u===1?"":"s"}`,this.usage?A(this.usage):null].filter(Boolean);this.commit(["",o.grey(` \u273B ${m.join(" \xB7 ")}`)])}this.render()}saveConversation(){this.opts.privacy||this.conversation.length===0||wt({version:1,...this.session,root:this.opts.ws.root,updated:new Date().toISOString(),model:this.model,messages:this.conversation,checkpoints:this.checkpoints.entries,mcpTools:this.opts.ws.mcp.registry})}async resumeCommand(){if(this.opts.privacy)return this.note("Privacy mode saves no conversations.",o.gold),this.render();let t=vt(this.opts.ws.root,9).filter(r=>r.id!==this.session.id||this.conversation.length===0);if(t.length===0)return this.note("No saved conversations in this folder yet."),this.render();let e=t.map(r=>({label:p(r.title||"(untitled)").slice(0,60),hint:`${B(r.updated)} \xB7 ${r.messages.length} messages`})),s=await this.ask("Continue which conversation?",e,0);if(s===null)return this.render();let i=t[s];this.saveConversation(),this.checkpoints=new I(this.opts.ws,i.checkpoints),this.opts.ws.jobs.stopAll(),this.opts.ws.mcp.closeAll(),this.opts.ws.mcp.restore(i.mcpTools),this.conversation=i.messages,this.session={id:i.id,created:i.created,title:i.title},this.commit(["",o.grey(` ${"\u2500".repeat(3)} continuing "${p(i.title)}" (${i.messages.length} messages) ${"\u2500".repeat(3)}`)]),this.render()}agentUI(t){let e=()=>this.screen.cols;return{onChild:(s,i)=>{this.flushMarkdown(),this.note(`Child ${s}: ${p(i)}`)},onMCP:(s,i)=>this.note(`MCP ${p(s)}: ${p(i)}`),onHook:(s,i,r,n)=>{this.flushMarkdown(),r===void 0?this.note(`Hook ${s}: ${p(i)}`):(this.commit(g(p(n??""),e(),3)),this.headerShown=!1)},onCompact:(s,i)=>{this.flushMarkdown(),this.note(i===void 0?"Compacting conversation\u2026":`Compacted ${s} messages to ${i}`)},onDelta:s=>{this.running&&(this.running=null),this.commitAssistant(this.md.push(p(s))),this.schedule()},onToolStart:(s,i)=>{this.flushMarkdown(),this.lastDetail=i,this.lastFeedback="",this.headerShown=!1,this.lastStats=null,this.running={name:s,detail:i},this.schedule()},onToolResult:(s,i,r="")=>{this.running=null;let n=[],h=this.lastDetail;if(!i)this.headerShown||n.push("",w(s,h,"error",e())),n.push(...g(r,e(),3,o.red));else if(s==="delegate"||s.startsWith("mcp__")||["start_background","read_job","stop_job"].includes(s))n.push("",w(s,h,"ok",e()),...g(r,e(),8));else if(s==="update_todos")n.push("",o.bold(" Tasks"),...p(r).split(`
26
+ `).map(a=>` ${a}`));else if(s==="apply_patch"){let a=r===P?"Interrupted":r.startsWith("Applied")?r.split(`
27
+ `)[0]:this.declinedText("Not applied");n.push(...g(a,e(),2))}else if(s==="git")this.headerShown||n.push("",w(s,h,"ok",e())),n.push(...g(/^The user declined/.test(r)?this.declinedText("Not run"):r,e(),5));else if(le.has(s))if(/^(Created|Updated) /.test(r)){let a=this.lastStats;n.push(...g(`${r.startsWith("Created")?"Created":"Updated"}${a?` \xB7 +${a.added} -${a.removed}`:""}`,e()))}else n.push(...g(r===P?"Interrupted":r.startsWith("Plan mode")?"Skipped (plan mode)":this.declinedText("Not applied"),e()));else if(s==="run_command")if(/^(The user declined|Plan mode is on)/.test(r))n.push(...g(r.startsWith("Plan mode")?"Skipped (plan mode)":this.declinedText("Not run"),e()));else if(r===P||r.startsWith("[interrupted by the user before"))n.push(...g("Interrupted",e()));else{let a=/\n?\[(exit code (\d+|null)|timed out after \d+s|interrupted by the user|could not run command[^\]]*)\]$/.exec(r),l=(a?r.slice(0,a.index):r).trimEnd(),u=!a||a[2]!=="0";this.headerShown||n.push("",w(s,h,u?"error":"ok",e())),l?n.push(...g(l,e(),5)):u||n.push(...g("Done (no output)",e())),u&&a&&n.push(` ${l?" ":o.grey("\u23BF")} ${o.red(a[1])}`)}else{let a=Ot(s,r);n.push("",w(s,h,"ok",e(),a.suffix)),a.detail&&n.push(...g(a.detail,e()))}this.commit(n),this.schedule()},approveChange:async(s,i)=>(this.running=null,this.headerShown=!0,this.lastStats=H(s.diff),this.lastDetail=s.path,this.commit(["",w(s.created?"write_file":"edit_file",s.path,"ok",e()),...J(s.diff,s.path,e(),s.created)]),this.mode==="plan"?{declined:"Plan mode is on, so no files may be changed. Put this change in your plan instead."}:this.opts.autoYes||i==="allow"||this.mode==="auto"&&i!=="ask"?!0:this.decide(t,`${s.created?"Create":"Make this edit to"} ${o.ember(p(s.path))}?`,"Yes, and don't ask again for edits this session","change",()=>{this.mode="auto"})),approvePatch:async(s,i)=>{this.running=null,this.headerShown=!0,this.lastDetail=i;let r=s.reduce((a,l)=>{let u=H(l.diff);return{added:a.added+u.added,removed:a.removed+u.removed}},{added:0,removed:0});this.lastStats=r,this.commit(["",w("apply_patch",`${p(i||"changes")} ${o.grey(`(${s.length} file${s.length===1?"":"s"} \xB7 +${r.added} -${r.removed})`)}`,"ok",e())]);let n=[],h=this.opts.autoYes||this.mode==="auto";for(let[a,l]of s.entries()){if(this.commit(["",...J(l.diff,l.renamedFrom?`${l.renamedFrom} \u2192 ${l.path}`:l.path,e(),l.created)]),this.mode==="plan"){n.push({declined:"Plan mode is on, so no files may be changed. Put this change in your plan instead."});continue}if(h||t.signal.aborted){n.push(!t.signal.aborted);continue}let u=s.length-a-1,c=[{label:"Yes"}];u&&c.push({label:`Yes, and the other ${u} file${u===1?"":"s"} in this patch`}),c.push({label:"No, skip this file"},{label:"No, tell flint what to do differently"});let m=await this.ask(`${ce(l)} ${o.ember(p(l.path))}? ${o.grey(`(${a+1}/${s.length})`)}`,c,0,"stop flint");if(m===null){for(t.abort();n.length<s.length;)n.push(!1);break}let f=c[m].label;if(f==="Yes")n.push(!0);else if(f.startsWith("Yes, and"))h=!0,n.push(!0);else if(f==="No, skip this file")n.push(!1);else{let b=await this.askFeedback();b&&(this.lastFeedback=b);let k=b?{declined:`The user rejected ${l.path} and said: ${JSON.stringify(b)}. Follow their instruction instead.`}:!1;for(;n.length<s.length;)n.push(n.length===a?k:!1);break}}return n},approveCommand:async(s,i,r)=>{this.running=null,this.headerShown=!0;let n=p(s),h=St(`${o.ember("\u25CF")} ${o.bold("Run")} ${n}`,e()-1," ");if(this.commit(["",...h]),this.mode==="plan")return{declined:"Plan mode is on, so no commands may run. Put this command in your plan instead."};if(this.opts.autoYes)return!0;if(r==="allow"||r!=="ask"&&i==="allow"&&this.mode==="auto")return this.note("Allowed (test/build/read-only command; auto mode)"),!0;let a=ht(s);return r!=="ask"&&a&&this.allowedKinds.has(a)?(this.note(`Allowed (${a} commands are approved for this session)`),!0):this.decide(t,"Run this command?",a?`Yes, and don't ask again for "${a}" commands this session`:null,"command",()=>a&&this.allowedKinds.add(a))}}}lastDetail="";declinedText(t){return this.lastFeedback?`${t} \xB7 you said: ${this.lastFeedback.split(`
28
+ `)[0]}`:t}lastFeedback="";async decide(t,e,s,i,r){let n=[{label:"Yes"}];s&&n.push({label:s,hint:i==="change"?"(auto-accept edits)":void 0}),n.push({label:"No, tell flint what to do differently"});let h=await this.ask(e,n,0,"stop flint");if(h===null)return t.abort(),!1;if(h===0)return!0;if(s&&h===1)return r(),!0;let a=await this.askFeedback();return a===null||a===""?!1:(this.lastFeedback=a,{declined:`The user declined this ${i} and said: ${JSON.stringify(a)}. Follow their instruction instead.`})}async command(t,e,s){if(!s&&this.customCommands.some(i=>i.name===t))return this.turn(`/${t}${e?" "+e:""}`);if(!s){let i=X(t);return this.echo(`/${t}${e?" "+e:""}`),this.note(`Unknown command /${t}.${i?` Did you mean /${i}?`:""} Type /help for the list.`,o.gold),this.render()}switch(t){case"help":return this.help();case"exit":return this.exit();case"resume":return this.resumeCommand();case"mcp":return this.commit(["",...p(this.opts.ws.mcp.status()).split(`
29
+ `).map(i=>` ${i}`)]),this.render();case"jobs":return e.startsWith("stop ")?this.note(this.opts.ws.jobs.stop(e.slice(5).trim())):this.commit(["",...p(this.opts.ws.jobs.list()).split(`
30
+ `).map(i=>` ${i}`)," /jobs stop <id> stops an owned job."]),this.render();case"clear":return this.opts.ws.jobs.stopAll(),this.opts.ws.mcp.closeAll(),this.saveConversation(),this.session={id:Y(),created:new Date().toISOString(),title:""},this.conversation=[],this.checkpoints=new I(this.opts.ws),this.commit(["",o.grey(` ${"\u2500".repeat(3)} new conversation ${"\u2500".repeat(Math.max(3,Math.min(40,this.screen.cols-26)))}`)]),this.render();case"mode":{let i=e.toLowerCase(),r=N.includes(i)?i:i==="auto-accept"?"auto":null;return r?this.mode=r:this.cycleMode(),this.note(`Mode: ${Mt[this.mode]}`),this.render()}case"model":return this.modelCommand(e);case"credits":return this.creditsCommand();case"init":return this.initCommand();case"rewind":return this.rewindCommand(e);case"compact":return this.compactCommand();case"login":return this.loginCommand();case"update":return this.opts.onUpdateNow?(this.opts.onUpdateNow(),this.exit("Checking for a newer flint\u2026")):(this.note("Run flint update in your terminal to update."),this.render());case"logout":return _(),this.exit("Signed out. Run flint login to connect again.")}}help(){let t=[...M,...this.customCommands].map(s=>`${o.ember(`/${s.name}`)}${s.args?o.grey(" "+s.args):""} ${o.grey(s.description)}`),e=[`${o.bold("enter")} send \xB7 ${o.bold("shift+enter")}, ${o.bold("ctrl+j")} or ${o.bold("\\")} new line`,`${o.bold("@path")} attach a file \xB7 ${o.bold("tab")} complete \xB7 ${o.bold("\u2191/\u2193")} history`,`${o.bold("esc")} interrupt \xB7 ${o.bold("shift+tab")} mode \xB7 ${o.bold("ctrl+c")} twice to exit`];this.commit(["",...At([o.bold("Commands"),...t,"",o.bold("Keys"),...e],Math.min(this.screen.cols-1,76),{border:o.ember})]),this.render()}async modelCommand(t){let e=t==="smart"||t==="standard"?t:null;if(!t){let s=["standard","smart"].map(r=>({label:`${v[r].label}${r===this.model?o.grey(" (current)"):""}`,hint:`${v[r].cost} \xB7 ${v[r].note}`})),i=await this.ask("Choose a model",s,this.model==="smart"?1:0);if(i===null)return;e=i===1?"smart":"standard"}if(!e)return this.note("Usage: /model standard | smart",o.gold);if(e==="smart"&&(this.me?.user.plan??"free")==="free")return this.commit(["",...E("Smart needs a paid plan",["You are on the Free plan, so flint stays on Standard.",`Upgrade: ${W}`],this.screen.cols,"warn")]),this.render();this.model=e,this.note(`Model: ${Tt[e]} \xB7 ${v[e].cost}`),this.render()}async creditsCommand(){try{this.me=await this.client.me(),this.usage=this.me.usage;let t=this.sessionCredits?[`This session: ${K(this.sessionCredits)} credits`]:[];this.info("Credits",[...rt(this.usage),...t,"",`Standard ${v.standard.cost} \xB7 Smart ${v.smart.cost}`,`More credits: ${W}`])}catch(t){this.showError(t,!1)}this.render()}async initCommand(){if(oe(he(this.opts.ws.root,T)))return this.info(`${T} already exists`,["flint reads it at the start of every conversation.","Edit it by hand, or ask flint to update it."]),this.render();await this.turn(nt,"/init")}async rewindCommand(t){if(!this.checkpoints.entries.length)return this.note("No patches to rewind in this conversation.");let e=this.checkpoints.entries,s;if(t){if(!/^\d+$/.test(t)||Number(t)<1||Number(t)>e.length)return this.note("Choose a checkpoint number from /rewind.",o.gold);s=Number(t)-1}else s=await this.ask("Rewind files and conversation to before which patch?",e.map((r,n)=>({label:`${n+1}. ${p(r.label)}`,hint:"restore this patch and every later patch"})));s===null||await this.ask(`Restore before patch ${s+1}? Shell commands and git changes cannot be undone.`,[{label:"Cancel"},{label:"Restore files and conversation"}])!==1||(this.conversation=this.checkpoints.rewind(s),this.saveConversation(),this.note("Files and conversation restored. Continue with your next instruction."),this.render())}async compactCommand(){if(this.conversation.length<3)return this.note("Nothing to compact yet."),this.render();this.echo("/compact");let t=this.startSpinner("Compacting");try{let e=this.conversation,s="";for(let r=0;r<4&&!s;r++)try{if(s=(await this.stepper(t)([...e,{role:"user",content:ot}],()=>{})).text.trim(),!s)throw new Error("The summary came back empty. Try again, or use /clear.")}catch(n){if(!(n instanceof ut))throw n;e=dt(e)}if(!s)throw new Error("This conversation is too long to summarise. Start a new one with /clear.");let i=this.conversation.length;this.conversation=[{role:"user",content:`Summary of our conversation so far (compacted to save context):
31
+
32
+ ${s}`},{role:"assistant",content:"Thanks, I have the context. What should we do next?"}],this.note(`Compacted ${i} messages into a summary`),this.saveConversation(),this.commit(g(s,this.screen.cols,6).map(r=>r.replace("\u23BF"," ")))}catch(e){t.signal.aborted||this.showError(e,!1)}this.stopSpinner(),this.render()}async loginCommand(){let t=gt(null),e=new U(t),s=this.startSpinner("Waiting for approval in your browser");try{let i=await e.deviceLogin((r,n)=>{this.info("Connect your FlintMaker account",[`Your code: ${o.bold(o.gold(r))}`,`Opening ${n}`,"Approve it in the browser \xB7 esc to cancel"]),pt(n),this.render()},s.signal);ft({token:i.token,email:i.user.email,api:e.base}),this.client=new U(t,i.token),this.client.privacy=!!this.opts.privacy,this.client.settings=this.opts.ws.settings,this.client.mcp=this.opts.ws.mcp,this.me=await this.client.me(),this.usage=this.me.usage,this.note(`Signed in as ${i.user.email}`,o.green)}catch(i){s.signal.aborted||this.showError(i,!1)}this.stopSpinner(),this.render()}};async function ze(d){await new Z(d).run()}export{Z as App,ze as interactive};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h}from"./chunk-NQ54OCJ5.js";import"./chunk-4IWYTYSQ.js";import"./chunk-6DHFEWGX.js";export{h as age,c as isSessionId,g as listSessions,f as loadSession,b as newSessionId,d as repairConversation,e as saveSession,a as sessionsDir};
@@ -1,4 +1,4 @@
1
- import{c as g,d,m as L}from"./chunk-K3ZZ2VJH.js";import{spawn as F,spawnSync as te}from"node:child_process";import{accessSync as H,chmodSync as re,closeSync as G,constants as C,existsSync as J,mkdirSync as V,openSync as K,readFileSync as U,realpathSync as oe,rmSync as ie,writeFileSync as y}from"node:fs";import{homedir as W}from"node:os";var x="flintmaker",se=`https://registry.npmjs.org/${x}/latest`,ae=300*1e3,O=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,k=e=>typeof e=="string"&&O.test(e);function ce(e,n){let t=O.exec(e),r=O.exec(n);if(!t||!r)return 0;for(let a=1;a<=3;a++){let l=Number(t[a])-Number(r[a]);if(l)return l>0?1:-1}let o=t[4],s=r[4];if(o===s)return 0;if(o===void 0)return 1;if(s===void 0)return-1;let i=o.split("."),c=s.split(".");for(let a=0;a<Math.max(i.length,c.length);a++){if(i[a]===void 0)return-1;if(c[a]===void 0)return 1;if(i[a]===c[a])continue;let l=/^\d+$/.test(i[a]),f=/^\d+$/.test(c[a]);return l&&f?Number(i[a])>Number(c[a])?1:-1:l!==f?l?-1:1:i[a]>c[a]?1:-1}return 0}var P=(e,n)=>k(e)&&k(n)&&ce(e,n)>0,_=e=>!!e&&e!=="0"&&e.toLowerCase()!=="false";function Y(e=process.env,n=""){return _(e.FLINT_NO_UPDATE)?"FLINT_NO_UPDATE is set":_(e.CI)?"running in CI":_(e.NO_UPDATE_NOTIFIER)?"NO_UPDATE_NOTIFIER is set":!k(n)||n.startsWith("0.0.0")?"development build":null}var N=(e=process.env)=>e.FLINT_UPDATE_DIR||d().join(W(),".flintmaker");function w(e=N()){try{let n=JSON.parse(U(d().join(e,"update.json"),"utf8"));return n&&typeof n=="object"?n:{}}catch{return{}}}function p(e,n=N()){try{V(n,{recursive:!0,mode:448}),y(d().join(n,"update.json"),JSON.stringify(e,null,2)+`
1
+ import{a as g,b as d,k as L}from"./chunk-FEVGFFVL.js";import"./chunk-6DHFEWGX.js";import{spawn as F,spawnSync as te}from"node:child_process";import{accessSync as H,chmodSync as re,closeSync as G,constants as C,existsSync as J,mkdirSync as V,openSync as K,readFileSync as U,realpathSync as oe,rmSync as ie,writeFileSync as y}from"node:fs";import{homedir as W}from"node:os";var x="flintmaker",se=`https://registry.npmjs.org/${x}/latest`,ae=300*1e3,O=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,k=e=>typeof e=="string"&&O.test(e);function ce(e,n){let t=O.exec(e),r=O.exec(n);if(!t||!r)return 0;for(let a=1;a<=3;a++){let l=Number(t[a])-Number(r[a]);if(l)return l>0?1:-1}let o=t[4],s=r[4];if(o===s)return 0;if(o===void 0)return 1;if(s===void 0)return-1;let i=o.split("."),c=s.split(".");for(let a=0;a<Math.max(i.length,c.length);a++){if(i[a]===void 0)return-1;if(c[a]===void 0)return 1;if(i[a]===c[a])continue;let l=/^\d+$/.test(i[a]),f=/^\d+$/.test(c[a]);return l&&f?Number(i[a])>Number(c[a])?1:-1:l!==f?l?-1:1:i[a]>c[a]?1:-1}return 0}var P=(e,n)=>k(e)&&k(n)&&ce(e,n)>0,_=e=>!!e&&e!=="0"&&e.toLowerCase()!=="false";function Y(e=process.env,n=""){return _(e.FLINT_NO_UPDATE)?"FLINT_NO_UPDATE is set":_(e.CI)?"running in CI":_(e.NO_UPDATE_NOTIFIER)?"NO_UPDATE_NOTIFIER is set":!k(n)||n.startsWith("0.0.0")?"development build":null}var N=(e=process.env)=>e.FLINT_UPDATE_DIR||d().join(W(),".flintmaker");function w(e=N()){try{let n=JSON.parse(U(d().join(e,"update.json"),"utf8"));return n&&typeof n=="object"?n:{}}catch{return{}}}function p(e,n=N()){try{V(n,{recursive:!0,mode:448}),y(d().join(n,"update.json"),JSON.stringify(e,null,2)+`
2
2
  `)}catch{}}var le=(e,n=Date.now())=>!e.checkedAt||n-e.checkedAt>=ae||e.checkedAt>n;function ue(e,n={}){let t=n.platform??process.platform,r=d(t),o=g(t),s=n.env??process.env,i=n.exists??J,c=h=>o?r.normalize(h).toLowerCase():r.normalize(h),a=(h,ne)=>c(h).startsWith(c(ne).replace(/[\\/]+$/,"")+r.sep),l=r.normalize(e);if(c(l).split(r.sep).includes("_npx"))return{kind:"npx"};let m=`${r.sep}node_modules${r.sep}${x}${r.sep}`,v=c(l).lastIndexOf(c(m));if(v<0)return{kind:"dev"};let S=l.slice(0,v+m.length-x.length-2),u=r.dirname(S),b=n.home??W(),M=r.join(b,".flintmaker");if(a(l,M))return{kind:"flintmaker",prefix:M};if(o){let h=s.APPDATA?r.join(s.APPDATA,"npm"):null;return h&&c(u)===c(h)||i(r.join(u,"npm.cmd"))||i(r.join(u,"node.exe"))?{kind:"npm-global",prefix:u}:{kind:"local"}}return r.basename(u)==="lib"?{kind:"npm-global",prefix:r.dirname(u)}:{kind:"local"}}var A=(e,n=process.platform)=>g(n)?d(n).join(e,"node_modules"):d(n).join(e,"lib","node_modules");function de(e,n){let t=d(n),r=t.dirname(e);return g(n)?t.join(r,"node_modules","npm","bin","npm-cli.js"):t.join(r,"..","lib","node_modules","npm","bin","npm-cli.js")}function $(e,n,t={}){if(e.kind!=="flintmaker"&&e.kind!=="npm-global"||!k(n))return null;let r=t.platform??process.platform,o=d(r),s=t.exists??J,i=["install","-g","--prefix",e.prefix,"--prefer-online","--no-fund","--no-audit",`${x}@${n}`],c=[];e.kind==="flintmaker"&&c.push(g(r)?o.join(e.prefix,"node","node.exe"):o.join(e.prefix,"node","bin","node")),c.push(t.execPath??process.execPath);for(let a of c){let l=de(a,r);if(s(a)&&s(l))return{file:a,args:[l,...i],options:{windowsHide:!0}}}if(g(r)){let a=i.map(l=>/[\s&()^]/.test(l)?`"${l}"`:l).join(" ");return{file:t.env?.ComSpec||"cmd.exe",args:["/d","/s","/c",`"npm ${a}"`],options:{windowsVerbatimArguments:!0,windowsHide:!0}}}return{file:"npm",args:i,options:{}}}function j(e,n=process.platform){if(e.kind!=="flintmaker"&&e.kind!=="npm-global")return!1;try{return H(A(e.prefix,n),C.W_OK),g(n)||H(d(n).join(e.prefix,"bin"),C.W_OK),!0}catch{return!1}}function T(){try{return ue(oe(process.argv[1]??""))}catch{return{kind:"dev"}}}var I=(e,n)=>e.kind==="flintmaker"?`Update available v${n}: run flint update`:e.kind==="npx"?`Update available v${n}: run npx flintmaker@latest`:`Update available v${n}: run npm i -g ${x}`;async function R(e=3e3,n=process.env.FLINT_UPDATE_URL||se){try{let t=await fetch(n,{signal:AbortSignal.timeout(e),headers:{accept:"application/json"}});if(!t.ok)return null;let r=await t.json();return k(r?.version)?r.version:null}catch{return null}}function z(e){let n="dist/flint.js";if(typeof e=="string")n=e;else if(e&&typeof e=="object"){let t=e,r=t.flint??t.flintmaker??Object.values(t)[0];typeof r=="string"&&(n=r)}return n.replace(/^\.[\\/]/,"")}var E=["flint","flintmaker"];function fe(e,n=process.platform){let t=d(n);return g(n)?E.flatMap(r=>["",".cmd",".ps1"].map(o=>t.join(e,r+o))):E.map(r=>t.join(e,"bin",r))}function pe(e,n,t=process.platform){let r=d(t);if(g(t)){let i=["@echo off","rem FlintMaker CLI launcher (written by https://flintmaker.com/install.ps1)","setlocal",'set "FM_HOME=%~dp0"','set "FM_NODE=node"','if exist "%FM_HOME%node\\node.exe" set "FM_NODE=%FM_HOME%node\\node.exe"','if exist "%FM_HOME%node\\node.exe" set "PATH=%FM_HOME%node;%PATH%"',`"%FM_NODE%" "%FM_HOME%node_modules\\flintmaker\\${n.replace(/\//g,"\\")}" %*`,""].join(`\r
3
3
  `);return E.map(c=>({path:r.join(e,`${c}.cmd`),content:i}))}let o=i=>i.replace(/[\\"$`]/g,"\\$&"),s=`#!/bin/sh
4
4
  # FlintMaker CLI launcher (written by https://flintmaker.com/install.sh)
package/dist/flint.js CHANGED
@@ -1,30 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{a as se,b as A,c as ae,d as ce,e as R}from"./chunks/chunk-EUPBID7K.js";import{e as B,f as T,g as I,i as de,j as ue,l as fe,v as me}from"./chunks/chunk-K6EGUENI.js";import{b as m,c as le}from"./chunks/chunk-5PRYZOW7.js";import{c as J,e as X,f as D,g as Q,h as Z,i as ee,j as C,k as te,l as ne,m as oe,o as re,p as ie}from"./chunks/chunk-K3ZZ2VJH.js";import{spawn as $e,execFileSync as ke}from"node:child_process";import{existsSync as _e,lstatSync as Te,realpathSync as W}from"node:fs";import{mkdir as Ce,readdir as Pe,readFile as q,stat as pe,writeFile as Le}from"node:fs/promises";import{basename as he,dirname as Fe,join as Y,relative as ge,resolve as Se,sep as Ne}from"node:path";var P=class{diff(e,n,t={}){let r;typeof t=="function"?(r=t,t={}):"callback"in t&&(r=t.callback);let a=this.castInput(e,t),s=this.castInput(n,t),l=this.removeEmpty(this.tokenize(a,t)),i=this.removeEmpty(this.tokenize(s,t));return this.diffWithOptionsObj(l,i,t,r)}diffWithOptionsObj(e,n,t,r){var a;let s=u=>{if(u=this.postProcess(u,t),r){setTimeout(function(){r(u)},0);return}else return u},l=n.length,i=e.length,f=1,c=l+i;t.maxEditLength!=null&&(c=Math.min(c,t.maxEditLength));let d=(a=t.timeout)!==null&&a!==void 0?a:1/0,w=Date.now()+d,h=[{oldPos:-1,lastComponent:void 0}],v=this.extractCommon(h[0],n,e,0,t);if(h[0].oldPos+1>=i&&v+1>=l)return s(this.buildValues(h[0].lastComponent,n,e));let p=-1/0,b=1/0,E=()=>{for(let u=Math.max(p,-f);u<=Math.min(b,f);u+=2){let g,y=h[u-1],x=h[u+1];y&&(h[u-1]=void 0);let _=!1;if(x){let G=x.oldPos-u;_=x&&0<=G&&G<l}let L=y&&y.oldPos+1<i;if(!_&&!L){h[u]=void 0;continue}if(!L||_&&y.oldPos<x.oldPos?g=this.addToPath(x,!0,!1,0,t):g=this.addToPath(y,!1,!0,1,t),v=this.extractCommon(g,n,e,u,t),g.oldPos+1>=i&&v+1>=l)return s(this.buildValues(g.lastComponent,n,e))||!0;h[u]=g,g.oldPos+1>=i&&(b=Math.min(b,u-1)),v+1>=l&&(p=Math.max(p,u+1))}f++};if(r)(function u(){setTimeout(function(){if(f>c||Date.now()>w)return r(void 0);E()||u()},0)})();else for(;f<=c&&Date.now()<=w;){let u=E();if(u)return u}}addToPath(e,n,t,r,a){let s=e.lastComponent;return s&&!a.oneChangePerToken&&s.added===n&&s.removed===t?{oldPos:e.oldPos+r,lastComponent:{count:s.count+1,added:n,removed:t,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:n,removed:t,previousComponent:s}}}extractCommon(e,n,t,r,a){let s=n.length,l=t.length,i=e.oldPos,f=i-r,c=0;for(;f+1<s&&i+1<l&&this.equals(t[i+1],n[f+1],a);)f++,i++,c++,a.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return c&&!a.oneChangePerToken&&(e.lastComponent={count:c,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=i,f}equals(e,n,t){return t.comparator?t.comparator(e,n):e===n||!!t.ignoreCase&&e.toLowerCase()===n.toLowerCase()}removeEmpty(e){let n=[];for(let t=0;t<e.length;t++)e[t]&&n.push(e[t]);return n}castInput(e,n){return e}tokenize(e,n){return Array.from(e)}join(e){return e.join("")}postProcess(e,n){return e}get useLongestToken(){return!1}buildValues(e,n,t){let r=[],a;for(;e;)r.push(e),a=e.previousComponent,delete e.previousComponent,e=a;r.reverse();let s=r.length,l=0,i=0,f=0;for(;l<s;l++){let c=r[l];if(c.removed)c.value=this.join(t.slice(f,f+c.count)),f+=c.count;else{if(!c.added&&this.useLongestToken){let d=n.slice(i,i+c.count);d=d.map(function(w,h){let v=t[f+h];return v.length>w.length?v:w}),c.value=this.join(d)}else c.value=this.join(n.slice(i,i+c.count));i+=c.count,c.added||(f+=c.count)}}return r}};var M=class extends P{constructor(){super(...arguments),this.tokenize=ye}equals(e,n,t){return t.ignoreWhitespace?((!t.newlineIsToken||!e.includes(`
3
- `))&&(e=e.trim()),(!t.newlineIsToken||!n.includes(`
4
- `))&&(n=n.trim())):t.ignoreNewlineAtEof&&!t.newlineIsToken&&(e.endsWith(`
5
- `)&&(e=e.slice(0,-1)),n.endsWith(`
6
- `)&&(n=n.slice(0,-1))),super.equals(e,n,t)}},be=new M;function j(o,e,n){return be.diff(o,e,n)}function ye(o,e){e.stripTrailingCr&&(o=o.replace(/\r\n/g,`
7
- `));let n=[],t=o.split(/(\n|\r\n)/);t[t.length-1]||t.pop();for(let r=0;r<t.length;r++){let a=t[r];r%2&&!e.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n}function xe(o){for(let e=0;e<o.length;e++)if(o[e]<" "||o[e]>"~"||o[e]==='"'||o[e]==="\\")return!0;return!1}function k(o){if(!xe(o))return o;let e='"',n=new TextEncoder().encode(o),t=0;for(;t<n.length;){let r=n[t];r===7?e+="\\a":r===8?e+="\\b":r===9?e+="\\t":r===10?e+="\\n":r===11?e+="\\v":r===12?e+="\\f":r===13?e+="\\r":r===34?e+='\\"':r===92?e+="\\\\":r>=32&&r<=126?e+=String.fromCharCode(r):e+="\\"+r.toString(8).padStart(3,"0"),t++}return e+='"',e}var U={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function O(o,e,n,t,r,a,s){let l;s?typeof s=="function"?l={callback:s}:l=s:l={},typeof l.context>"u"&&(l.context=4);let i=l.context;if(l.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(l.callback){let{callback:c}=l;j(n,t,Object.assign(Object.assign({},l),{callback:d=>{let w=f(d);c(w)}}))}else return f(j(n,t,l));function f(c){if(!c)return;c.push({value:"",lines:[]});function d(u){return u.map(function(g){return" "+g})}let w=[],h=0,v=0,p=[],b=1,E=1;for(let u=0;u<c.length;u++){let g=c[u],y=g.lines||Ee(g.value);if(g.lines=y,g.added||g.removed){if(!h){let x=c[u-1];h=b,v=E,x&&(p=i>0?d(x.lines.slice(-i)):[],h-=p.length,v-=p.length)}for(let x of y)p.push((g.added?"+":"-")+x);g.added?E+=y.length:b+=y.length}else{if(h)if(y.length<=i*2&&u<c.length-2)for(let x of d(y))p.push(x);else{let x=Math.min(y.length,i);for(let L of d(y.slice(0,x)))p.push(L);let _={oldStart:h,oldLines:b-h+x,newStart:v,newLines:E-v+x,lines:p};w.push(_),h=0,v=0,p=[]}b+=y.length,E+=y.length}}for(let u of w)for(let g=0;g<u.lines.length;g++)u.lines[g].endsWith(`
8
- `)?u.lines[g]=u.lines[g].slice(0,-1):(u.lines.splice(g+1,0,"\"),g++);return{oldFileName:o,newFileName:e,oldHeader:r,newHeader:a,hunks:w}}}function F(o,e){var n,t,r,a,s,l;if(e||(e=U),Array.isArray(o)){if(o.length>1&&!e.includeFileHeaders&&!o.every(c=>c.isGit))throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");return o.map(c=>F(c,e)).join(`
9
- `)}let i=[];if(o.isGit){if(e=U,!o.oldFileName)throw new Error("oldFileName must be specified for Git patches");if(!o.newFileName)throw new Error("newFileName must be specified for Git patches");let c=o.oldFileName,d=o.newFileName;o.isCreate&&c==="/dev/null"?c=d.replace(/^b\//,"a/"):o.isDelete&&d==="/dev/null"&&(d=c.replace(/^a\//,"b/")),i.push("diff --git "+k(c)+" "+k(d)),o.isDelete&&i.push("deleted file mode "+((n=o.oldMode)!==null&&n!==void 0?n:"100644")),o.isCreate&&i.push("new file mode "+((t=o.newMode)!==null&&t!==void 0?t:"100644")),o.oldMode&&o.newMode&&!o.isDelete&&!o.isCreate&&(i.push("old mode "+o.oldMode),i.push("new mode "+o.newMode)),o.isRename&&(i.push("rename from "+k(((r=o.oldFileName)!==null&&r!==void 0?r:"").replace(/^a\//,""))),i.push("rename to "+k(((a=o.newFileName)!==null&&a!==void 0?a:"").replace(/^b\//,"")))),o.isCopy&&(i.push("copy from "+k(((s=o.oldFileName)!==null&&s!==void 0?s:"").replace(/^a\//,""))),i.push("copy to "+k(((l=o.newFileName)!==null&&l!==void 0?l:"").replace(/^b\//,""))))}else e.includeIndex&&o.oldFileName==o.newFileName&&o.oldFileName!==void 0&&i.push("Index: "+o.oldFileName),e.includeUnderline&&i.push("===================================================================");let f=o.hunks.length>0;e.includeFileHeaders&&o.oldFileName!==void 0&&o.newFileName!==void 0&&(!o.isGit||f)&&(i.push("--- "+k(o.oldFileName)+(o.oldHeader?" "+o.oldHeader:"")),i.push("+++ "+k(o.newFileName)+(o.newHeader?" "+o.newHeader:"")));for(let c=0;c<o.hunks.length;c++){let d=o.hunks[c],w=d.oldLines===0?d.oldStart-1:d.oldStart,h=d.newLines===0?d.newStart-1:d.newStart;i.push("@@ -"+w+","+d.oldLines+" +"+h+","+d.newLines+" @@");for(let v of d.lines)i.push(v)}return i.join(`
10
- `)+`
11
- `}function H(o,e,n,t,r,a,s){if(typeof s=="function"&&(s={callback:s}),s?.callback){let{callback:l}=s;O(o,e,n,t,r,a,Object.assign(Object.assign({},s),{callback:i=>{l(i?F(i,s.headerOptions):void 0)}}))}else{let l=O(o,e,n,t,r,a,s);return l?F(l,s?.headerOptions):void 0}}function Ee(o){let e=o.endsWith(`
12
- `),n=o.split(`
13
- `).map(t=>t+`
14
- `);return e?n.pop():n.push(n.pop().slice(0,-1)),n}var Ie=new Set(["node_modules",".git","dist","build",".next",".nuxt",".svelte-kit","coverage",".venv","venv","__pycache__",".turbo",".cache","Pods","DerivedData"]),De=/^(\.env(\..+)?|\.envrc|\.dev\.vars|\.netrc|\.git-credentials|\.npmrc|\.pypirc|.*\.(pem|key|p12|pfx|keystore|jks|tfvars|tfstate)|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|credentials(\.json)?|.*service[-_]?account.*\.json|.*-credentials\.json)$/i,Ae=/^\.env\.(example|sample|template)$/i,Re=1e5,z=400,Me=12e3,S=class{root;constructor(e){this.root=W(e)}resolve(e){if(typeof e!="string"||e.trim()==="")throw new Error("path is required");let n=e.trim(),t=X(n);if(t)throw new Error(t);let r=Se(this.root,n);if(!D(this.root,r))throw new Error(`${n} is outside the project`);let a=this.root;for(let l of ge(this.root,r).split(Ne).filter(Boolean)){a=Y(a,l);let i;try{i=Te(a)}catch{break}if(i.isSymbolicLink()){let f;try{f=W(a)}catch{throw new Error(`${n} goes through a broken symlink; refusing`)}if(!D(this.root,f))throw new Error(`${n} is outside the project`)}}let s=[Q(he(r))];if(J())try{s.push(he(W.native(r)))}catch{}if(s.some(l=>De.test(l)&&!Ae.test(l)))throw new Error(`${n} looks like a secret file; flint does not read or change it`);return r}rel(e){return Z(ge(this.root,e))||"."}async listFiles(e="."){let n=this.resolve(e),t;try{t=ke("git",["ls-files","--cached","--others","--exclude-standard","--",this.rel(n)],{cwd:this.root,encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:!0,maxBuffer:16*1024*1024}).split(/\r?\n/).filter(Boolean)}catch{t=[],await this.walk(n,t)}return t.sort(),t.slice(0,z).join(`
15
- `)+(t.length>z?`
16
- \u2026 ${t.length-z} more files`:"")||"(empty)"}async walk(e,n){if(!(n.length>5e3))for(let t of await Pe(e,{withFileTypes:!0}))t.isDirectory()?Ie.has(t.name)||await this.walk(Y(e,t.name),n):t.isFile()&&n.push(this.rel(Y(e,t.name)))}async readFile(e,n,t){let r=this.resolve(e),a=await pe(r);if(!a.isFile())throw new Error(`${e} is not a file`);let s=await q(r);if(s.subarray(0,8e3).includes(0))return`[binary file, ${a.size} bytes]`;let l=s.toString("utf8").split(/\r?\n/);l.at(-1)===""&&l.pop();let i=Math.max(1,n??1),f=Math.min(l.length,t??l.length),c="";for(let d=i;d<=f;d++){let w=`${d} ${l[d-1]}`;if(c.length+w.length>Re){c+=`
17
- [truncated at line ${d-1} of ${l.length}; read more with start_line]`;break}c+=(c?`
18
- `:"")+w}return c}async search(e,n="."){let t;try{t=new RegExp(e)}catch{throw new Error("invalid regular expression")}let r=(await this.listFiles(n)).split(`
19
- `).filter(s=>s&&!s.startsWith("\u2026 ")),a=[];for(let s of r){if(a.length>=200)break;let l;try{let i=this.resolve(s);if((await pe(i)).size>4e5)continue;let f=await q(i);if(f.subarray(0,8e3).includes(0))continue;l=f.toString("utf8")}catch{continue}l.split(/\r?\n/).forEach((i,f)=>{a.length<200&&t.test(i)&&a.push(`${s}:${f+1}:${i.slice(0,300)}`)})}return a.join(`
20
- `)||"No matches."}async plan(e,n){let t=this.resolve(n.path),r=this.rel(t),a=_e(t)?await q(t,"utf8"):null,s=a!==null&&ee(a)==="crlf",l=a!==null&&s?C(a):a,i;if(e==="write_file"){if(typeof n.content!="string")throw new Error("content is required");i=s?C(n.content):n.content}else{if(l===null)throw new Error(`${r} does not exist`);if(typeof n.old_text!="string"||n.old_text===""||typeof n.new_text!="string")throw new Error("old_text and new_text are required");let d=s?C(n.old_text):n.old_text,w=s?C(n.new_text):n.new_text,h=l.split(d).length-1;if(h===0)throw new Error(`old_text not found in ${r}`);if(h>1)throw new Error(`old_text matches ${h} times in ${r}; include more context`);i=l.replace(d,()=>w)}let f=H(`a/${r}`,`b/${r}`,l??"",i,"","",{context:3}),c=s?te(i):i;return{path:r,diff:f,created:a===null,apply:async()=>{await Ce(Fe(t),{recursive:!0}),await Le(t,c)}}}runCommand(e,n=12e4,t){return new Promise(r=>{if(t?.aborted)return r("[interrupted by the user before it started]");let a=ne(e),s;try{s=$e(a.file,a.args,{...a.options,cwd:this.root,env:{...process.env,FORCE_COLOR:"0",CI:"1"}})}catch(b){return r(`[could not run command: ${b.message}]`)}let l="",i="",f=0,c=b=>{let E=b.toString("utf8");if(l.length<4e3){let u=4e3-l.length;l+=E.slice(0,u),i+=E.slice(u)}else i+=E;i.length>8e3&&(f+=i.length-8e3,i=i.slice(-8e3))};s.stdout.on("data",c),s.stderr.on("data",c);let d=!1,w=!1,h=()=>oe(s.pid,process.platform,()=>s.kill("SIGKILL")),v=setTimeout(()=>{d=!0,h()},n),p=()=>{w=!0,h()};t?.addEventListener("abort",p,{once:!0}),s.on("close",b=>{clearTimeout(v),t?.removeEventListener("abort",p);let E=(l+(f?`
21
- [\u2026 ${f} characters omitted \u2026]
22
- `:"")+i).replace(/\r\n/g,`
23
- `),u=w?"[interrupted by the user]":d?`[timed out after ${Math.round(n/1e3)}s]`:`[exit code ${b}]`;r(`${E.slice(0,Me)}
24
- ${u}`.trim())}),s.on("error",b=>{clearTimeout(v),t?.removeEventListener("abort",p),r(`[could not run command: ${b.message}]`)})})}};var $=B,je=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/,N=je.test(process.env.FLINT_JUST_UPDATED??"")?process.env.FLINT_JUST_UPDATED:null,Ue=!!process.env.FLINT_NO_UPDATE_CHECK_ONCE&&process.env.FLINT_NO_UPDATE_CHECK_ONCE!=="0";delete process.env.FLINT_JUST_UPDATED;delete process.env.FLINT_NO_UPDATE_CHECK_ONCE;var Oe=()=>`
25
- ${m.ember("\u2726")} ${m.bold(le("FlintMaker"))} ${m.bold("flint")} ${m.grey(`v${$}`)} ${m.grey("\u2014 the AI coding agent for your terminal")}
2
+ import{a as D,b as I,c as V,d as q,e as U}from"./chunks/chunk-EBWJOG3A.js";import{a as R,b as l,c as N,e as K,f as W,h as H}from"./chunks/chunk-OMZ5ETOR.js";import{b as o,c as Y}from"./chunks/chunk-MQW5CMHG.js";import{j,m as M}from"./chunks/chunk-IZWMUOBI.js";import"./chunks/chunk-4IWYTYSQ.js";import{m as L,n as O}from"./chunks/chunk-FEVGFFVL.js";import"./chunks/chunk-6DHFEWGX.js";var c=R,X=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/,y=X.test(process.env.FLINT_JUST_UPDATED??"")?process.env.FLINT_JUST_UPDATED:null,tt=!!process.env.FLINT_NO_UPDATE_CHECK_ONCE&&process.env.FLINT_NO_UPDATE_CHECK_ONCE!=="0";delete process.env.FLINT_JUST_UPDATED;delete process.env.FLINT_NO_UPDATE_CHECK_ONCE;var et=()=>`
3
+ ${o.ember("\u2726")} ${o.bold(Y("FlintMaker"))} ${o.bold("flint")} ${o.grey(`v${c}`)} ${o.grey("\u2014 the AI coding agent for your terminal")}
26
4
 
27
- ${m.bold("Usage")}
5
+ ${o.bold("Usage")}
28
6
  flint start an interactive session in this folder
29
7
  flint "task" do one task, then exit (plain output, good for scripts)
30
8
  flint login connect this computer to your FlintMaker account
@@ -32,30 +10,38 @@ ${u}`.trim())}),s.on("error",b=>{clearTimeout(v),t?.removeEventListener("abort",
32
10
  flint whoami show account and credits
33
11
  flint update update flint now (it also updates itself automatically)
34
12
 
35
- ${m.bold("Options")}
13
+ ${o.bold("Options")}
14
+ -p, --print run without prompts (scripts and CI)
15
+ --output-format <format> text, json or stream-json (with -p)
16
+ --max-turns <n> maximum model turns (with -p; default 25)
36
17
  --smart use the Smart model (paid plans, more credits)
37
18
  --plan plan only: read the project, change nothing
38
- --yes approve every change and command (careful!)
19
+ --yes approve every change, patch and command; refused ones stay refused (careful!)
20
+ -c, --continue continue the last conversation in this folder
21
+ --resume [id] pick a saved conversation (or resume one by id)
22
+ --privacy privacy mode: no history or sessions saved, no web tools
23
+ --allow-push let flint run git push after you approve it (never forced)
24
+ --timeout <seconds> time limit per command (default 120)
39
25
  --help, --version
40
26
 
41
- ${m.bold("In a session")}
42
- /help /model /mode /clear /compact /credits /init /update /login /logout /exit
27
+ ${o.bold("In a session")}
28
+ /help /model /mode /clear /resume /rewind /compact /credits /init /update /login /logout /exit
43
29
  @path attaches a file \xB7 shift+tab switches mode \xB7 esc interrupts
44
- `;function He(o){let e=new Set(o.filter(t=>t.startsWith("--"))),n=o.filter(t=>!t.startsWith("--"));return{flags:e,rest:n}}async function we(){let o=new I(R(null));console.log();let e=await o.deviceLogin((n,t)=>{console.log(` ${m.ember("\u2726")} Your code: ${m.bold(m.gold(n))}`),console.log(` ${m.grey("Opening")} ${t}`),console.log(` ${m.grey("Approve it in the browser. Waiting\u2026")}`),se(t)});ae({token:e.token,email:e.user.email,api:o.base}),console.log(`
45
- ${m.green("\u2713")} Signed in as ${m.bold(e.user.email)}. Run ${m.bold("flint")} in any project folder.
46
- `)}async function We(){let o="";process.stdin.setEncoding("utf8");for await(let e of process.stdin)o+=e;return o.trim()}var K=()=>Promise.all([import("./chunks/repl-5SO4OJNB.js"),import("./chunks/plain-32HV3XHW.js"),import("./chunks/highlight-QJIBHZTN.js"),import("./chunks/render-73QVSOTH.js")]);function qe(o){let e=!1,n=()=>import("./chunks/update-A3SQIJXY.js").then(t=>t.autoUpdate({current:$,notify:r=>ue(r),preload:K,ready:()=>{e=!0,fe("Update ready \u2014 restart flint")}})).then(t=>{(t==="disabled"||t==="hint"||t==="failed")&&(e=!0)}).catch(()=>{});setTimeout(n,200).unref(),o&&import("./chunks/update-A3SQIJXY.js").then(t=>{let r=setInterval(()=>e?clearInterval(r):void n(),t.CHECK_EVERY_MS+1e3);r.unref()}).catch(()=>{})}function V(o){let e=["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D","\u273B","\u2736","\u2733","\u2722"],n=0,t=()=>process.stdout.write(`\r ${m.ember(e[n++%e.length])} ${o}\x1B[K`);process.stdout.write("\x1B[?25l"),t();let r=setInterval(t,100);return()=>{clearInterval(r),process.stdout.write("\r\x1B[K\x1B[?25h")}}async function Ye(){if(Ue||N)return null;let o=await import("./chunks/update-A3SQIJXY.js"),e=await o.foregroundUpdate({current:$,interactive:!0,spinner:V,preload:K});return e.status==="reexec"?e.code??0:(e.status==="failed"&&console.log(` ${m.ember("\u2726")} ${m.grey(`Could not update to v${e.latest}; continuing with v${$}. Details: ${o.stateDir()}${process.platform==="win32"?"\\":"/"}update.log`)}`),e.status==="cancelled"&&console.log(` ${m.ember("\u2726")} ${m.grey(`Update skipped; continuing with v${$}.`)}`),null)}async function ze(){let o=await import("./chunks/update-A3SQIJXY.js"),e=await o.foregroundUpdate({current:$,interactive:!0,force:!0,spinner:V,preload:K});if(e.status==="reexec")return e.code??0;if(e.status==="current")console.log(` ${m.ember("\u2726")} flint v${$} is the newest version.`);else if(e.status==="offline")console.log(` ${m.ember("\u2726")} ${m.grey("Could not reach the update server. Check your connection and try again.")}`);else{let t=o.currentInstall().kind==="npx"?"npx flintmaker@latest":"npm i -g flintmaker@latest";console.log(` ${m.ember("\u2726")} ${m.grey(`Could not update automatically. Run: ${t}`)}`)}return 0}async function ve(o){let e=!!process.stdin.isTTY&&!!process.stdout.isTTY,n=await import("./chunks/update-A3SQIJXY.js");if(e&&!N){let a=await n.foregroundUpdate({current:$,interactive:!0,force:!0,spinner:V});if(a.status==="reexec")return a.code??0}let t=n.currentInstall(),r=t.kind==="npx"?"npx flintmaker@latest":t.kind==="flintmaker"?"flint update":"npm i -g flintmaker@latest";return process.stderr.write(`
47
- ${m.red("\u2717")} ${m.bold("flint needs an update")}
48
- ${o.message}
30
+ `,ot=new Set(["--timeout","--output-format","--max-turns"]),nt=new Set(["--resume"]);function st(t){let e=new Set,s=new Map,n=[];for(let r=0;r<t.length;r++){let i=t[r];if(i==="-p"&&(i="--print"),i==="-c"&&(i="--continue"),i==="-y"&&(i="--yes"),!i.startsWith("--")){n.push(i);continue}let d=i.indexOf("="),u=d===-1?i:i.slice(0,d);if(e.add(u),d!==-1)s.set(u,i.slice(d+1));else if(ot.has(u)){if(t[r+1]===void 0||t[r+1].startsWith("--"))throw new l(`${u} requires a value`);s.set(u,t[++r])}else nt.has(u)&&/^\d{8}T\d{6}-[0-9a-f]{6}$/.test(t[r+1]??"")&&s.set(u,t[++r])}return{flags:e,values:s,rest:n}}async function J(){let t=new N(U(null));console.log();let e=await t.deviceLogin((s,n)=>{console.log(` ${o.ember("\u2726")} Your code: ${o.bold(o.gold(s))}`),console.log(` ${o.grey("Opening")} ${n}`),console.log(` ${o.grey("Approve it in the browser. Waiting\u2026")}`),D(n)});V({token:e.token,email:e.user.email,api:t.base}),console.log(`
31
+ ${o.green("\u2713")} Signed in as ${o.bold(e.user.email)}. Run ${o.bold("flint")} in any project folder.
32
+ `)}async function rt(){let t="";process.stdin.setEncoding("utf8");for await(let e of process.stdin)t+=e;return t.trim()}var C=()=>Promise.all([import("./chunks/repl-764CFGWW.js"),import("./chunks/plain-IR6PPFKU.js"),import("./chunks/highlight-2UNDOBIV.js"),import("./chunks/render-ZGZKZ2WL.js")]);function it(t){let e=!1,s=()=>import("./chunks/update-2MKXAMLY.js").then(n=>n.autoUpdate({current:c,notify:r=>W(r),preload:C,ready:()=>{e=!0,H("Update ready \u2014 restart flint")}})).then(n=>{(n==="disabled"||n==="hint"||n==="failed")&&(e=!0)}).catch(()=>{});setTimeout(s,200).unref(),t&&import("./chunks/update-2MKXAMLY.js").then(n=>{let r=setInterval(()=>e?clearInterval(r):void s(),n.CHECK_EVERY_MS+1e3);r.unref()}).catch(()=>{})}function F(t){let e=["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D","\u273B","\u2736","\u2733","\u2722"],s=0,n=()=>process.stdout.write(`\r ${o.ember(e[s++%e.length])} ${t}\x1B[K`);process.stdout.write("\x1B[?25l"),n();let r=setInterval(n,100);return()=>{clearInterval(r),process.stdout.write("\r\x1B[K\x1B[?25h")}}async function at(){if(tt||y)return null;let t=await import("./chunks/update-2MKXAMLY.js"),e=await t.foregroundUpdate({current:c,interactive:!0,spinner:F,preload:C});return e.status==="reexec"?e.code??0:(e.status==="failed"&&console.log(` ${o.ember("\u2726")} ${o.grey(`Could not update to v${e.latest}; continuing with v${c}. Details: ${t.stateDir()}${process.platform==="win32"?"\\":"/"}update.log`)}`),e.status==="cancelled"&&console.log(` ${o.ember("\u2726")} ${o.grey(`Update skipped; continuing with v${c}.`)}`),null)}async function ct(){let t=await import("./chunks/update-2MKXAMLY.js"),e=await t.foregroundUpdate({current:c,interactive:!0,force:!0,spinner:F,preload:C});if(e.status==="reexec")return e.code??0;if(e.status==="current")console.log(` ${o.ember("\u2726")} flint v${c} is the newest version.`);else if(e.status==="offline")console.log(` ${o.ember("\u2726")} ${o.grey("Could not reach the update server. Check your connection and try again.")}`);else{let n=t.currentInstall().kind==="npx"?"npx flintmaker@latest":"npm i -g flintmaker@latest";console.log(` ${o.ember("\u2726")} ${o.grey(`Could not update automatically. Run: ${n}`)}`)}return 0}async function B(t){let e=!!process.stdin.isTTY&&!!process.stdout.isTTY,s=await import("./chunks/update-2MKXAMLY.js");if(e&&!y){let i=await s.foregroundUpdate({current:c,interactive:!0,force:!0,spinner:F});if(i.status==="reexec")return i.code??0}let n=s.currentInstall(),r=n.kind==="npx"?"npx flintmaker@latest":n.kind==="flintmaker"?"flint update":"npm i -g flintmaker@latest";return process.stderr.write(`
33
+ ${o.red("\u2717")} ${o.bold("flint needs an update")}
34
+ ${t.message}
49
35
  Run: ${r}
50
36
 
51
- `),1}async function Ke(){if(!re())for(let p of[process.stdout,process.stderr])p.isTTY&&ie(p);let{flags:o,rest:e}=He(process.argv.slice(2));if(o.has("--version")||o.has("-v"))return console.log($);if(o.has("--help")||e[0]==="help"||e[0]==="-h")return console.log(Oe());if(e[0]==="login")return we();if(e[0]==="__update"&&e[1]){let{updateWorker:p}=await import("./chunks/update-A3SQIJXY.js");return p(e[1])}if(e[0]==="update"&&e.length===1){let{updateNow:p}=await import("./chunks/update-A3SQIJXY.js");return p($,b=>console.log(` ${b}`))}if(e[0]==="logout")return ce(),console.log(`
52
- Signed out. ${m.grey("Disconnect old terminals any time on your account page.")}
53
- `);let n=!!process.stdin.isTTY&&!!process.stdout.isTTY,t=n&&e.length===0;if(t){let p=await Ye();if(p!==null)return p}if(!A()){if(!n)return process.stderr.write(`flint: not signed in. Run: flint login
54
- `),1;let{welcome:p,shortPath:b}=await import("./chunks/render-73QVSOTH.js"),{homedir:E}=await import("node:os"),u=Math.max(40,process.stdout.columns||80);console.log();let g={version:$,model:o.has("--smart")?"smart":"standard",cwd:b(process.cwd(),E(),28),status:"not signed in yet",updated:N?$:void 0};for(let y of p(g,u))console.log(y);console.log(`
55
- ${m.ember("\u2726")} Welcome to ${m.bold("flint")}. Let's connect your FlintMaker account (opening your browser):`),await we()}let r=A(),a=R(r);if(a!==r.api)throw new T(`This token belongs to ${r.api}. Run flint login to use ${a}.`);let s=new I(a,r.token);if(e[0]==="whoami"){let p=await s.me();return console.log(`
56
- ${m.bold(p.user.email)} \xB7 ${p.user.plan} \xB7 ${me(p.usage)}
57
- `)}let l=new S(process.cwd()),i=o.has("--smart")?"smart":"standard",f=o.has("--plan")?"plan":"ask",c=o.has("--yes");qe(t);let d=e.join(" ").trim();if(!d&&!process.stdin.isTTY&&(d=await We()),d||!n){if(!d)throw new T('Nothing to do. Pass a task: flint "fix the failing test"');let{oneShot:p}=await import("./chunks/plain-32HV3XHW.js");return p(d,{client:s,ws:l,model:i,autoYes:c,mode:f})}let{interactive:w}=await import("./chunks/repl-5SO4OJNB.js"),h=null,v=!1;if(await w({version:$,client:s,ws:l,model:i,autoYes:c,mode:f,updated:N?$:void 0,onUpdateRequired:()=>h=new T(`FlintMaker no longer serves flint v${$}.`,"update_required",426),onUpdateNow:()=>v=!0}),h)return ve(h);if(v)return ze()}Ke().then(o=>{typeof o=="number"&&o!==0&&(process.exitCode=o),setTimeout(()=>process.exit(),20).unref()},async o=>{if(o instanceof T&&o.reason==="update_required")return process.exitCode=await ve(o).catch(()=>1),void setTimeout(()=>process.exit(),20).unref();let e=de(o);process.stderr.write(`
58
- ${m.red("\u2717")} ${m.bold(e.title)}
59
- ${e.lines.map(n=>` ${n}
37
+ `),1}async function lt(){if(!L())for(let a of[process.stdout,process.stderr])a.isTTY&&O(a);let{flags:t,values:e,rest:s}=st(process.argv.slice(2));if(t.has("--version")||t.has("-v"))return console.log(c);if(t.has("--help")||s[0]==="help"||s[0]==="-h")return console.log(et());let n=t.has("--print"),r=e.get("--output-format")??"text",i=Number(e.get("--max-turns")??25);if(!["text","json","stream-json"].includes(r))throw new l("--output-format must be text, json or stream-json");if(!Number.isInteger(i)||i<1||i>1e3)throw new l("--max-turns must be an integer from 1 to 1000");if(!n&&(t.has("--output-format")||t.has("--max-turns")))throw new l("--output-format and --max-turns require -p");if(!n&&s[0]==="login")return J();if(!n&&s[0]==="__update"&&s[1]){let{updateWorker:a}=await import("./chunks/update-2MKXAMLY.js");return a(s[1])}if(!n&&s[0]==="update"&&s.length===1){let{updateNow:a}=await import("./chunks/update-2MKXAMLY.js");return a(c,f=>console.log(` ${f}`))}if(!n&&s[0]==="logout")return q(),console.log(`
38
+ Signed out. ${o.grey("Disconnect old terminals any time on your account page.")}
39
+ `);let d=!!process.stdin.isTTY&&!!process.stdout.isTTY,u=!n&&d&&s.length===0;if(u){let a=await at();if(a!==null)return a}if(!I()){if(n||!d)return process.stderr.write(`flint: not signed in. Run: flint login
40
+ `),1;let{welcome:a,shortPath:f}=await import("./chunks/render-ZGZKZ2WL.js"),{homedir:g}=await import("node:os"),z=Math.max(40,process.stdout.columns||80);console.log();let Z={version:c,model:t.has("--smart")?"smart":"standard",cwd:f(process.cwd(),g(),28),status:"not signed in yet",updated:y?c:void 0};for(let Q of a(Z,z))console.log(Q);console.log(`
41
+ ${o.ember("\u2726")} Welcome to ${o.bold("flint")}. Let's connect your FlintMaker account (opening your browser):`),await J()}let v=I(),b=U(v);if(b!==v.api)throw new l(`This token belongs to ${v.api}. Run flint login to use ${b}.`);let p=new N(b,v.token),w=t.has("--privacy")||!!process.env.FLINT_PRIVACY&&process.env.FLINT_PRIVACY!=="0";if(p.privacy=w,!n&&s[0]==="whoami"){let a=await p.me();return console.log(`
42
+ ${o.bold(a.user.email)} \xB7 ${a.user.plan} \xB7 ${M(a.usage)}
43
+ `)}let m=new j(process.cwd());p.settings=m.settings,p.mcp=m.mcp;let T=t.has("--smart")?"smart":"standard",k=t.has("--plan")?"plan":"ask",x=t.has("--yes"),_=Number(e.get("--timeout")),E={allowPush:t.has("--allow-push"),timeoutMs:Number.isFinite(_)&&_>0?Math.min(3600,_)*1e3:void 0},$;if(t.has("--continue")||e.has("--resume")){if(w)throw new l("Privacy mode saves no conversations, so there is nothing to continue.");let{listSessions:a,loadSession:f}=await import("./chunks/sessions-J2WOKTGW.js"),g=e.has("--resume")?f(e.get("--resume")):a(m.root,1)[0];if(!g)throw new l(e.has("--resume")?`No saved conversation ${e.get("--resume")}.`:"No saved conversation in this folder yet.");if(g.root!==m.root)throw new l(`That conversation belongs to ${g.root}. Run flint there.`);$=g}let P=t.has("--resume")&&!e.has("--resume");n||it(u);let h=s.join(" ").trim();if(!h&&!process.stdin.isTTY&&(h=await rt()),n||h||!d){if(!h)throw new l('Nothing to do. Pass a task: flint "fix the failing test"');let{oneShot:a}=await import("./chunks/plain-IR6PPFKU.js");if(P)throw new l('Pick a conversation in an interactive session, or pass its id: flint --resume <id> "task"');if(n){let{headless:f}=await import("./chunks/headless-X75XCEC6.js");return f(h,{client:p,ws:m,model:T,autoYes:x,mode:k,policy:E,privacy:w,resume:$,outputFormat:r,maxTurns:i})}return a(h,{client:p,ws:m,model:T,autoYes:x,mode:k,policy:E,privacy:w,resume:$})}let{interactive:G}=await import("./chunks/repl-764CFGWW.js"),S=null,A=!1;if(await G({version:c,client:p,ws:m,model:T,autoYes:x,mode:k,policy:E,privacy:w,resume:$,pickSession:P,updated:y?c:void 0,onUpdateRequired:()=>S=new l(`FlintMaker no longer serves flint v${c}.`,"update_required",426),onUpdateNow:()=>A=!0}),S)return B(S);if(A)return ct()}lt().then(t=>{typeof t=="number"&&t!==0&&(process.exitCode=t),setTimeout(()=>process.exit(),20).unref()},async t=>{if(t instanceof l&&t.reason==="update_required")return process.exitCode=await B(t).catch(()=>1),void setTimeout(()=>process.exit(),20).unref();let e=K(t);process.stderr.write(`
44
+ ${o.red("\u2717")} ${o.bold(e.title)}
45
+ ${e.lines.map(s=>` ${s}
60
46
  `).join("")}
61
47
  `),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flintmaker",
3
- "version": "0.2.6",
3
+ "version": "0.5.0",
4
4
  "description": "flint — the FlintMaker AI coding agent for your terminal.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "PT Jiji Labs Digital",
@@ -12,7 +12,8 @@
12
12
  },
13
13
  "files": [
14
14
  "dist",
15
- "README.md"
15
+ "README.md",
16
+ "CHANGELOG.md"
16
17
  ],
17
18
  "engines": {
18
19
  "node": ">=20"
@@ -1 +0,0 @@
1
- import{r as p}from"./chunk-K3ZZ2VJH.js";import{spawn as h}from"node:child_process";var d=t=>/^https:\/\/[\w.-]+\/device(\?[\w=&-]*)?$/.test(t);function I(t){if(!d(t))return;let n=(f,m,l,c)=>{try{let s=h(f,m,{stdio:"ignore",detached:!0,...l});s.on("error",()=>c?.()),s.unref()}catch{c?.()}},{file:i,args:u,options:a}=p(t);n(i,u,a,process.platform==="linux"&&i==="cmd.exe"?()=>n("xdg-open",[t],{}):void 0)}import{chmodSync as g,existsSync as x,mkdirSync as y,readFileSync as A,rmSync as S,writeFileSync as v}from"node:fs";import{homedir as k}from"node:os";import{join as e}from"node:path";var w="https://flintmaker.com",r=()=>e(process.env.XDG_CONFIG_HOME||e(k(),".config"),"flintmaker"),o=(t=r())=>e(t,"auth.json");function P(t=r()){try{let n=JSON.parse(A(o(t),"utf8"));return typeof n?.token=="string"?n:null}catch{return null}}function B(t,n=r()){y(n,{recursive:!0,mode:448}),v(o(n),JSON.stringify(t,null,2),{mode:384});try{g(o(n),384)}catch{}}function C(t=r()){x(o(t))&&S(o(t))}function E(t){return(process.env.FLINT_API||t?.api||w).replace(/\/$/,"")}export{I as a,P as b,B as c,C as d,E as e};
@@ -1,6 +0,0 @@
1
- var u=Object.create;var l=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var w=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty;var R=(e,r)=>()=>{try{return r||e((r={exports:{}}).exports,r),r.exports}catch(t){throw r=0,t}};var g=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of m(r))!h.call(e,n)&&n!==t&&l(e,n,{get:()=>r[n],enumerable:!(o=d(r,n))||o.enumerable});return e};var T=(e,r,t)=>(t=e!=null?u(w(e)):{},g(r||!e||!e.__esModule?l(t,"default",{value:e,enumerable:!0}):t,e));import{spawn as S}from"node:child_process";import{release as x}from"node:os";import p from"node:path";var s=(e=process.platform)=>e==="win32",c=(e=process.platform)=>s(e)?p.win32:p.posix;function M(e,r=process.platform){if(c(r).isAbsolute(e))return`${e} is outside the project`;if(s(r)){if(/^[a-zA-Z]:/.test(e)||/^[\\/]/.test(e))return`${e} is outside the project`;if(e.includes(":"))return`${e} is not a valid path on Windows`}return null}function b(e,r,t=process.platform){let o=c(t),n=o.normalize(e),i=o.normalize(r);return s(t)&&(n=n.toLowerCase(),i=i.toLowerCase()),n.endsWith(o.sep)&&(n=n.slice(0,-1)),i===n||i.startsWith(n+o.sep)}function O(e,r=process.platform){return s(r)?e.replace(/[. ]+$/,""):e}function W(e,r=process.platform){return s(r)?e.replace(/\\/g,"/"):e}function $(e){let r=(e.match(/\n/g)??[]).length;return r===0?"lf":(e.match(/\r\n/g)??[]).length===r?"crlf":"lf"}var P=e=>e.replace(/\r\n/g,`
2
- `),k=e=>P(e).replace(/\n/g,`\r
3
- `);function a(e=process.platform,r=process.env){if(!s(e))return"sh";let t=(r.FLINT_SHELL??"").trim().toLowerCase();return t==="powershell"||t==="powershell.exe"?"powershell":t==="pwsh"||t==="pwsh.exe"?"pwsh":"cmd"}function v(e,r=process.platform,t=process.env){let o=a(r,t);if(o==="sh")return{file:"/bin/sh",args:["-c",e],options:{detached:!0}};if(o==="cmd")return{file:t.ComSpec||t.COMSPEC||"cmd.exe",args:["/d","/s","/c",`"${e}"`],options:{windowsVerbatimArguments:!0,windowsHide:!0}};let n=Buffer.from(e,"utf16le").toString("base64");return{file:o==="pwsh"?"pwsh.exe":"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",n],options:{windowsHide:!0}}}function J(e,r=process.platform,t){if(!e)return t?.();if(s(r)){try{S("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0}).on("error",()=>t?.())}catch{t?.()}return}try{process.kill(-e,"SIGKILL")}catch{t?.()}}var E={sh:"/bin/sh",cmd:"cmd.exe (Windows Command Prompt)",powershell:"Windows PowerShell (powershell.exe)",pwsh:"PowerShell 7 (pwsh.exe)"};function N(e=process.platform,r=process.env){return e==="win32"?"Windows":e==="darwin"?"macOS":e==="linux"?r.WSL_DISTRO_NAME?`Linux (WSL, ${r.WSL_DISTRO_NAME})`:"Linux":e}function F(e=process.platform,r=process.env){let t=a(e,r),o=[`OS: ${N(e,r)}`,`run_command shell: ${E[t]}`];return t==="cmd"?o.push("Use Windows cmd syntax: dir, type, copy, move, del, mkdir, findstr, set VAR=x, && to chain. No ls/cat/grep/rm/export, no single-quote quoting."):t!=="sh"&&o.push("Use PowerShell syntax (Get-ChildItem, Get-Content, $env:VAR, ; to chain)."),s(e)&&o.push("File tool paths are project-relative; forward slashes are fine."),`<environment>
4
- ${o.join(`
5
- `)}
6
- </environment>`}function U(e=process.platform,r=process.env){return r.FLINT_ASCII&&r.FLINT_ASCII!=="0"?!1:r.FLINT_UNICODE&&r.FLINT_UNICODE!=="0"?!0:s(e)?!!r.WT_SESSION||!!r.TERMINUS_SUBLIME||r.ConEmuTask==="{cmd::Cmder}"||r.TERM_PROGRAM==="vscode"||r.TERM_PROGRAM==="Terminus-Sublime"||r.TERMINAL_EMULATOR==="JetBrains-JediTerm"||r.TERM==="xterm-256color"||r.TERM==="alacritty"||r.TERM==="rxvt-unicode"||r.TERM==="rxvt-unicode-256color":r.TERM!=="linux"}var f={"\u2726":"*","\u25CF":"*","\u23BF":"`","\u276F":">","\u270E":">","\u23F5":">","\u23F8":"|","\u2387":"@","\u23CE":"/","\u2713":"v","\u2717":"x","\u2722":"*","\u2733":"*","\u2736":"*","\u273B":"*","\u273D":"*","\u259F":"/","\u2599":"\\","\u2588":"#","\u256D":"+","\u256E":"+","\u2570":"+","\u256F":"+","\u250C":"+","\u2510":"+","\u2514":"+","\u2518":"+","\u251C":"+","\u2524":"+","\u252C":"+","\u2534":"+","\u253C":"+","\u2500":"-","\u2502":"|","\u2191":"^","\u2193":"v","\u2192":">","\u2190":"<","\u2026":".","\u2248":"~","\u2013":"-","\u2014":"-","\u25B8":">","\u258C":"|","\u258E":"|","\u2022":"*","\u23F9":"#","\u2714":"v","\u2610":"o","\u2506":":","\u22EE":":","\xD7":"x"},I=new RegExp(`[${Object.keys(f).join("").replace(/[\\\]^-]/g,"\\$&")}]`,"g"),L=e=>e.replace(I,r=>f[r]??r);function j(e){let r=e.write.bind(e);e.write=((t,...o)=>r(typeof t=="string"?L(t):t,...o))}function B(e=process.platform,r=x()){if(!s(e))return 0;let t=r.split(".");return Number(t[0])>=10&&Number(t[2])||0}function G(e,r=process.platform,t=process.env){return r==="darwin"?{file:"open",args:[e],options:{}}:s(r)?{file:t.ComSpec||"cmd.exe",args:["/d","/s","/c",`start "" "${e}"`],options:{windowsVerbatimArguments:!0,windowsHide:!0}}:t.WSL_DISTRO_NAME?{file:"cmd.exe",args:["/d","/c","start",'""',e.replace(/&/g,"^&")],options:{}}:{file:"xdg-open",args:[e],options:{}}}export{R as a,T as b,s as c,c as d,M as e,b as f,O as g,W as h,$ as i,P as j,k,v as l,J as m,F as n,U as o,j as p,B as q,G as r};
@@ -1,23 +0,0 @@
1
- import{c as b,n as R}from"./chunk-K3ZZ2VJH.js";var S="Interrupted by the user before this finished.",f=class extends Error{},F={list_files:e=>String(e.path??"."),read_file:e=>`${e.path}${e.start_line?`:${e.start_line}-${e.end_line??""}`:""}`,search:e=>`/${e.pattern}/ ${e.path??""}`.trim(),write_file:e=>String(e.path),edit_file:e=>String(e.path),run_command:e=>String(e.command),web_search:e=>`"${e.query??""}"`,web_fetch:e=>String(e.url??"").replace(/^https?:\/\//,"").replace(/\/$/,"")},T=(e,n)=>typeof e=="object"?e.declined:n;async function W(e,n,t,r,i){switch(n){case"list_files":return e.listFiles(typeof t.path=="string"?t.path:".");case"read_file":return e.readFile(String(t.path),$(t.start_line),$(t.end_line));case"search":return e.search(String(t.pattern??""),typeof t.path=="string"?t.path:".");case"write_file":case"edit_file":{let s=await e.plan(n,t),o=await r.approveChange(s);return o!==!0?T(o,"The user declined this change. Ask what they want instead, or try a different approach."):i?.aborted?S:(await s.apply(),`${s.created?"Created":"Updated"} ${s.path}.`)}case"run_command":{let s=String(t.command??"").trim();if(!s)throw new Error("command is required");let o=await r.approveCommand(s);return o!==!0?T(o,"The user declined to run this command."):i?.aborted?S:e.runCommand(s,void 0,i)}default:throw new Error(`unknown tool ${n}`)}}var $=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0;function q(e){let n=structuredClone(e),t=n.map((r,i)=>({m:r,i})).filter(r=>r.m.role==="tool"&&(r.m.content?.length??0)>400);for(let{m:r}of t.slice(0,Math.max(1,Math.ceil(t.length/2))))r.role==="tool"&&(r.content=`${r.content.slice(0,300)}
2
- [output trimmed to save context; read again if needed]`);return t.length===0&&n.length>4&&n.splice(1,2),n}async function te(e,n,t,r,i={}){let s=[...n],o=i.signal;try{for(let l=0;l<(i.maxSteps??25);l++){if(o?.aborted)return s;let c=null,m="",w=a=>{m+=a,r.onDelta(a)};for(let a=0;a<4&&!c;a++)try{m="",c=await t(s,w)}catch(g){if(o?.aborted)return m&&s.push({role:"assistant",content:m}),s;if(!(g instanceof f))throw g;s=q(s)}if(!c)throw new Error("This conversation is too long. Start a new one with /clear.");if(c.toolCalls.length===0)return s.push({role:"assistant",content:c.text}),s;s.push({role:"assistant",content:c.text||null,tool_calls:c.toolCalls.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:a.arguments}}))});for(let a of c.toolCalls){if(o?.aborted){s.push({role:"tool",tool_call_id:a.id,content:S});continue}let g={};try{g=JSON.parse(a.arguments||"{}")}catch{}r.onToolStart(a.name,(F[a.name]??(()=>""))(g),g);let d,u=c.serverResults?.[a.id];if(u){d=u.content,r.onToolResult(a.name,u.ok,u.ok?d:d.replace(/^Error: /,"")),s.push({role:"tool",tool_call_id:a.id,content:d});continue}try{d=await W(e,a.name,g,r,o),r.onToolResult(a.name,!0,d)}catch(E){d=`Error: ${E.message}`,r.onToolResult(a.name,!1,E.message)}s.push({role:"tool",tool_call_id:a.id,content:d})}}}catch(l){throw l&&typeof l=="object"&&Object.assign(l,{partial:s}),l}return s.push({role:"assistant",content:"I stopped after many steps. Tell me how to continue."}),s}function C(){let e="";return n=>{e+=n;let t=e.split(`
3
-
4
- `);return e=t.pop()??"",t.filter(Boolean).map(r=>{let i="message",s=[];for(let o of r.split(`
5
- `))o.startsWith("event:")?i=o.slice(6).trim():o.startsWith("data:")&&s.push(o.slice(5).replace(/^ /,""));return{event:i,data:s.join(`
6
- `)}})}}var N="0.2.6",p=class extends Error{constructor(t,r="error",i=0,s){super(t);this.reason=r;this.status=i;this.minVersion=s}reason;status;minVersion},V=e=>e?new Date(e).toLocaleString(void 0,{weekday:"short",hour:"2-digit",minute:"2-digit"}):"soon";async function M(e,n){let t=await e.json().catch(()=>({})),r=t.requestId?` (ref ${t.requestId})`:"";switch(t.reason){case"signed_out":return new p("You are signed out. Run: flint login","signed_out",e.status);case"limit":return new p(`Out of credits until ${V(t.resetAt)}. Get more at ${n}/pricing`,"limit",e.status);case"busy":return new p("FlintMaker is very busy right now. Please try again later.","busy",e.status);case"upgrade_required":return new p(`The smart model needs a paid plan: ${n}/pricing`,"upgrade_required",e.status);case"in_progress":return new p("Another flint session is still working. Wait for it to finish.","in_progress",e.status);case"update_required":{let i=typeof t.minVersion=="string"&&/^\d+\.\d+\.\d+/.test(t.minVersion)?t.minVersion:void 0;return new p(`FlintMaker needs flint v${i??"latest"} or newer (this is v${N}).`,"update_required",e.status,i)}default:return new p(`Request failed (${e.status} ${t.reason??""})${r}`,t.reason??"error",e.status)}}var A=class{constructor(n,t){this.base=n;this.token=t}base;token;headers(){return{"content-type":"application/json","user-agent":"flint-cli","x-flint-version":N,...this.token?{authorization:`Bearer ${this.token}`}:{}}}async json(n,t={}){let r=await fetch(`${this.base}/api${n}`,{...t,headers:{...this.headers(),...t.headers}});if(!r.ok)throw await M(r,this.base);return await r.json()}me(){return this.json("/me")}async deviceLogin(n,t){let r=await this.json("/auth/device",{method:"POST",body:"{}"});n(r.userCode,r.verifyUrl);let i=Date.now()+r.expiresIn*1e3;for(;Date.now()<i;){if(await new Promise(o=>setTimeout(o,r.interval*1e3)),t?.aborted)throw new p("Login cancelled.","cancelled");let s=await fetch(`${this.base}/api/auth/device/token`,{method:"POST",headers:this.headers(),body:JSON.stringify({deviceCode:r.deviceCode})});if(s.status!==428){if(s.ok)return await s.json();throw new p("The login code expired. Run flint login again.","expired",s.status)}}throw new p("The login code expired. Run flint login again.","expired")}stepper(n,t,r){return async(i,s)=>{let o=await fetch(`${this.base}/api/agent`,{method:"POST",headers:{...this.headers(),"x-flint-features":"web"},body:JSON.stringify({messages:i,model:n()}),signal:t()});if(o.status===413)throw new f;if(!o.ok||!o.body)throw await M(o,this.base);let l=C(),c=new TextDecoder,m="",w=[],a={};for await(let g of o.body)for(let d of l(c.decode(g,{stream:!0}))){let u=d.data?JSON.parse(d.data):{};if(d.event==="delta")m+=u.text,s(u.text);else if(d.event==="tool_call")w.push(u);else if(d.event==="tool_result")a[u.id]={ok:u.ok!==!1,content:String(u.content??"")};else if(d.event==="done")r(u.credits,u.usage);else if(d.event==="error")throw new p(`The model hit a problem; no credits were used.${u.requestId?` (ref ${u.requestId})`:""}`,"model")}return{text:m,toolCalls:w,serverResults:a}}}};var I="https://flintmaker.com/pricing";function B(e){let n=e;return n?.name==="TypeError"&&/fetch failed|network/i.test(n.message??"")||["ECONNREFUSED","ENOTFOUND","ECONNRESET","ETIMEDOUT","EAI_AGAIN","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(n?.cause?.code??"")}function le(e,n={}){let t=n.interactive?"Run /login to connect your FlintMaker account.":"Run: flint login",r=n.retry?[n.retry]:[];if(B(e))return{title:"Can't reach FlintMaker",lines:["Check your internet connection, then try again.",...r],tone:"warn"};if(e instanceof p)switch(e.reason){case"signed_out":return{title:"You are signed out",lines:[t],tone:"warn"};case"limit":return{title:"Out of credits",lines:[e.message.replace(/\. Get more at .*$/,"."),`Upgrade or top up: ${I}`],tone:"warn"};case"upgrade_required":return{title:"Smart needs a paid plan",lines:["Switch back with /model standard, or upgrade:",I],tone:"warn"};case"busy":return{title:"FlintMaker is very busy",lines:["Please try again in a minute.",...r],tone:"warn"};case"in_progress":return{title:"Another flint session is working",lines:["Wait for it to finish, then try again."],tone:"warn"};case"update_required":return{title:"flint needs an update",lines:[e.message,n.interactive?"Updating\u2026 if it does not restart, run: flint update":"Run: flint update (or: npm i -g flintmaker@latest)"],tone:"warn"};case"model":return{title:"The model hit a problem",lines:[e.message,...r],tone:"error"};default:return{title:"Something went wrong",lines:[e.message,...r],tone:"error"}}return{title:"Something went wrong",lines:[e?.message??String(e)],tone:"error"}}var _=null,P=[];function de(e){_?_(e):P.push(e)}function ue(e){if(_=e,e)for(let n of P.splice(0))e(n)}var L=null,k=null;function pe(e){k=e,L?.(e)}function me(e){L=e,e&&k&&e(k)}import{readdirSync as z}from"node:fs";import{join as G,sep as J}from"node:path";var y=[{name:"help",description:"Show commands and keyboard shortcuts"},{name:"model",args:"[standard|smart]",description:"Switch model and see credit costs"},{name:"mode",args:"[ask|auto|plan]",description:"Change when flint asks before acting (or Shift+Tab)"},{name:"clear",description:"Start a new conversation",aliases:["new","reset"]},{name:"compact",description:"Summarise the conversation to free up context"},{name:"credits",description:"Show credit usage and plans",aliases:["usage"]},{name:"init",description:"Create FLINT.md, the project memory flint reads first"},{name:"update",description:"Update flint to the newest version now"},{name:"login",description:"Connect another FlintMaker account"},{name:"logout",description:"Disconnect this computer"},{name:"exit",description:"Quit flint",aliases:["quit","q"]}];function we(e){let n=/^\/([a-zA-Z][\w-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!n)return null;let t=n[1].toLowerCase(),r=y.find(i=>i.name===t||i.aliases?.includes(t));return!r&&(t==="smart"||t==="standard")?{name:"model",args:t,command:y.find(i=>i.name==="model")}:{name:r?.name??t,args:(n[2]??"").trim(),command:r}}function Y(e,n){let t=Array.from({length:n.length+1},(r,i)=>i);for(let r=1;r<=e.length;r++){let i=t[0];t[0]=r;for(let s=1;s<=n.length;s++){let o=t[s];t[s]=Math.min(t[s]+1,t[s-1]+1,i+(e[r-1]===n[s-1]?0:1)),i=o}}return t[n.length]}function ye(e){let n=null,t=1/0;for(let r of y)for(let i of[r.name,...r.aliases??[]]){let s=i.startsWith(e)?0:Y(e,i);s<t&&(t=s,n=r.name)}return t<=Math.max(2,Math.floor(e.length/3))?n:null}function xe(e){let n=e.replace(/^\//,"").toLowerCase();return y.filter(t=>t.name.startsWith(n)||t.aliases?.some(r=>r.startsWith(n)))}function be(e){if(e.length===0)return"";let n=e[0];for(let t of e.slice(1))for(;!t.startsWith(n);)n=n.slice(0,-1);return n}var K=new Set(["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__","DerivedData","Pods"]);function Se(e,n){let t=n.lastIndexOf("/"),r=t>=0?n.slice(0,t+1):"",i=t>=0?n.slice(t+1):n;if(r.split("/").includes("..")||r.startsWith("/"))return[];let s;try{s=z(G(e,r.split("/").join(J)),{withFileTypes:!0})}catch{return[]}return s.filter(o=>o.name.startsWith(i)&&!K.has(o.name)&&(i.startsWith(".")||!o.name.startsWith(".")||o.name===".github")).map(o=>r+o.name+(o.isDirectory()?"/":"")).sort((o,l)=>Number(l.endsWith("/"))-Number(o.endsWith("/"))||o.localeCompare(l)).slice(0,50)}function O(e){let n=new Set;for(let t of e.matchAll(/(?:^|\s)@((?:[\w.-]+\/)*[\w.-]+)/g))n.add(t[1]);return[...n]}import{readFileSync as j,statSync as H}from"node:fs";import{join as Q}from"node:path";var x="FLINT.md",D=2e4,h=e=>e.toLocaleString("en-US");function Te(e){return e.creditsLeftToday!==null?`${h(e.creditsLeftToday)} credits left today`:`${h(e.creditsLeftMonth)} credits left`}function $e(e){let n=r=>new Date(r).toLocaleString(void 0,{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}),t=[`Plan: ${e.plan.charAt(0).toUpperCase()+e.plan.slice(1)}`];return e.creditsLeftToday!==null&&t.push(`Today: ${h(e.creditsLeftToday)} credits left (resets ${n(e.resetAt)})`),t.push(`This period: ${h(e.creditsLeftMonth)} of ${h(e.monthlyCredits)} credits left (resets ${n(e.monthResetAt)})`),t}var Ce={standard:{label:"Standard",cost:"\u22482\u20133 credits per step",note:"fast, great for most tasks \xB7 all plans"},smart:{label:"Smart",cost:"\u22482\u20138 credits per step",note:"stronger reasoning, longer answers \xB7 paid plans"}},Me=`Create ${x} in the project root: a concise project memory that you will read at the start of every future conversation.
7
- First explore the project (list files, read the README, package/config files and a few key sources). Then write ${x} (max ~60 lines) with:
8
- - What the project is, in 1\u20132 sentences
9
- - Tech stack and layout (key directories and entry points)
10
- - How to install, build, run, test and lint (exact commands)
11
- - Code style and conventions worth following
12
- - Anything surprising (gotchas, generated files, things not to touch)
13
- Do not include secrets. Keep it factual and short.`,Ae=`Summarise our conversation so far so we can continue in a fresh context. Do not call any tools.
14
- Include: the goal, decisions made, files changed (with what changed), commands run and their outcomes, open problems and next steps.
15
- Be concise but keep exact file paths, names and error messages.`,X="[Plan mode is on: do not change files or run commands. Explore with read-only tools (list_files, read_file, search) and reply with a clear, numbered plan. The user will switch modes to let you carry it out.]";function Z(e){let n=Q(e,x);try{return H(n).size>D?j(n,"utf8").slice(0,D)+`
16
- [truncated]`:j(n,"utf8")}catch{return null}}async function Ne(e,n,t){let r=[],i=[],s=!1;if(t.first){i.push(R());let o=Z(e.root);o&&(s=!0,i.push(`<project-memory file="${x}">
17
- ${o.trim()}
18
- </project-memory>`))}t.mode==="plan"&&i.push(X),i.push(n);for(let o of O(n))try{let l=await e.readFile(o),c=l.split(`
19
- `).filter(m=>/^\d+\t/.test(m)).length;r.push({path:o,lines:c}),i.push(`<file path="${o}">
20
- ${l}
21
- </file>`)}catch(l){let c=l.message;r.push({path:o,error:/ENOENT|no such file/.test(c)?"not found":c.replace(`${o} `,"")})}return{content:i.join(`
22
-
23
- `),attachments:r,memory:s}}var v=new Set(["rm","rmdir","sudo","su","doas","dd","mkfs","shred","curl","wget","ssh","scp","sh","bash","zsh","fish","eval","exec","xargs","env","chmod","chown","kill","killall","git push"]),ee=new Set(["del","erase","rd","rmdir","format","cmd","powershell","pwsh","start","reg","regedit","taskkill","runas","icacls","takeown","attrib","cipher","diskpart","bcdedit","schtasks","sc","net","netsh","wsl","certutil","bitsadmin","mshta","rundll32","wscript","cscript","remove-item","invoke-expression","iex","invoke-webrequest","iwr","curl.exe","move","ren","rename","copy","xcopy","robocopy","mklink","setx","stop-process"]),U=new Set(["node","py","python","python3","ruby","perl","php","deno","bun","npx","pnpx","bunx"]);function Ie(e,n=process.platform){let t=e.trim();if(!t||/[;&|<>`$(){}\n\r\\*?!~#'"]/.test(t)||b(n)&&/[%^]/.test(t))return null;let[r,i]=t.split(/\s+/),s=b(n),o=s?r.split("/").pop().toLowerCase().replace(/\.(exe|cmd|bat|com|ps1)$/,""):r.split("/").pop();if(v.has(o)||s&&ee.has(o))return null;let l=i&&/^[a-z][\w:-]*$/i.test(i)?`${r} ${i}`:r;return v.has(l)||s&&v.has(`${o} ${i?.toLowerCase()}`)||U.has(o)&&l===r||U.has(o)&&["npx","pnpx","bunx"].includes(o)?null:l}export{S as a,f as b,q as c,te as d,N as e,p as f,A as g,I as h,le as i,de as j,ue as k,pe as l,me as m,y as n,we as o,ye as p,xe as q,be as r,Se as s,x as t,h as u,Te as v,$e as w,Ce as x,Me as y,Ae as z,Ne as A,Ie as B};
@@ -1,9 +0,0 @@
1
- import{a as M,b as s,c as S}from"./chunk-5PRYZOW7.js";var I=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,L=t=>t.replace(I,"");function N(t){return t===0||t<32||t>=127&&t<160||t>=768&&t<=879||t>=8203&&t<=8207||t>=65024&&t<=65039||t>=6832&&t<=6911||t>=8400&&t<=8447||t>=917760&&t<=917999?0:t>=4352&&t<=4447||t>=11904&&t<=12350||t>=12353&&t<=13311||t>=13312&&t<=19903||t>=19968&&t<=40959||t>=40960&&t<=42191||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65072&&t<=65103||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=127744&&t<=128591||t>=129280&&t<=129535||t>=128640&&t<=128767||t>=129648&&t<=129791||t>=131072&&t<=262141?2:1}function x(t){let r=0;for(let e of L(t))r+=N(e.codePointAt(0));return r}function*O(t){let r=0;for(let e of t.matchAll(I)){for(let n of t.slice(r,e.index))yield{ansi:!1,text:n};yield{ansi:!0,text:e[0]},r=e.index+e[0].length}for(let e of t.slice(r))yield{ansi:!1,text:e}}function m(t,r,e="\u2026"){if(r<=0)return"";if(x(t)<=r)return t;let n=r-x(e),i=0,o="",l=!1;for(let a of O(t)){if(a.ansi){o+=a.text;continue}if(l)continue;let c=N(a.text.codePointAt(0));if(i+c>n){o+=e,l=!0;continue}o+=a.text,i+=c}return o+(/\x1b\[/.test(o)?"\x1B[0m":"")}var R=(t,r)=>t+" ".repeat(Math.max(0,r-x(t)));function H(t,r){let e=[],n="",i=0;for(let o of t){let l=N(o.codePointAt(0));i+l>r&&n!==""&&(e.push(n),n="",i=0),n+=o,i+=l}return e.push(n),e}function P(t,r,e=""){let n=[];for(let i of t.split(`
2
- `)){let o=[],l="",a=0,c=[],f="",h=0,d="",b=()=>c.join(""),p=()=>{o.push(l+(c.length?"\x1B[0m":"")),l=e+b(),a=x(e)},$=()=>{if(f){a+x(d)+h>r&&a>x(e)&&(p(),d=""),l+=d+f,a+=x(d)+h,d="";for(let u of f.matchAll(/\x1b\[[0-9;]*m/g))/^\x1b\[0?m$/.test(u[0])?c=[]:c.push(u[0]);for(;a>r;){let u=L(l),g=H(u,r)[0];o.push(g),l=e+u.slice(g.length),a=x(l)}f="",h=0}};for(let u of O(i)){if(u.ansi){f+=u.text;continue}if(u.text===" "){$(),d+=" ";continue}f+=u.text,h+=N(u.text.codePointAt(0))}$(),o.push(l),n.push(...o)}return n}function v(t){return t.replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)?/g,"").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,"").replace(/\x1b[@-Z\\-_]/g,"").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,"").replace(/[‪-‮⁦-⁩]/g,r=>`<U+${r.charCodeAt(0).toString(16).toUpperCase()}>`)}var B={ask:"ask before edits",auto:"auto-accept edits",plan:"plan only (no changes)"},T={standard:"Standard",smart:"Smart"};function U(t,r,e={}){let n=e.border??s.grey,i=e.padX??1,o=Math.max(4,r-2-i*2),l=e.title?n("\u256D\u2500 ")+e.title+" "+n("\u2500".repeat(Math.max(0,r-5-x(e.title)))+"\u256E"):n("\u256D"+"\u2500".repeat(r-2)+"\u256E"),a=" ".repeat(i);return[l,...t.map(c=>n("\u2502")+a+R(m(c,o),o)+a+n("\u2502")),n("\u2570"+"\u2500".repeat(r-2)+"\u256F")]}var W=[" \u2726 "," \u259F\u2588\u2599 ","\u259F\u2588\u2588\u2588\u2599"];function lt(t,r){let e=Math.min(r-1,76),n=M()===0?W:[s.gold(W[0]),S(W[1],[[255,194,74],[255,122,61]]),S(W[2],[[255,122,61],[232,51,107]])],i=`${s.bold(S("FlintMaker"))} ${s.bold("flint")} ${s.grey(`v${t.version}`)}`,o=t.email?`${t.email}${t.plan?s.grey(" \xB7 ")+Z(t.plan):""}${t.credits?s.grey(" \xB7 ")+t.credits:""}`:s.grey(t.status??"connecting\u2026"),l=[i,o,`${s.grey("model")} ${T[t.model]}${s.grey(" \xB7 ")}${s.grey(t.cwd)}`],a=W.map((c,f)=>`${n[f]} ${l[f]}`);return a.push("",s.grey("/help commands \xB7 @ attach files \xB7 esc interrupt \xB7 shift+tab mode")),t.updated&&a.push(`${s.ember("\u2726")} ${s.bold(`Updated to v${t.updated}`)}`),U(a,e,{border:c=>s.ember(c)})}var Z=t=>t.charAt(0).toUpperCase()+t.slice(1),j=["Forging","Sparking","Kindling","Stoking","Smelting","Hammering","Tempering","Igniting","Annealing","Striking","Blazing","Quenching"],F=["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D","\u273B","\u2736","\u2733","\u2722"];function at(t,r,e,n,i){let o=i??j[Math.floor(r/3e3)%j.length],l=F[t%F.length],c=[`${Math.floor(r/1e3)}s`,e?`${e} credit${e===1?"":"s"}`:null,"esc to interrupt"].filter(Boolean).join(" \xB7 ");return m(`${s.ember(l)} ${S(`${o}\u2026`,[[255,122,61],[255,194,74]])} ${s.grey(`(${c})`)}`,n-1)}function ct(t,r){let e=t.mode==="ask"?s.grey(B.ask):t.mode==="auto"?s.gold(`\u23F5\u23F5 ${B.auto}`):s.pink(`\u23F8 ${B.plan}`),n=[s.ember(T[t.model]),...t.note?[s.dim(t.note)]:[],e+s.grey(" (shift+tab)")];t.credits&&n.push(s.grey(t.credits)),n.push(s.grey(t.cwd)+(t.branch?s.grey(` \u2387 ${t.branch}`):""));let i=" "+(t.hint?s.gold(t.hint):n.join(s.grey(" \xB7 ")));return m(i,r-1)}var q={list_files:"List",read_file:"Read",search:"Search",write_file:"Write",edit_file:"Edit",run_command:"Run",web_search:"Web search",web_fetch:"Fetch"};function G(t){return q[t]??t.replace(/_/g," ")}function gt(t,r,e,n,i=""){let o=e==="running"?s.gold("\u25CF"):e==="ok"?s.ember("\u25CF"):e==="error"?s.red("\u25CF"):s.grey("\u25CF"),l=v(r).replace(/\s*\n\s*/g," \u23CE ");return m(`${o} ${s.bold(G(t))} ${l}${i?s.grey(` ${i}`):""}`,n-1)}function ft(t,r,e=4,n=s.grey){let i=v(t).replace(/\s+$/,"").split(`
3
- `),l=i.slice(0,e).map((a,c)=>m(` ${c===0?s.grey("\u23BF"):" "} ${n(a.replace(/\t/g," "))}`,r-1));return i.length>e&&l.push(s.grey(` \u2026 +${i.length-e} lines`)),l}function ut(t,r){switch(t){case"read_file":{if(r.startsWith("[binary file"))return{suffix:"(binary)"};let e=r.split(`
4
- `).filter(n=>/^\d+\t/.test(n)).length;return{suffix:`(${e} line${e===1?"":"s"})`}}case"list_files":{let e=/… (\d+) more files/.exec(r),n=r==="(empty)"?0:r.split(`
5
- `).filter(i=>i&&!i.startsWith("\u2026 ")).length+(e?Number(e[1]):0);return{detail:`${n} file${n===1?"":"s"}`}}case"search":{if(r==="No matches.")return{detail:"No matches"};let e=r.split(`
6
- `).filter(Boolean),n=new Set(e.map(i=>i.split(":")[0]));return{detail:`${e.length} match${e.length===1?"":"es"} in ${n.size} file${n.size===1?"":"s"}`}}case"run_command":{let e=/\[exit code (\d+|null)\]$|\[timed out after \d+s\]$|^\[could not run command/.exec(r.trim());return{failed:!e||(e[1]!==void 0?e[1]!=="0":!0)}}case"web_search":{let e=r.split(`
7
- `),n=e.flatMap((o,l)=>/^\[\d+\] /.test(o)?[Q(e[l+1]??"")]:[]).filter(Boolean);if(n.length===0)return{detail:"No results"};let i=[...new Set(n)];return{detail:`${n.length} result${n.length===1?"":"s"}: ${i.slice(0,3).join(", ")}${i.length>3?"\u2026":""}`}}case"web_fetch":{let e=/^Words: (\d+)( \(truncated\))?/m.exec(r);return e?{detail:`${Number(e[1]).toLocaleString("en-US")} words${e[2]?" (truncated)":""}`}:{}}default:return{}}}function Q(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return""}}function J(t){let r=0,e=0;for(let n of t.split(`
8
- `))n.startsWith("+++")||n.startsWith("---")||(n.startsWith("+")?r++:n.startsWith("-")&&e++);return{added:r,removed:e}}function dt(t,r,e,n=!1){let i=v(t),{added:o,removed:l}=J(i),a=e-1,c=`${s.bold(r)} ${s.green(`+${o}`)} ${s.red(`-${l}`)}${n?s.grey(" (new file)"):""}`,f=[` ${s.grey("\u250C")} ${c}`],h=0,d=0,b=1;for(let g of i.matchAll(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm))b=Math.max(b,Number(g[1])+Number(g[2]??1),Number(g[3])+Number(g[4]??1));let p=String(b).length,$=[],u=!0;for(let g of i.split(`
9
- `)){if(g.startsWith("===")||g.startsWith("Index:")||g.startsWith("---")||g.startsWith("+++"))continue;let E=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(g);if(E){h=Number(E[1]),d=Number(E[2]),u||$.push(` ${s.grey("\u2506")} ${s.grey(" ".repeat(p)+" \u22EE")}`),u=!1;continue}if(g==="\")continue;let y=g[0],D=g.slice(1).replace(/\t/g," "),k,A,w;if(y==="+")k=String(d++),A="+",w=M()>=2?s.addBg:s.green;else if(y==="-")k=String(h++),A="-",w=M()>=2?s.delBg:s.red;else if(y===" ")k=String(d),h++,d++,A=" ",w=_=>_;else continue;let K=` ${s.grey("\u2502")} ${s.grey(k.padStart(p))} `,C=Math.max(10,a-(p+5)-2);Y(`${A} ${D}`,C).forEach((_,V)=>{let z=y===" "?s.grey(_):_,X=y===" "||M()<2?w(z):w(R(z,C));$.push((V===0?K:` ${s.grey("\u2502")} ${" ".repeat(p)} `)+X)})}return f.push(...$,` ${s.grey("\u2514")}`),f}function Y(t,r){let e=[],n=t;for(;x(n)>r;){let i=0,o=0;for(let l of n){let a=x(l);if(o+a>r)break;o+=a,i+=l.length}e.push(n.slice(0,i)),n=" "+n.slice(i)}return e.push(n),e}function xt(t,r,e,n="error"){let i=n==="error"?s.red:n==="warn"?s.gold:s.ember,o=n==="error"?"\u2717":n==="warn"?"!":"\u2726",l=Math.min(e-1,76),a=r.flatMap(c=>P(` ${c}`,l-4," "));return U([`${i(o)} ${s.bold(t)}`,...a],l,{border:i})}function ht(t,r,e,n,i="cancel"){let o=[m(s.bold(t),n-1)];return r.forEach((l,a)=>{let c=a===e,f=c?s.ember("\u276F"):" ",h=`${a+1}. ${l.label}`;o.push(m(`${f} ${c?s.ember(h):h}${l.hint?s.grey(` ${l.hint}`):""}`,n-1))}),o.push(s.grey(`\u2191/\u2193 or 1-${r.length} to choose \xB7 enter to confirm \xB7 esc to ${i}`)),o}function mt(t,r,e,n={}){let i=e-1,o=n.prefix??"\u276F ",l=tt(e,o),a=n.maxRows??8,c=0;t.length>a&&(c=Math.min(Math.max(0,r.row-a+1),t.length-a));let f=t.slice(c,c+a),h=t.length===1&&t[0]==="",d=[s.grey("\u256D"+"\u2500".repeat(i-2)+"\u256E")];f.forEach((p,$)=>{let u=$===0&&c===0?s.ember(o):" ".repeat(x(o)),g=h&&n.placeholder?s.grey(m(n.placeholder,l)):p;d.push(s.grey("\u2502")+" "+u+R(g,l)+" "+s.grey("\u2502"))});let b=t.length>a?`\u2500 ${c+f.length}/${t.length} lines `:"";return d.push(s.grey("\u2570"+b+"\u2500".repeat(Math.max(0,i-2-b.length))+"\u256F")),{lines:d,cursorRow:1+(r.row-c),cursorCol:2+x(o)+(h?0:r.col)}}var tt=(t,r="\u276F ")=>Math.max(8,t-1-4-x(r));function bt(t,r,e=32){/^[a-zA-Z]:[\\/]|^\\\\/.test(t)&&(t=t.replace(/\\/g,"/"),r=r.replace(/\\/g,"/"),r&&(t.toLowerCase()===r.toLowerCase()||t.toLowerCase().startsWith(r.toLowerCase()+"/"))&&(t=r+t.slice(r.length)));let n=r&&(t===r||t.startsWith(r+"/"))?`~${t.slice(r.length)}`:t;if(n.length<=e)return n;let i=n.split("/");for(;i.length>2&&i.join("/").length>e-2;)i.splice(1,1);return n=i.length>1?`${i[0]}/\u2026/${i.slice(1).join("/")}`:n,n.length>e?"\u2026"+n.slice(-(e-1)):n}var pt=t=>t.map(L);export{L as a,N as b,x as c,m as d,R as e,H as f,P as g,v as h,B as i,T as j,U as k,lt as l,j as m,F as n,at as o,ct as p,G as q,gt as r,ft as s,ut as t,J as u,dt as v,xt as w,ht as x,mt as y,tt as z,bt as A,pt as B};
@@ -1,5 +0,0 @@
1
- import{a as U,b as Y}from"./chunk-O4FFCD22.js";import{A as P,d as M,i as _,k as x,v as I}from"./chunk-K6EGUENI.js";import{h as m,r as u,s as p,t as L,v as S}from"./chunk-YCYJUZK6.js";import{b as o}from"./chunk-5PRYZOW7.js";import"./chunk-K3ZZ2VJH.js";import{createInterface as R}from"node:readline/promises";var r=(y="")=>process.stdout.write(y+`
2
- `);async function J(y,s){let a=!!process.stdout.isTTY,n=()=>a?Math.max(40,process.stdout.columns||80):100;a&&await import("./highlight-QJIBHZTN.js").then(e=>U(e.highlight)).catch(()=>{});let C=new Y(()=>n()-1),h=!!process.stdin.isTTY&&a?R({input:process.stdin,output:process.stdout,terminal:!0}):null;x(e=>{process.stderr.isTTY&&process.stderr.write(o.grey(`\u2726 ${e}`)+`
3
- `)});let l=new AbortController;process.on("SIGINT",()=>{l.signal.aborted&&process.exit(130),l.abort()});let A=null,d=0,f=!1,g=!1,$=()=>{a?C.end().forEach(e=>r(e)):f&&r(),f=!1},E=async e=>{if(s.autoYes)return!0;if(!h)return r(` ${e} no (not a terminal; pass --yes to allow)`),!1;let t=(await h.question(` ${e} ${o.grey("[y/N]")} `)).trim().toLowerCase();return t==="y"||t==="yes"},w="",j={onDelta:e=>{!f&&g&&r(),g=!1;let t=m(e);a?C.push(t).forEach(i=>r(i)):process.stdout.write(t),f=!0},onToolStart:(e,t)=>{$(),w=t,g=!0},onToolResult:(e,t,i="")=>{if(!t){r(u(e,w,"error",n())),p(i,n(),3).forEach(c=>r(c));return}if(e==="write_file"||e==="edit_file"||e==="run_command"){p(i,n(),e==="run_command"?8:2).forEach(c=>r(c));return}let k=L(e,i);r(u(e,w,"ok",n(),k.suffix)),k.detail&&p(k.detail,n()).forEach(c=>r(c))},approveChange:async e=>(r(u(e.created?"write_file":"edit_file",e.path,"ok",n())),S(e.diff,e.path,n(),e.created).forEach(t=>r(t)),s.mode==="plan"?{declined:"Plan mode is on, so no files may be changed."}:E(`${e.created?"Create":"Apply this edit to"} ${m(e.path)}?`)),approveCommand:async e=>(r(`${o.ember("\u25CF")} ${o.bold("Run")} ${m(e)}`),s.mode==="plan"?{declined:"Plan mode is on, so no commands may run."}:E("Run this command?"))},N=s.client.stepper(()=>s.model,()=>l.signal,(e,t)=>{d+=e,A=t}),b=0;try{let e=await P(s.ws,y,{first:!0,mode:s.mode??"ask"});for(let t of e.attachments)t.error&&r(o.gold(`! Could not attach ${t.path}: ${t.error}`));await M(s.ws,[{role:"user",content:e.content}],N,j,{signal:l.signal}),$(),l.signal.aborted&&(r(o.grey("Interrupted.")),b=130)}catch(e){$();let t=_(e);process.stderr.write(`${o.red("\u2717")} ${t.title}
4
- ${t.lines.map(i=>` ${i}
5
- `).join("")}`),b=1}finally{h?.close()}let T=A;return(d||T)&&r(o.grey(`${d} credit${d===1?"":"s"} used${T?` \xB7 ${I(T)}`:""}`)),b}export{J as oneShot};
@@ -1 +0,0 @@
1
- import{A as s,B as t,i as a,j as b,k as c,l as d,m as e,n as f,o as g,p as h,q as i,r as j,s as k,t as l,u as m,v as n,w as o,x as p,y as q,z as r}from"./chunk-YCYJUZK6.js";import"./chunk-5PRYZOW7.js";import"./chunk-K3ZZ2VJH.js";export{b as MODEL_LABEL,a as MODE_LABEL,f as SPARK_FRAMES,e as VERBS,c as box,m as diffStats,o as errorBox,h as footer,q as inputBox,r as inputWidth,p as menu,t as plain,n as renderDiff,k as resultLines,s as shortPath,g as spinnerLine,l as summarize,j as toolLine,i as toolVerb,d as welcome};