flintmaker 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -58,7 +58,7 @@ flint "add a dark mode toggle" # one task, then exit (plain output, fine for
58
58
 
59
59
  **Updates**
60
60
 
61
- flint checks for a new version in the background (at most once an hour) and installs it when it was installed with `npm i -g` or the FlintMaker installer (never with sudo); restart to use it. `flint update` updates right away. Turn it off with `FLINT_NO_UPDATE=1` (it is also off when `CI` is set).
61
+ An interactive `flint` checks for a new version when it starts (waiting at most 1.5 s) and, when it was installed with `npm i -g` or the FlintMaker installer (never with sudo), installs it and restarts itself on the new version right away. Offline, or when the install cannot be updated (npx, a project's node_modules, a root-owned global folder), it starts at once and tells you how to update. One-shot runs (`flint "task"`, pipes, CI) never wait: they update in the background for next time, and a long session shows "Update ready — restart flint" when a new version was installed meanwhile. `flint update` updates right away. Turn it off with `FLINT_NO_UPDATE=1` (it is also off when `CI` is set).
62
62
 
63
63
  Uses credits from your FlintMaker plan — see [pricing](https://flintmaker.com/pricing). Respects `NO_COLOR`.
64
64
 
@@ -1,4 +1,4 @@
1
- import{a as H,c as P,d as fe,e as de,g as xe}from"./chunk-HEEZNIZR.js";import{b as f}from"./chunk-5PRYZOW7.js";function ee(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var v=ee();function _e(r){v=r}var E={exec:()=>null};function I(r){let e=[];return t=>{let s=Math.max(0,Math.min(3,t-1)),n=e[s];return n||(n=r(s),e[s]=n),n}}function g(r,e=""){let t=typeof r=="string"?r:r.source,s={replace:(n,i)=>{let l=typeof i=="string"?i:i.source;return l=l.replace(y.caret,"$1"),t=t.replace(n,l),s},getRegex:()=>new RegExp(t,e)};return s}var je=((r="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+r)}catch{return!1}})(),y={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:r=>new RegExp(`^( {0,3}${r})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(r=>new RegExp(`^ {0,${r}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(r=>new RegExp(`^ {0,${r}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:I(r=>new RegExp(`^ {0,${r}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(r=>new RegExp(`^ {0,${r}}#`)),htmlBeginRegex:I(r=>new RegExp(`^ {0,${r}}(?:</?(?:${Q})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:I(r=>new RegExp(`^ {0,${r}}>`))},He=/^(?:[ \t]*(?:\n|$))+/,Ne=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Fe=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,M=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ge=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,te=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Pe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Le=g(Pe).replace(/bull/g,te).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Xe=g(Pe).replace(/bull/g,te).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),re=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Ue=/^[^\n]+/,ne=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,We=g(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ne).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Je=g(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,te).getRegex(),Q="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",se=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ke=g("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",se).replace("tag",Q).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ee=r=>g(re).replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",r).replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),Ve=Ee(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ye=Ee(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),et=g(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ye).getRegex(),ie={blockquote:et,code:Ne,def:We,fences:Fe,heading:Ge,hr:M,html:Ke,lheading:Le,list:Je,newline:He,paragraph:Ve,table:E,text:Ue},be=g("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),tt={...ie,lheading:Xe,table:be,paragraph:g(re).replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",be).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex()},rt={...ie,html:g(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",se).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:g(re).replace("hr",M).replace("heading",` *#{1,6} *[^
1
+ import{a as H,c as P,d as fe,e as de,g as xe}from"./chunk-B6N6RRG5.js";import{b as f}from"./chunk-5PRYZOW7.js";function ee(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var v=ee();function _e(r){v=r}var E={exec:()=>null};function I(r){let e=[];return t=>{let s=Math.max(0,Math.min(3,t-1)),n=e[s];return n||(n=r(s),e[s]=n),n}}function g(r,e=""){let t=typeof r=="string"?r:r.source,s={replace:(n,i)=>{let l=typeof i=="string"?i:i.source;return l=l.replace(y.caret,"$1"),t=t.replace(n,l),s},getRegex:()=>new RegExp(t,e)};return s}var je=((r="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+r)}catch{return!1}})(),y={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:r=>new RegExp(`^( {0,3}${r})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(r=>new RegExp(`^ {0,${r}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(r=>new RegExp(`^ {0,${r}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:I(r=>new RegExp(`^ {0,${r}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(r=>new RegExp(`^ {0,${r}}#`)),htmlBeginRegex:I(r=>new RegExp(`^ {0,${r}}(?:</?(?:${Q})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:I(r=>new RegExp(`^ {0,${r}}>`))},He=/^(?:[ \t]*(?:\n|$))+/,Ne=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Fe=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,M=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ge=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,te=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Pe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Le=g(Pe).replace(/bull/g,te).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Xe=g(Pe).replace(/bull/g,te).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),re=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Ue=/^[^\n]+/,ne=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,We=g(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ne).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Je=g(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,te).getRegex(),Q="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",se=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ke=g("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",se).replace("tag",Q).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ee=r=>g(re).replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",r).replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),Ve=Ee(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ye=Ee(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),et=g(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ye).getRegex(),ie={blockquote:et,code:Ne,def:We,fences:Fe,heading:Ge,hr:M,html:Ke,lheading:Le,list:Je,newline:He,paragraph:Ve,table:E,text:Ue},be=g("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),tt={...ie,lheading:Xe,table:be,paragraph:g(re).replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",be).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex()},rt={...ie,html:g(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",se).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:g(re).replace("hr",M).replace("heading",` *#{1,6} *[^
2
2
  ]`).replace("lheading",Le).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},nt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,st=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ce=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,it=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,T=/[\p{P}\p{S}]/u,B=/[\s\p{P}\p{S}]/u,j=/[^\s\p{P}\p{S}]/u,lt=g(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,B).getRegex(),at=/[\p{Pi}\p{Ps}"']/u,ve=/(?!~)[\p{P}\p{S}]/u,ot=/(?!~)[\s\p{P}\p{S}]/u,ct=/(?:[^\s\p{P}\p{S}]|~)/u,ht=g(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",je?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ie=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,pt=g(Ie,"u").replace(/punct/g,T).getRegex(),ut=g(Ie,"u").replace(/punct/g,ve).getRegex(),gt=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,kt=g(gt,"u").replace(/openQuote/g,at).replace(/punct/g,T).getRegex(),Be="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",ft=g(Be,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,B).replace(/punct/g,T).getRegex(),dt=g(Be,"gu").replace(/notPunctSpace/g,ct).replace(/punctSpace/g,ot).replace(/punct/g,ve).getRegex(),xt="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",bt=g(xt,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,B).replace(/punct/g,T).getRegex(),mt=g("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,B).replace(/punct/g,T).getRegex(),wt="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",yt=g(wt,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,B).replace(/punct/g,T).getRegex(),$t=g(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,T).getRegex(),St="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Rt=g(St,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,B).replace(/punct/g,T).getRegex(),Tt=g(/\\(punct)/,"gu").replace(/punct/g,T).getRegex(),At=g(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,T).getRegex(),zt=g(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),_t=g(se).replace("(?:-->|$)","-->").getRegex(),Pt=g("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",_t).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),qe=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,F=g(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",qe).getRegex(),Lt=g(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",F).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Et=g(/^!?\[(label)\]\[(ref)\]/).replace("label",F).replace("ref",ne).getRegex(),Ct=g(/^!?\[(ref)\](?:\[\])?/).replace("ref",ne).getRegex(),me=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,vt=g(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",qe).getRegex(),It=g("reflink|nolink(?!\\()","g").replace("reflink",g(/^!?\[(label)\]\[(ref)\]/).replace("label",vt).replace("ref",me).getRegex()).replace("nolink",g(/^!?\[(ref)\](?:\[\])?/).replace("ref",me).getRegex()).getRegex(),we=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Bt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,qt=g(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,Bt).getRegex(),le={_backpedal:E,anyPunctuation:Tt,anyPunctuationOutsideCode:At,autolink:zt,blockSkip:ht,br:Ce,code:st,del:E,delLDelim:E,delRDelim:E,emStrongLDelim:pt,emStrongRDelimAst:ft,emStrongRDelimUnd:mt,escape:nt,link:Lt,nolink:Ct,punctuation:lt,reflink:Et,reflinkSearch:It,tag:Pt,text:it,url:E},Zt={...le,emStrongLDelim:kt,emStrongRDelimAst:bt,emStrongRDelimUnd:yt,link:g(/^!?\[(label)\]\((.*?)\)/).replace("label",F).getRegex(),reflink:g(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",F).getRegex()},K={...le,emStrongRDelimAst:dt,emStrongLDelim:ut,delLDelim:$t,delRDelim:Rt,url:g(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",qt).replace("protocol",we).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:g(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace("protocol",we).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},Dt={...K,br:g(Ce).replace("{2,}","*").getRegex(),text:g(K.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},N={normal:ie,gfm:tt,pedantic:rt},D={normal:le,gfm:K,breaks:Dt,pedantic:Zt},Ot={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ye=r=>Ot[r];function $(r,e){if(e){if(y.escapeTest.test(r))return r.replace(y.escapeReplace,ye)}else if(y.escapeTestNoEncode.test(r))return r.replace(y.escapeReplaceNoEncode,ye);return r}function Mt(r){return y.numericCharacterReference.test(r)?r.replace(y.numericCharacterReferenceOrAmpersand,(e,t,s)=>{if(t===void 0&&s===void 0)return"&amp;";let n=t===void 0?Number.parseInt(s,16):Number.parseInt(t,10);return n===0||n>1114111||n>=55296&&n<=57343?"\uFFFD":n===38?"&amp;":String.fromCodePoint(n)}):r}function $e(r){try{r=encodeURI(r).replace(y.percentDecode,"%")}catch{return null}return r}function Se(r,e){let t=r.replace(y.findPipe,(i,l,a)=>{let h=!1,o=l;for(;--o>=0&&a[o]==="\\";)h=!h;return h?"|":" |"}),s=t.split(y.splitPipe),n=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),e)if(s.length>e)s.splice(e);else for(;s.length<e;)s.push("");for(;n<s.length;n++)s[n]=s[n].trim().replace(y.slashPipe,"|");return s}function z(r,e,t){let s=r.length;if(s===0)return"";let n=0;for(;n<s;){let i=r.charAt(s-n-1);if(i===e&&!t)n++;else if(i!==e&&t)n++;else break}return r.slice(0,s-n)}function Re(r){let e=r.split(`
3
3
  `),t=e.length-1;for(;t>=0&&y.blankLine.test(e[t]);)t--;return e.length-t<=2?r:e.slice(0,t+1).join(`
4
4
  `)}function G(r){return r.trim().toLowerCase().toUpperCase().toLowerCase()}function Te(r,e){if(r.indexOf(e[0])===-1&&r.indexOf(e[1])===-1)return-1;let t=0;for(let s=0;s<r.length;s++)if(r[s]==="\\")s++;else if(r[s]===e[0])t++;else if(r[s]===e[1]&&(t--,t<0))return s;return t>0?-2:-1}function J(r,e=0){let t=e,s="";for(let n of r)if(n===" "){let i=4-t%4;s+=" ".repeat(i),t+=i}else s+=n,t++;return s}function Ae(r,e,t,s,n){let i=e.href,l=e.title||null,a=r[1].replace(n.other.outputLinkReplace,"$1"),h=r[0].charAt(0)==="!",o=s.state.inLink,c=s.state.linkEmitted,p=s.state.inRawBlock;s.state.inLink=!0,s.state.linkEmitted=!1;let k=s.inlineTokens(a),u=s.state.linkEmitted;if(s.state.linkEmitted=c,s.state.inLink=o,!h){if(u){s.state.inRawBlock=p;return}s.state.linkEmitted=!0}return{type:h?"image":"link",raw:t,href:i,title:l,text:a,tokens:k}}function Qt(r,e,t){let s=r.match(t.other.indentCodeCompensation);if(s===null)return e;let n=s[1];return e.split(`
@@ -1,9 +1,9 @@
1
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 X(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 et(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(""),$=()=>{o.push(l+(c.length?"\x1B[0m":"")),l=e+b(),a=x(e)},p=()=>{if(f){a+x(d)+h>r&&a>x(e)&&($(),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=X(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===" "){p(),d+=" ";continue}f+=u.text,h+=N(u.text.codePointAt(0))}p(),o.push(l),n.push(...o)}return n}function E(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)"},F={standard:"Standard",smart:"Smart"};function T(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 ")+H(t.plan):""}${t.credits?s.grey(" \xB7 ")+t.credits:""}`:s.grey(t.status??"connecting\u2026"),l=[i,o,`${s.grey("model")} ${F[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(a,e,{border:c=>s.ember(c)})}var H=t=>t.charAt(0).toUpperCase()+t.slice(1),P=["Forging","Sparking","Kindling","Stoking","Smelting","Hammering","Tempering","Igniting","Annealing","Striking","Blazing","Quenching"],j=["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D","\u273B","\u2736","\u2733","\u2722"];function at(t,r,e,n,i){let o=i??P[Math.floor(r/3e3)%P.length],l=j[t%j.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(F[t.model]),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 Z={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 q(t){return Z[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=E(r).replace(/\s*\n\s*/g," \u23CE ");return m(`${o} ${s.bold(q(t))} ${l}${i?s.grey(` ${i}`):""}`,n-1)}function ft(t,r,e=4,n=s.grey){let i=E(t).replace(/\s+$/,"").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=X(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)"},F={standard:"Standard",smart:"Smart"};function T(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 ")+H(t.plan):""}${t.credits?s.grey(" \xB7 ")+t.credits:""}`:s.grey(t.status??"connecting\u2026"),l=[i,o,`${s.grey("model")} ${F[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}`)}`),T(a,e,{border:c=>s.ember(c)})}var H=t=>t.charAt(0).toUpperCase()+t.slice(1),P=["Forging","Sparking","Kindling","Stoking","Smelting","Hammering","Tempering","Igniting","Annealing","Striking","Blazing","Quenching"],j=["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D","\u273B","\u2736","\u2733","\u2722"];function at(t,r,e,n,i){let o=i??P[Math.floor(r/3e3)%P.length],l=j[t%j.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(F[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 Z={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 q(t){return Z[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(q(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
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
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
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
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
7
  `),n=e.flatMap((o,l)=>/^\[\d+\] /.test(o)?[G(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 G(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return""}}function Q(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=E(t),{added:o,removed:l}=Q(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 $=String(b).length,p=[],u=!0;for(let g of i.split(`
9
- `)){if(g.startsWith("===")||g.startsWith("Index:")||g.startsWith("---")||g.startsWith("+++"))continue;let v=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(g);if(v){h=Number(v[1]),d=Number(v[2]),u||p.push(` ${s.grey("\u2506")} ${s.grey(" ".repeat($)+" \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 U=` ${s.grey("\u2502")} ${s.grey(k.padStart($))} `,C=Math.max(10,a-($+5)-2);J(`${A} ${D}`,C).forEach((_,K)=>{let z=y===" "?s.grey(_):_,V=y===" "||M()<2?w(z):w(R(z,C));p.push((K===0?U:` ${s.grey("\u2502")} ${" ".repeat($)} `)+V)})}return f.push(...p,` ${s.grey("\u2514")}`),f}function J(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);return T([`${i(o)} ${s.bold(t)}`,...r.map(a=>` ${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=Y(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=p===0&&c===0?s.ember(o):" ".repeat(x(o)),g=h&&n.placeholder?s.grey(m(n.placeholder,l)):$;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 Y=(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 $t=t=>t.map(L);export{L as a,N as b,x as c,m as d,R as e,X as f,et as g,E as h,B as i,F as j,T as k,lt as l,P as m,j as n,at as o,ct as p,q,gt as r,ft as s,ut as t,Q as u,dt as v,xt as w,ht as x,mt as y,Y as z,bt as A,$t as B};
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}=Q(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],U=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 D=` ${s.grey("\u2502")} ${s.grey(k.padStart(p))} `,C=Math.max(10,a-(p+5)-2);J(`${A} ${U}`,C).forEach((_,K)=>{let z=y===" "?s.grey(_):_,V=y===" "||M()<2?w(z):w(R(z,C));$.push((K===0?D:` ${s.grey("\u2502")} ${" ".repeat(p)} `)+V)})}return f.push(...$,` ${s.grey("\u2514")}`),f}function J(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);return T([`${i(o)} ${s.bold(t)}`,...r.map(a=>` ${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=Y(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 Y=(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,X as f,et as g,v as h,B as i,F as j,T as k,lt as l,P as m,j as n,at as o,ct as p,q,gt as r,ft as s,ut as t,Q as u,dt as v,xt as w,ht as x,mt as y,Y as z,bt as A,pt as B};
@@ -0,0 +1,23 @@
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{},U={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,(U[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.3",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:"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"]),F=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()}`)||F.has(o)&&l===r||F.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,4 +1,4 @@
1
- import{a as U,b as Y}from"./chunk-2XK6FXMP.js";import{d as M,h as _,j as x,s as I,x as P}from"./chunk-2DDAUP6P.js";import{h as m,r as u,s as p,t as L,v as S}from"./chunk-HEEZNIZR.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+`
1
+ import{a as U,b as Y}from"./chunk-67ZTNBQ7.js";import{A as P,d as M,i as _,k as x,v as I}from"./chunk-NIG4OMDP.js";import{h as m,r as u,s as p,t as L,v as S}from"./chunk-B6N6RRG5.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
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
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
4
  ${t.lines.map(i=>` ${i}
@@ -1 +1 @@
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-HEEZNIZR.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};
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-B6N6RRG5.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};
@@ -1,27 +1,27 @@
1
- import{a as Q,c as G,d as R,e as Z}from"./chunk-EUPBID7K.js";import{a as mt,b as pt}from"./chunk-2XK6FXMP.js";import{a as L,b as j,c as H,d as J,e as z,f as I,g as K,h as V,j as N,k as W,l as X,m as tt,n as et,o as st,p as it,q as M,r as F,s as k,t as rt,u as g,v as nt,w as ot,x as ht,y as at}from"./chunk-2DDAUP6P.js";import{A as Tt,b as lt,c as w,d as ct,f as ut,g as dt,h as x,i as ft,j as gt,k as bt,l as wt,m as v,o as xt,p as vt,r as y,s as p,t as yt,u as St,v as $t,w as T,x as Ct,y as Mt,z as kt}from"./chunk-HEEZNIZR.js";import{b as o}from"./chunk-5PRYZOW7.js";import"./chunk-K3ZZ2VJH.js";import{existsSync as Zt}from"node:fs";import{homedir as Vt}from"node:os";import{join as Xt}from"node:path";var S=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(`
1
+ import{a as G,c as Z,d as K,e as V}from"./chunk-EUPBID7K.js";import{a as pt,b as ft}from"./chunk-67ZTNBQ7.js";import{A as ht,B as lt,a as D,b as J,c as z,d as Q,f as L,g as I,h as N,i as X,k as U,m as W,n as F,o as tt,p as et,q as st,r as it,s as rt,t as M,u as q,v as k,w as nt,x as g,y as ot,z as at}from"./chunk-NIG4OMDP.js";import{A as Pt,b as ct,c as x,d as ut,f as dt,g as mt,h as w,i as gt,j as bt,k as xt,l as wt,m as v,o as vt,p as yt,r as y,s as p,t as St,u as $t,v as Ct,w as T,x as Mt,y as kt,z as Tt}from"./chunk-B6N6RRG5.js";import{b as o}from"./chunk-5PRYZOW7.js";import"./chunk-K3ZZ2VJH.js";import{existsSync as Vt}from"node:fs";import{homedir as Xt}from"node:os";import{join as te}from"node:path";var S=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
2
  `,t-1)+1}lineEnd(t=this.cursor){let e=this.text.indexOf(`
3
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
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=w(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 l=lt(this.text.codePointAt(i));if(r+l>e)break;r+=l,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 l=ut(n,Math.max(1,t)),h=r;l.forEach((a,c)=>{let b=c===l.length-1,d=h+a.length;this.cursor>=h&&(this.cursor<d||b&&this.cursor===d)&&(s=e.length,i=w(a.slice(0,this.cursor-h))),e.push(a),h=d}),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 Pt,statSync as Ut}from"node:fs";import{dirname as _t,join as At,resolve as Et}from"node:path";function Ot(u){let t=Et(u);for(let e=0;e<40;e++){let s=At(t,".git");try{let r=s;if(Ut(s).isFile()){let h=/^gitdir:\s*(.+)$/m.exec(Pt(s,"utf8"));if(!h)return null;r=Et(t,h[1].trim())}let n=Pt(At(r,"HEAD"),"utf8").trim(),l=/^ref: refs\/heads\/(.+)$/.exec(n);return l?l[1]:n.slice(0,7)}catch{}let i=_t(t);if(i===t)return null;t=i}return null}import{appendFileSync as Bt,mkdirSync as qt,readFileSync as Yt,writeFileSync as jt}from"node:fs";import{homedir as Ht}from"node:os";import{dirname as Jt,join as zt}from"node:path";var Qt=()=>process.env.FLINT_HISTORY||zt(Ht(),".flintmaker","history"),U=500,P=class{constructor(t=Qt()){this.file=t;if(t)try{this.entries=Yt(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(-U)}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{qt(Jt(this.file),{recursive:!0,mode:448}),this.entries.length>U*1.5?(this.entries=this.entries.slice(-U),jt(this.file,this.entries.map(s=>JSON.stringify(s)).join(`
5
+ `,this.cursor)<0}vertical(t){if(t<0?this.onFirstLine:this.onLastLine)return!1;let e=x(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 l=ct(this.text.codePointAt(i));if(r+l>e)break;r+=l,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 l=dt(n,Math.max(1,t)),a=r;l.forEach((h,c)=>{let b=c===l.length-1,d=a+h.length;this.cursor>=a&&(this.cursor<d||b&&this.cursor===d)&&(s=e.length,i=x(h.slice(0,this.cursor-a))),e.push(h),a=d}),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 At,statSync as qt}from"node:fs";import{dirname as _t,join as Et,resolve as Rt}from"node:path";function Ot(u){let t=Rt(u);for(let e=0;e<40;e++){let s=Et(t,".git");try{let r=s;if(qt(s).isFile()){let a=/^gitdir:\s*(.+)$/m.exec(At(s,"utf8"));if(!a)return null;r=Rt(t,a[1].trim())}let n=At(Et(r,"HEAD"),"utf8").trim(),l=/^ref: refs\/heads\/(.+)$/.exec(n);return l?l[1]:n.slice(0,7)}catch{}let i=_t(t);if(i===t)return null;t=i}return null}import{appendFileSync as Bt,mkdirSync as Yt,readFileSync as jt,writeFileSync as Ht}from"node:fs";import{homedir as Jt}from"node:os";import{dirname as zt,join as Qt}from"node:path";var Gt=()=>process.env.FLINT_HISTORY||Qt(Jt(),".flintmaker","history"),_=500,P=class{constructor(t=Gt()){this.file=t;if(t)try{this.entries=jt(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(-_)}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{Yt(zt(this.file),{recursive:!0,mode:448}),this.entries.length>_*1.5?(this.entries=this.entries.slice(-_),Ht(this.file,this.entries.map(s=>JSON.stringify(s)).join(`
8
8
  `)+`
9
9
  `,{mode:384})):Bt(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 Gt={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"},_={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",Z:"tab"},Dt={13:"enter",9:"tab",27:"escape",127:"backspace",8:"backspace",32:"space"};function B(u){let t=(u??1)-1;return{shift:!!(t&1),meta:!!(t&2)||!!(t&8),ctrl:!!(t&4)}}function Lt(u,t){let e=B(t);if(Dt[u])return{name:Dt[u],...e,...u===32&&!e.ctrl&&!e.meta?{text:" "}:{}};let s=String.fromCodePoint(u);return e.ctrl||e.meta?{name:s.toLowerCase(),...e}:{name:s,text:e.shift?s.toUpperCase():s,...e}}var It="\x1B[200~",Rt="\x1B[201~",A=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(Rt);if(r<0)return this.paste+=this.buf,this.buf="",e;this.paste+=this.buf.slice(0,r),this.buf=this.buf.slice(r+Rt.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(It)){this.buf=this.buf.slice(It.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 a=/^\x1b\[([0-9;:?<>]*)([ -/]*)([@-~])/.exec(t);if(!a)return t.length<16?[null,0]:[{name:"escape"},1];let[c,b,,d]=a,m=b.split(";").map(f=>Number(f.split(":")[0])||void 0);return d==="u"?[Lt(m[0]??0,m[1]),c.length]:d==="~"?m[0]===27&&m[2]!==void 0?[Lt(m[2],m[1]),c.length]:[{name:Gt[String(m[0])]??"unknown",...B(m[1])},c.length]:d==="Z"?[{name:"tab",shift:!0},c.length]:_[d]?[{name:_[d],...B(m[1])},c.length]:d==="I"||d==="O"?[{name:d==="I"?"focusin":"focusout"},c.length]:[{name:"unknown"},c.length]}if(n==="O"&&t.length>=3)return[{name:_[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 l=t.codePointAt(1),h=l>65535?3:2;return[{name:String.fromCodePoint(l).toLowerCase(),meta:!0},h]}if(e==="\r")return[{name:"enter"},t[1]===`
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 Zt={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"},B={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",Z:"tab"},Dt={13:"enter",9:"tab",27:"escape",127:"backspace",8:"backspace",32:"space"};function Y(u){let t=(u??1)-1;return{shift:!!(t&1),meta:!!(t&2)||!!(t&8),ctrl:!!(t&4)}}function Lt(u,t){let e=Y(t);if(Dt[u])return{name:Dt[u],...e,...u===32&&!e.ctrl&&!e.meta?{text:" "}:{}};let s=String.fromCodePoint(u);return e.ctrl||e.meta?{name:s.toLowerCase(),...e}:{name:s,text:e.shift?s.toUpperCase():s,...e}}var It="\x1B[200~",Kt="\x1B[201~",A=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(Kt);if(r<0)return this.paste+=this.buf,this.buf="",e;this.paste+=this.buf.slice(0,r),this.buf=this.buf.slice(r+Kt.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(It)){this.buf=this.buf.slice(It.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 h=/^\x1b\[([0-9;:?<>]*)([ -/]*)([@-~])/.exec(t);if(!h)return t.length<16?[null,0]:[{name:"escape"},1];let[c,b,,d]=h,m=b.split(";").map(f=>Number(f.split(":")[0])||void 0);return d==="u"?[Lt(m[0]??0,m[1]),c.length]:d==="~"?m[0]===27&&m[2]!==void 0?[Lt(m[2],m[1]),c.length]:[{name:Zt[String(m[0])]??"unknown",...Y(m[1])},c.length]:d==="Z"?[{name:"tab",shift:!0},c.length]:B[d]?[{name:B[d],...Y(m[1])},c.length]:d==="I"||d==="O"?[{name:d==="I"?"focusin":"focusout"},c.length]:[{name:"unknown"},c.length]}if(n==="O"&&t.length>=3)return[{name:B[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 l=t.codePointAt(1),a=l>65535?3:2;return[{name:String.fromCodePoint(l).toLowerCase(),meta:!0},a]}if(e==="\r")return[{name:"enter"},t[1]===`
14
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]}},E=u=>u.name==="enter"&&!!(u.shift||u.meta||u.ctrl);var Kt="\x1B[?2026h",Nt="\x1B[?2026l",$=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=>w(r)>t-1?ct(r,t-1):r);if(this.widths=e.map(w),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(Kt+"\x1B[?25l"+s+this.drawSeq()+Nt)}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(`
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]}},E=u=>u.name==="enter"&&!!(u.shift||u.meta||u.ctrl);var Nt="\x1B[?2026h",Ut="\x1B[?2026l",$=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=>x(r)>t-1?ut(r,t-1):r);if(this.widths=e.map(x),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(Nt+"\x1B[?25l"+s+this.drawSeq()+Ut)}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
17
  `)).map(r=>r+"\x1B[K").join(`\r
18
18
  `)+`\r
19
- `;this.out.write(Kt+"\x1B[?25l"+s+i+this.drawSeq()+Nt)}clear(){let t=this.eraseSeq();this.lines=[],this.cursor=null,this.widths=[],this.cursorRow=0,this.out.write(t+"\x1B[?25h")}};var O=["ask","auto","plan"],te=new Set(["write_file","edit_file"]),q=class{constructor(t){this.opts=t;this.model=t.model,this.mode=t.mode??"ask",this.client=t.client,this.branch=Ot(t.ws.root),this.cwdShort=Tt(t.ws.root,Vt(),28),this.md=new pt(()=>this.screen.cols-1)}opts;screen=new $(process.stdout);editor=new S;feedback=new S;history=new P;parser=new A({pasteHeuristic:process.platform==="win32"});escTimer;mode="ask";model;client;me=null;usage=null;branch;cwdShort;conversation=[];busy=null;sessionCredits=0;frame=0;spinTimer;md;assistantStarted=!1;running=null;headerShown=!1;lastStats=null;prompt=null;suggestions=null;suggestionsDismissed=!1;queue=[];hint=null;exitArmedUntil=0;allowedKinds=new Set;welcomePending=!0;renderQueued=!1;finished;closed=!1;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-QJIBHZTN.js").then(e=>mt(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.busy?.controller.abort(),this.stopSpinner(),this.prompt=null,this.screen.clear();let e=this.sessionCredits?o.grey(` ${F(this.sessionCredits)} credits used this session.`):"";process.stdout.write(`${o.ember("\u2726")} ${o.grey(t)}${e}\r
20
- `),this.restoreTerminal(),N(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()]),N(t=>this.commit(["",`${o.ember("\u2726")} ${o.grey(t)}`])))}welcomeLines(){return wt({version:this.opts.version,email:this.me?.user.email,plan:this.me?.user.plan,credits:this.usage?k(this.usage):void 0,model:this.model,cwd:this.cwdShort,status:this.me?void 0:"connecting\u2026"},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("",y(this.running.name,this.running.detail,"running",t)),this.busy&&!this.prompt&&e.push("",xt(this.frame,Date.now()-this.busy.start,this.busy.credits,t,this.busy.verb)),this.prompt?.kind==="menu")s.push("",...Ct(this.prompt.question,this.prompt.options,this.prompt.selected,t,this.prompt.esc));else{for(let f of this.queue)s.push(o.grey(` \u23F5 queued: ${f.split(`
21
- `)[0]}`));s.push("");let a=this.prompt?.kind==="feedback"?this.feedback:this.editor,c=this.prompt?.kind==="feedback"?"\u270E ":"\u276F ",b=a.layout(kt(t,c)),d=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",m=Mt(b.rows,b,t,{placeholder:d,prefix:c,maxRows:Math.max(3,Math.min(10,this.screen.rows-12))});if(i={row:s.length+m.cursorRow,col:m.cursorCol},s.push(...m.lines),this.suggestions&&!this.prompt){let{items:f,selected:Y}=this.suggestions,D=Math.max(0,Math.min(Y-3,f.length-7));f.slice(D,D+7).forEach((C,Wt)=>{let Ft=D+Wt===Y?o.ember(`\u276F ${C.label}`):` ${C.label}`;s.push(` ${Ft}${C.hint?o.grey(` ${C.hint}`):""}`)}),f.length>7&&s.push(o.grey(` ${f.length} matches \xB7 tab to complete`))}}s.push(this.footerLine());let r=this.screen.rows-1-e.length-s.length,n=this.previewLines(),l=r>0?n.slice(Math.max(0,n.length-r)):[],h=[...l,...e,...s];return i&&(i={row:i.row+l.length+e.length,col:i.col}),{lines:h,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),vt({model:this.model,mode:this.mode,credits:this.usage?k(this.usage):void 0,cwd:this.cwdShort,branch:this.branch,hint:this.hint?.text},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){let s=V(t,{interactive:!0,retry:e?"Press \u2191 then enter to try again.":void 0});this.commit(["",...T(s.title,s.lines,this.screen.cols,s.tone)]),this.render()}info(t,e){this.commit(["",...T(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??v[Math.floor(Math.random()*v.length)],controller:e};let s=!t,i=0;return this.spinTimer=setInterval(()=>{this.frame++,s&&++i%40===0&&this.busy&&(this.busy.verb=v[(v.indexOf(this.busy.verb)+1)%v.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"&&!E(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"&&!E(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 $(process.stdout),this.render();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(x(e.text??"").replace(/\t/g," "));if(E(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.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)return 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=O[(O.indexOf(this.mode)+1)%O.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=et(t).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=it(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=st(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 s=this.suggestions.items[this.suggestions.selected].value;W.some(i=>`/${i.name}`===t.text.trim())||t.set(s)}let e=t.text.trim();if(e){if(this.history.add(e),t.clear(),this.suggestions=null,this.busy)return this.queue.push(e),this.schedule();this.submit(e)}}async submit(t){try{let s=X(t);s?await this.command(s.name,s.args,!!s.command):await this.turn(t)}catch(s){this.stopSpinner(),this.showError(s,!1)}let e=this.queue.shift();e!==void 0&&!this.closed&&this.submit(e)}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(x(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){this.echo(e);let s=await ht(this.opts.ws,t,{first:this.conversation.length===0,mode:this.mode});s.memory&&this.note(`Using ${M} project memory`);for(let a of s.attachments)a.error?this.note(`Could not attach ${a.path}: ${a.error}`,o.gold):this.note(`Attached ${a.path} (${a.lines} line${a.lines===1?"":"s"})`);let i=this.startSpinner(),r=Date.now(),n=[...this.conversation,{role:"user",content:s.content}],l=!1;try{this.conversation=await J(this.opts.ws,n,this.stepper(i),this.agentUI(i),{signal:i.signal})}catch(a){l=!0,this.flushMarkdown();let c=a.partial;c&&c.length>n.length&&(this.conversation=c),this.showError(a),a instanceof z&&a.reason==="signed_out"&&R()}this.flushMarkdown(),this.running=null;let h=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 c=[`${Math.max(1,Math.round((Date.now()-r)/1e3))}s`,`${h} credit${h===1?"":"s"}`,this.usage?k(this.usage):null].filter(Boolean);this.commit(["",o.grey(` \u273B ${c.join(" \xB7 ")}`)])}this.render()}agentUI(t){let e=()=>this.screen.cols;return{onDelta:s=>{this.running&&(this.running=null),this.commitAssistant(this.md.push(x(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=[],l=this.lastDetail;if(!i)this.headerShown||n.push("",y(s,l,"error",e())),n.push(...p(r,e(),3,o.red));else if(te.has(s))if(/^(Created|Updated) /.test(r)){let h=this.lastStats;n.push(...p(`${r.startsWith("Created")?"Created":"Updated"}${h?` \xB7 +${h.added} -${h.removed}`:""}`,e()))}else n.push(...p(r===L?"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(...p(r.startsWith("Plan mode")?"Skipped (plan mode)":this.declinedText("Not run"),e()));else if(r===L||r.startsWith("[interrupted by the user before"))n.push(...p("Interrupted",e()));else{let h=/\n?\[(exit code (\d+|null)|timed out after \d+s|interrupted by the user|could not run command[^\]]*)\]$/.exec(r),a=(h?r.slice(0,h.index):r).trimEnd(),c=!h||h[2]!=="0";this.headerShown||n.push("",y(s,l,c?"error":"ok",e())),a?n.push(...p(a,e(),5)):c||n.push(...p("Done (no output)",e())),c&&h&&n.push(` ${a?" ":o.grey("\u23BF")} ${o.red(h[1])}`)}else{let h=yt(s,r);n.push("",y(s,l,"ok",e(),h.suffix)),h.detail&&n.push(...p(h.detail,e()))}this.commit(n),this.schedule()},approveChange:async s=>(this.running=null,this.headerShown=!0,this.lastStats=St(s.diff),this.lastDetail=s.path,this.commit(["",y(s.created?"write_file":"edit_file",s.path,"ok",e()),...$t(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||this.mode==="auto"?!0:this.decide(t,`${s.created?"Create":"Make this edit to"} ${o.ember(x(s.path))}?`,"Yes, and don't ask again for edits this session","change",()=>{this.mode="auto"})),approveCommand:async s=>{this.running=null,this.headerShown=!0;let i=x(s),r=dt(`${o.ember("\u25CF")} ${o.bold("Run")} ${i}`,e()-1," ");if(this.commit(["",...r]),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;let n=at(s);return n&&this.allowedKinds.has(n)?(this.note(`Allowed (${n} commands are approved for this session)`),!0):this.decide(t,"Run this command?",n?`Yes, and don't ask again for "${n}" commands this session`:null,"command",()=>n&&this.allowedKinds.add(n))}}}lastDetail="";declinedText(t){return this.lastFeedback?`${t} \xB7 you said: ${this.lastFeedback.split(`
25
- `)[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 l=await this.ask(e,n,0,"stop flint");if(l===null)return t.abort(),!1;if(l===0)return!0;if(s&&l===1)return r(),!0;let h=await this.askFeedback();return h===null||h===""?!1:(this.lastFeedback=h,{declined:`The user declined this ${i} and said: ${JSON.stringify(h)}. Follow their instruction instead.`})}async command(t,e,s){if(!s){let i=tt(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"clear":return this.conversation=[],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=O.includes(i)?i:i==="auto-accept"?"auto":null;return r?this.mode=r:this.cycleMode(),this.note(`Mode: ${ft[this.mode]}`),this.render()}case"model":return this.modelCommand(e);case"credits":return this.creditsCommand();case"init":return this.initCommand();case"compact":return this.compactCommand();case"login":return this.loginCommand();case"logout":return R(),this.exit("Signed out. Run flint login to connect again.")}}help(){let t=W.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(["",...bt([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:`${g[r].label}${r===this.model?o.grey(" (current)"):""}`,hint:`${g[r].cost} \xB7 ${g[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(["",...T("Smart needs a paid plan",["You are on the Free plan, so flint stays on Standard.",`Upgrade: ${K}`],this.screen.cols,"warn")]),this.render();this.model=e,this.note(`Model: ${gt[e]} \xB7 ${g[e].cost}`),this.render()}async creditsCommand(){try{this.me=await this.client.me(),this.usage=this.me.usage;let t=this.sessionCredits?[`This session: ${F(this.sessionCredits)} credits`]:[];this.info("Credits",[...rt(this.usage),...t,"",`Standard ${g.standard.cost} \xB7 Smart ${g.smart.cost}`,`More credits: ${K}`])}catch(t){this.showError(t,!1)}this.render()}async initCommand(){if(Zt(Xt(this.opts.ws.root,M)))return this.info(`${M} 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 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 j))throw n;e=H(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):
19
+ `;this.out.write(Nt+"\x1B[?25l"+s+i+this.drawSeq()+Ut)}clear(){let t=this.eraseSeq();this.lines=[],this.cursor=null,this.widths=[],this.cursorRow=0,this.out.write(t+"\x1B[?25h")}};var R=["ask","auto","plan"],ee=new Set(["write_file","edit_file"]),j=class{constructor(t){this.opts=t;this.model=t.model,this.mode=t.mode??"ask",this.client=t.client,this.branch=Ot(t.ws.root),this.cwdShort=Pt(t.ws.root,Xt(),28),this.md=new ft(()=>this.screen.cols-1)}opts;screen=new $(process.stdout);editor=new S;feedback=new S;history=new P;parser=new A({pasteHeuristic:process.platform==="win32"});escTimer;mode="ask";model;client;me=null;usage=null;branch;cwdShort;conversation=[];busy=null;sessionCredits=0;frame=0;spinTimer;md;assistantStarted=!1;running=null;headerShown=!1;lastStats=null;prompt=null;suggestions=null;suggestionsDismissed=!1;queue=[];hint=null;statusNote=null;updateRequested=!1;exitArmedUntil=0;allowedKinds=new Set;welcomePending=!0;renderQueued=!1;finished;closed=!1;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-QJIBHZTN.js").then(e=>pt(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.busy?.controller.abort(),this.stopSpinner(),this.prompt=null,this.screen.clear();let e=this.sessionCredits?o.grey(` ${q(this.sessionCredits)} credits used this session.`):"";process.stdout.write(`${o.ember("\u2726")} ${o.grey(t)}${e}\r
20
+ `),this.restoreTerminal(),U(null),W(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()]),U(t=>this.commit(["",`${o.ember("\u2726")} ${o.grey(t)}`])),W(t=>{this.statusNote=t,this.schedule()}))}welcomeLines(){return wt({version:this.opts.version,email:this.me?.user.email,plan:this.me?.user.plan,credits:this.usage?k(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("",y(this.running.name,this.running.detail,"running",t)),this.busy&&!this.prompt&&e.push("",vt(this.frame,Date.now()-this.busy.start,this.busy.credits,t,this.busy.verb)),this.prompt?.kind==="menu")s.push("",...Mt(this.prompt.question,this.prompt.options,this.prompt.selected,t,this.prompt.esc));else{for(let f of this.queue)s.push(o.grey(` \u23F5 queued: ${f.split(`
21
+ `)[0]}`));s.push("");let h=this.prompt?.kind==="feedback"?this.feedback:this.editor,c=this.prompt?.kind==="feedback"?"\u270E ":"\u276F ",b=h.layout(Tt(t,c)),d=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",m=kt(b.rows,b,t,{placeholder:d,prefix:c,maxRows:Math.max(3,Math.min(10,this.screen.rows-12))});if(i={row:s.length+m.cursorRow,col:m.cursorCol},s.push(...m.lines),this.suggestions&&!this.prompt){let{items:f,selected:H}=this.suggestions,O=Math.max(0,Math.min(H-3,f.length-7));f.slice(O,O+7).forEach((C,Wt)=>{let Ft=O+Wt===H?o.ember(`\u276F ${C.label}`):` ${C.label}`;s.push(` ${Ft}${C.hint?o.grey(` ${C.hint}`):""}`)}),f.length>7&&s.push(o.grey(` ${f.length} matches \xB7 tab to complete`))}}s.push(this.footerLine());let r=this.screen.rows-1-e.length-s.length,n=this.previewLines(),l=r>0?n.slice(Math.max(0,n.length-r)):[],a=[...l,...e,...s];return i&&(i={row:i.row+l.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),yt({model:this.model,mode:this.mode,credits:this.usage?k(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 L&&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=X(t,{interactive:!0,retry:e?"Press \u2191 then enter to try again.":void 0});this.commit(["",...T(s.title,s.lines,this.screen.cols,s.tone)]),this.render()}info(t,e){this.commit(["",...T(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??v[Math.floor(Math.random()*v.length)],controller:e};let s=!t,i=0;return this.spinTimer=setInterval(()=>{this.frame++,s&&++i%40===0&&this.busy&&(this.busy.verb=v[(v.indexOf(this.busy.verb)+1)%v.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"&&!E(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"&&!E(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 $(process.stdout),this.render();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(w(e.text??"").replace(/\t/g," "));if(E(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.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)return 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=R[(R.indexOf(this.mode)+1)%R.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=st(t).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=rt(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=it(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 s=this.suggestions.items[this.suggestions.selected].value;F.some(i=>`/${i.name}`===t.text.trim())||t.set(s)}let e=t.text.trim();if(e){if(this.history.add(e),t.clear(),this.suggestions=null,this.busy)return this.queue.push(e),this.schedule();this.submit(e)}}async submit(t){try{let s=tt(t);s?await this.command(s.name,s.args,!!s.command):await this.turn(t)}catch(s){this.stopSpinner(),this.showError(s,!1)}let e=this.queue.shift();e!==void 0&&!this.closed&&this.submit(e)}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(w(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){this.echo(e);let s=await ht(this.opts.ws,t,{first:this.conversation.length===0,mode:this.mode});s.memory&&this.note(`Using ${M} project memory`);for(let h of s.attachments)h.error?this.note(`Could not attach ${h.path}: ${h.error}`,o.gold):this.note(`Attached ${h.path} (${h.lines} line${h.lines===1?"":"s"})`);let i=this.startSpinner(),r=Date.now(),n=[...this.conversation,{role:"user",content:s.content}],l=!1;try{this.conversation=await Q(this.opts.ws,n,this.stepper(i),this.agentUI(i),{signal:i.signal})}catch(h){l=!0,this.flushMarkdown();let c=h.partial;c&&c.length>n.length&&(this.conversation=c),this.showError(h),h instanceof L&&h.reason==="signed_out"&&K()}this.flushMarkdown(),this.running=null;let a=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 c=[`${Math.max(1,Math.round((Date.now()-r)/1e3))}s`,`${a} credit${a===1?"":"s"}`,this.usage?k(this.usage):null].filter(Boolean);this.commit(["",o.grey(` \u273B ${c.join(" \xB7 ")}`)])}this.render()}agentUI(t){let e=()=>this.screen.cols;return{onDelta:s=>{this.running&&(this.running=null),this.commitAssistant(this.md.push(w(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=[],l=this.lastDetail;if(!i)this.headerShown||n.push("",y(s,l,"error",e())),n.push(...p(r,e(),3,o.red));else if(ee.has(s))if(/^(Created|Updated) /.test(r)){let a=this.lastStats;n.push(...p(`${r.startsWith("Created")?"Created":"Updated"}${a?` \xB7 +${a.added} -${a.removed}`:""}`,e()))}else n.push(...p(r===D?"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(...p(r.startsWith("Plan mode")?"Skipped (plan mode)":this.declinedText("Not run"),e()));else if(r===D||r.startsWith("[interrupted by the user before"))n.push(...p("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),h=(a?r.slice(0,a.index):r).trimEnd(),c=!a||a[2]!=="0";this.headerShown||n.push("",y(s,l,c?"error":"ok",e())),h?n.push(...p(h,e(),5)):c||n.push(...p("Done (no output)",e())),c&&a&&n.push(` ${h?" ":o.grey("\u23BF")} ${o.red(a[1])}`)}else{let a=St(s,r);n.push("",y(s,l,"ok",e(),a.suffix)),a.detail&&n.push(...p(a.detail,e()))}this.commit(n),this.schedule()},approveChange:async s=>(this.running=null,this.headerShown=!0,this.lastStats=$t(s.diff),this.lastDetail=s.path,this.commit(["",y(s.created?"write_file":"edit_file",s.path,"ok",e()),...Ct(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||this.mode==="auto"?!0:this.decide(t,`${s.created?"Create":"Make this edit to"} ${o.ember(w(s.path))}?`,"Yes, and don't ask again for edits this session","change",()=>{this.mode="auto"})),approveCommand:async s=>{this.running=null,this.headerShown=!0;let i=w(s),r=mt(`${o.ember("\u25CF")} ${o.bold("Run")} ${i}`,e()-1," ");if(this.commit(["",...r]),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;let n=lt(s);return n&&this.allowedKinds.has(n)?(this.note(`Allowed (${n} commands are approved for this session)`),!0):this.decide(t,"Run this command?",n?`Yes, and don't ask again for "${n}" commands this session`:null,"command",()=>n&&this.allowedKinds.add(n))}}}lastDetail="";declinedText(t){return this.lastFeedback?`${t} \xB7 you said: ${this.lastFeedback.split(`
25
+ `)[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 l=await this.ask(e,n,0,"stop flint");if(l===null)return t.abort(),!1;if(l===0)return!0;if(s&&l===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){let i=et(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"clear":return this.conversation=[],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=R.includes(i)?i:i==="auto-accept"?"auto":null;return r?this.mode=r:this.cycleMode(),this.note(`Mode: ${gt[this.mode]}`),this.render()}case"model":return this.modelCommand(e);case"credits":return this.creditsCommand();case"init":return this.initCommand();case"compact":return this.compactCommand();case"login":return this.loginCommand();case"logout":return K(),this.exit("Signed out. Run flint login to connect again.")}}help(){let t=F.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(["",...xt([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:`${g[r].label}${r===this.model?o.grey(" (current)"):""}`,hint:`${g[r].cost} \xB7 ${g[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(["",...T("Smart needs a paid plan",["You are on the Free plan, so flint stays on Standard.",`Upgrade: ${N}`],this.screen.cols,"warn")]),this.render();this.model=e,this.note(`Model: ${bt[e]} \xB7 ${g[e].cost}`),this.render()}async creditsCommand(){try{this.me=await this.client.me(),this.usage=this.me.usage;let t=this.sessionCredits?[`This session: ${q(this.sessionCredits)} credits`]:[];this.info("Credits",[...nt(this.usage),...t,"",`Standard ${g.standard.cost} \xB7 Smart ${g.smart.cost}`,`More credits: ${N}`])}catch(t){this.showError(t,!1)}this.render()}async initCommand(){if(Vt(te(this.opts.ws.root,M)))return this.info(`${M} 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(ot,"/init")}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:at}],()=>{})).text.trim(),!s)throw new Error("The summary came back empty. Try again, or use /clear.")}catch(n){if(!(n instanceof J))throw n;e=z(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):
26
26
 
27
- ${s}`},{role:"assistant",content:"Thanks, I have the context. What should we do next?"}],this.note(`Compacted ${i} messages into a summary`),this.commit(p(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=Z(null),e=new I(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"]),Q(n),this.render()},s.signal);G({token:i.token,email:i.user.email,api:e.base}),this.client=new I(t,i.token),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 Re(u){await new q(u).run()}export{q as App,Re as interactive};
27
+ ${s}`},{role:"assistant",content:"Thanks, I have the context. What should we do next?"}],this.note(`Compacted ${i} messages into a summary`),this.commit(p(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=V(null),e=new I(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"]),G(n),this.render()},s.signal);Z({token:i.token,email:i.user.email,api:e.base}),this.client=new I(t,i.token),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 Ke(u){await new j(u).run()}export{j as App,Ke as interactive};
@@ -0,0 +1,20 @@
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)+`
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,"--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
+ `);return E.map(c=>({path:r.join(e,`${c}.cmd`),content:i}))}let o=i=>i.replace(/[\\"$`]/g,"\\$&"),s=`#!/bin/sh
4
+ # FlintMaker CLI launcher (written by https://flintmaker.com/install.sh)
5
+ FM_HOME="${o(e)}"
6
+ ENTRY="$FM_HOME/lib/node_modules/flintmaker/${o(n)}"
7
+ if [ -x "$FM_HOME/node/bin/node" ]; then
8
+ PATH="$FM_HOME/node/bin:$PATH"; export PATH
9
+ exec "$FM_HOME/node/bin/node" "$ENTRY" "$@"
10
+ fi
11
+ if command -v node >/dev/null 2>&1; then exec node "$ENTRY" "$@"; fi
12
+ echo "flint: Node.js 20+ is missing. Reinstall: curl -fsSL https://flintmaker.com/install.sh | sh" >&2
13
+ exit 127
14
+ `;return E.map(i=>({path:r.join(e,"bin",i),content:s,mode:493}))}function D(e){for(let n of fe(e))ie(n,{force:!0})}function q(e,n=process.platform){let t=d(n),r;try{r=JSON.parse(U(t.join(A(e,n),x,"package.json"),"utf8")).bin}catch{}D(e);for(let o of pe(e,z(r),n))V(t.dirname(o.path),{recursive:!0}),y(o.path,o.content,o.mode?{mode:o.mode}:{}),o.mode&&re(o.path,o.mode)}function Z(e,n,t="inherit"){let r=$(e,n);if(!r)return-1;let o=e.kind==="flintmaker";o&&D(e.prefix);let s=-1;try{s=te(r.file,r.args,{...r.options,stdio:["ignore",t,t],env:{...process.env,npm_config_update_notifier:"false"}}).status??-1}finally{if(o)try{q(e.prefix)}catch(i){typeof t=="number"&&y(t,`could not write launchers: ${i.message}
15
+ `),s=s===0?1:s}}return s}function me(e,n,t={}){let r=$(e,n);if(!r)return Promise.resolve(-1);let o=e.kind==="flintmaker",s=t.logFd??"ignore",i=g()?process.title:null;return new Promise(c=>{let a,l=u=>{if(a&&clearTimeout(a),i)try{process.title=i}catch{}if(t.signal?.removeEventListener("abort",m),o)try{q(e.prefix)}catch(b){typeof s=="number"&&y(s,`could not write launchers: ${b.message}
16
+ `),u=u===0?1:u}c(u)},f,m=()=>L(f?.pid,process.platform,()=>f?.kill("SIGKILL"));try{o&&D(e.prefix),f=F(r.file,r.args,{...r.options,stdio:["ignore",s,s],env:{...process.env,npm_config_update_notifier:"false"}})}catch{return l(-1)}let v=!1,S=u=>{v||(v=!0,l(u))};f.on("error",()=>S(-1)),f.on("exit",u=>S(u??-1)),t.timeoutMs&&(a=setTimeout(m,t.timeoutMs)),t.signal?.aborted?m():t.signal?.addEventListener("abort",m,{once:!0})})}function Fe(e){if(!k(e))return 2;let n=Z(T(),e,"inherit");return p({...w(),attempted:e,...n===0?{installed:e,failed:void 0}:{failed:e}}),n}function ge(e,n){return new Promise(t=>{let r="ignore";try{r=K(n,"a"),y(r,`
17
+ [${new Date().toISOString()}] updating to ${x}@${e}
18
+ `)}catch{r="ignore"}try{let o=F(process.execPath,[process.argv[1],"__update",e],{detached:!0,windowsHide:!0,stdio:["ignore",r,r],env:{...process.env,FLINT_NO_UPDATE:"1"}});o.on("error",()=>t(-1)),o.on("exit",s=>t(s??-1)),o.unref()}catch{t(-1)}finally{typeof r=="number"&&G(r)}})}async function Ue(e){let n=e.env??process.env;if(Y(n,e.current))return"disabled";let t=e.dir??N(n),r=e.now??Date.now(),o=w(t),s=e.install??T();if(!le(o,r)){let f=o.failed??(s.kind==="flintmaker"||s.kind==="npm-global"?void 0:o.latest);return f&&P(f,e.current)?(e.notify(I(s,f),"info"),"hint"):"throttled"}let i=await(e.fetchLatest??R)();if(!i)return"offline";let c={...o,checkedAt:r,latest:i};return P(i,e.current)?!((e.run||j(s))&&$(s,i)!==null)||o.attempted===i?(p(c,t),e.notify(I(s,i),"info"),"hint"):(p({...c,attempted:i},t),await e.preload?.().catch(()=>{}),await(e.run??ge)(i,d().join(t,"update.log"))===0?(p({...c,attempted:i,installed:i,failed:void 0},t),e.notify(`Updated to v${i} \u2014 restart flint to use it`,"ok"),e.ready?.(i),"updated"):(p({...c,attempted:i,failed:i},t),e.notify(I(s,i),"info"),"failed")):(p({checkedAt:r,latest:i},t),"current")}async function je(e,n){let t=await R(15e3);if(!t)return n("Could not reach the npm registry. Check your connection and try again."),1;if(!P(t,e))return n(`flint is up to date (v${e}).`),p({...w(),checkedAt:Date.now(),latest:t}),0;let r=T();if(!j(r)||!$(r,t))return r.kind==="npm-global"?n(`v${t} is available, but ${A(r.prefix)} is not writable by you. Run: npm i -g ${x} (without sudo, from a user-owned Node such as nvm), or use the FlintMaker installer.`):n(I(r,t).replace(/^Update available /,"Available: ")),1;n(`Updating flint v${e} \u2192 v${t}\u2026`);let o=Z(r,t,"inherit"),s=o===0;return p({...w(),checkedAt:Date.now(),latest:t,attempted:t,...s?{installed:t,failed:void 0}:{failed:t}}),n(s?`Updated to v${t}.`:`Update failed (exit ${o}). Try: npm i -g ${x}`),s?0:1}var xe=1500,he=9e4,be=3600*1e3,B="FLINT_JUST_UPDATED",Q="FLINT_NO_UPDATE_CHECK_ONCE",ke=(e,n=j)=>(e.kind==="flintmaker"||e.kind==="npm-global")&&n(e);function ve(e){if(!e.interactive)return"not interactive";if(_(e.env[Q])||k(e.env[B]))return"just updated";let n=Y(e.env,e.current);return n||(e.updatable?null:"not updatable")}function Se(e,n,t,r,o=!1){if(!e||!P(e,n))return null;let s=t.failedAt!==void 0&&r-t.failedAt>=0&&r-t.failedAt<be;return!o&&t.failed===e&&s?null:e}var X=(e,n=process.platform)=>e.kind==="flintmaker"||e.kind==="npm-global"?d(n).join(A(e.prefix,n),x):null;function ee(e,n=process.platform){let t=X(e,n);if(!t)return null;try{return JSON.parse(U(d(n).join(t,"package.json"),"utf8"))}catch{return null}}function Pe(e,n=process.platform){let t=ee(e,n)?.version;return k(t)?t:null}function ye(e,n,t=process.platform){let r=X(e,t);return r?d(t).join(r,z(ee(e,t)?.bin)):n}function we(e){return{file:e.execPath,args:[...e.execArgv,e.entry,...e.argv],env:{...e.env,[B]:e.from,[Q]:"1"}}}var _e={SIGHUP:1,SIGINT:2,SIGKILL:9,SIGTERM:15};function Ie(e){return new Promise(n=>{let t;try{t=F(e.file,e.args,{stdio:"inherit",env:e.env})}catch{return n(-1)}let r=()=>{},o=a=>()=>{try{t.kill(a)}catch{}},s=o("SIGTERM"),i=o("SIGHUP");process.on("SIGINT",r),process.on("SIGTERM",s),g()||process.on("SIGHUP",i);let c=()=>{process.off("SIGINT",r),process.off("SIGTERM",s),process.off("SIGHUP",i)};t.on("error",()=>{c(),n(-1)}),t.on("exit",(a,l)=>{if(c(),l){try{process.kill(process.pid,l)}catch{}return n(128+(_e[l]??1))}n(a??1)})})}function Ee(e){return(n,t,r)=>{let o="ignore";try{o=K(t,"a"),y(o,`
19
+ [${new Date().toISOString()}] updating to ${x}@${n} (on start)
20
+ `)}catch{o="ignore"}return me(e,n,{logFd:o,timeoutMs:he,signal:r}).finally(()=>{typeof o=="number"&&G(o)})}}function Ne(e){return n=>Ie(we({execPath:process.execPath,execArgv:process.execArgv,entry:ye(e,process.argv[1]??""),argv:process.argv.slice(2),env:process.env,from:n}))}var Ae=e=>(process.on("SIGINT",e),()=>{process.off("SIGINT",e)});async function Re(e){let n=e.env??process.env,t=e.install??T(),r=e.updatable??ke(t),o=ve({interactive:e.interactive,env:n,current:e.current,updatable:r});if(o)return{status:"skipped",reason:o};let s=e.dir??N(n),i=e.now??Date.now(),c=w(s),a=await(e.fetchLatest??(h=>R(h)))(xe);if(!a)return{status:"offline"};if(!P(a,e.current))return p({checkedAt:i,latest:a},s),{status:"current",latest:a};let l=Se(a,e.current,c,i,e.force);if(!l)return{status:"backoff",latest:a};let f={...c,checkedAt:i,latest:a,attempted:l};p(f,s),await e.preload?.().catch(()=>{});let m=new AbortController,v=(e.onInterrupt??Ae)(()=>m.abort()),S=e.spinner?.(`Updating flint ${e.current} \u2192 ${l}\u2026`),u=-1;try{u=await(e.run??Ee(t))(l,d().join(s,"update.log"),m.signal)}finally{S?.(),v()}let b=u===0?(e.installed??(()=>Pe(t)))():null;return u!==0||!b||!P(b,e.current)?(p({...f,failed:l,failedAt:i},s),{status:m.signal.aborted?"cancelled":"failed",latest:l}):(p({...f,installed:b,failed:void 0,failedAt:void 0},s),{status:"reexec",code:await(e.reexec??Ne(t))(e.current),latest:b})}export{ae as CHECK_EVERY_MS,xe as FOREGROUND_CHECK_MS,he as FOREGROUND_INSTALL_MS,be as FOREGROUND_RETRY_MS,B as JUST_UPDATED_ENV,x as PACKAGE,se as REGISTRY_URL,Q as SKIP_ONCE_ENV,Ue as autoUpdate,ke as canSelfUpdate,ce as compareVersions,T as currentInstall,ue as detectInstall,ye as entryAfterInstall,R as fetchLatest,ve as foregroundSkip,Se as foregroundTarget,Re as foregroundUpdate,A as globalModules,Z as installVersion,me as installVersionAsync,Pe as installedVersion,P as isNewer,k as isVersion,z as launcherEntry,pe as launcherFiles,fe as launcherPaths,I as manualHint,w as readState,we as reexecSpec,ge as runDetached,Ie as runReexec,le as shouldCheck,N as stateDir,$ as updateCommand,Y as updateDisabled,je as updateNow,Fe as updateWorker,j as writable,q as writeLaunchers,p as writeState};
package/dist/flint.js CHANGED
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
- import{a as ne,b as D,c as ie,d as re,e as R}from"./chunks/chunk-EUPBID7K.js";import{e as F,f as N,h as se,i as le,s as ae}from"./chunks/chunk-2DDAUP6P.js";import{b as g,c as oe}from"./chunks/chunk-5PRYZOW7.js";import{c as V,e as G,f as I,g as B,h as X,i as K,j as $,k as J,l as Q,m as Z,o as ee,p as te}from"./chunks/chunk-K3ZZ2VJH.js";import{spawn as we,execFileSync as ye}from"node:child_process";import{existsSync as xe,lstatSync as be,realpathSync as H}from"node:fs";import{mkdir as ve,readdir as Ee,readFile as U,stat as ce,writeFile as ke}from"node:fs/promises";import{basename as fe,dirname as _e,join as z,relative as de,resolve as Pe,sep as $e}from"node:path";var C=class{diff(e,n,t={}){let i;typeof t=="function"?(i=t,t={}):"callback"in t&&(i=t.callback);let c=this.castInput(e,t),s=this.castInput(n,t),l=this.removeEmpty(this.tokenize(c,t)),r=this.removeEmpty(this.tokenize(s,t));return this.diffWithOptionsObj(l,r,t,i)}diffWithOptionsObj(e,n,t,i){var c;let s=u=>{if(u=this.postProcess(u,t),i){setTimeout(function(){i(u)},0);return}else return u},l=n.length,r=e.length,f=1,a=l+r;t.maxEditLength!=null&&(a=Math.min(a,t.maxEditLength));let d=(c=t.timeout)!==null&&c!==void 0?c:1/0,m=Date.now()+d,h=[{oldPos:-1,lastComponent:void 0}],w=this.extractCommon(h[0],n,e,0,t);if(h[0].oldPos+1>=r&&w+1>=l)return s(this.buildValues(h[0].lastComponent,n,e));let y=-1/0,x=1/0,E=()=>{for(let u=Math.max(y,-f);u<=Math.min(x,f);u+=2){let p,b=h[u-1],v=h[u+1];b&&(h[u-1]=void 0);let P=!1;if(v){let q=v.oldPos-u;P=v&&0<=q&&q<l}let L=b&&b.oldPos+1<r;if(!P&&!L){h[u]=void 0;continue}if(!L||P&&b.oldPos<v.oldPos?p=this.addToPath(v,!0,!1,0,t):p=this.addToPath(b,!1,!0,1,t),w=this.extractCommon(p,n,e,u,t),p.oldPos+1>=r&&w+1>=l)return s(this.buildValues(p.lastComponent,n,e))||!0;h[u]=p,p.oldPos+1>=r&&(x=Math.min(x,u-1)),w+1>=l&&(y=Math.max(y,u+1))}f++};if(i)(function u(){setTimeout(function(){if(f>a||Date.now()>m)return i(void 0);E()||u()},0)})();else for(;f<=a&&Date.now()<=m;){let u=E();if(u)return u}}addToPath(e,n,t,i,c){let s=e.lastComponent;return s&&!c.oneChangePerToken&&s.added===n&&s.removed===t?{oldPos:e.oldPos+i,lastComponent:{count:s.count+1,added:n,removed:t,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+i,lastComponent:{count:1,added:n,removed:t,previousComponent:s}}}extractCommon(e,n,t,i,c){let s=n.length,l=t.length,r=e.oldPos,f=r-i,a=0;for(;f+1<s&&r+1<l&&this.equals(t[r+1],n[f+1],c);)f++,r++,a++,c.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return a&&!c.oneChangePerToken&&(e.lastComponent={count:a,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=r,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 i=[],c;for(;e;)i.push(e),c=e.previousComponent,delete e.previousComponent,e=c;i.reverse();let s=i.length,l=0,r=0,f=0;for(;l<s;l++){let a=i[l];if(a.removed)a.value=this.join(t.slice(f,f+a.count)),f+=a.count;else{if(!a.added&&this.useLongestToken){let d=n.slice(r,r+a.count);d=d.map(function(m,h){let w=t[f+h];return w.length>m.length?w:m}),a.value=this.join(d)}else a.value=this.join(n.slice(r,r+a.count));r+=a.count,a.added||(f+=a.count)}}return i}};var M=class extends C{constructor(){super(...arguments),this.tokenize=he}equals(e,n,t){return t.ignoreWhitespace?((!t.newlineIsToken||!e.includes(`
2
+ import{a as ie,b as A,c as se,d as le,e as R}from"./chunks/chunk-EUPBID7K.js";import{e as V,f as T,g as I,i as ae,j as ce,l as de,v as fe}from"./chunks/chunk-NIG4OMDP.js";import{b as h,c as re}from"./chunks/chunk-5PRYZOW7.js";import{c as G,e as B,f as D,g as J,h as X,i as Q,j as P,k as Z,l as ee,m as te,o as ne,p as oe}from"./chunks/chunk-K3ZZ2VJH.js";import{spawn as $e,execFileSync as _e}from"node:child_process";import{existsSync as ke,lstatSync as Te,realpathSync as W}from"node:fs";import{mkdir as Pe,readdir as Ce,readFile as q,stat as ue,writeFile as Le}from"node:fs/promises";import{basename as me,dirname as Fe,join as Y,relative as pe,resolve as Se,sep as Ne}from"node:path";var C=class{diff(e,n,t={}){let i;typeof t=="function"?(i=t,t={}):"callback"in t&&(i=t.callback);let a=this.castInput(e,t),s=this.castInput(n,t),l=this.removeEmpty(this.tokenize(a,t)),r=this.removeEmpty(this.tokenize(s,t));return this.diffWithOptionsObj(l,r,t,i)}diffWithOptionsObj(e,n,t,i){var a;let s=f=>{if(f=this.postProcess(f,t),i){setTimeout(function(){i(f)},0);return}else return f},l=n.length,r=e.length,u=1,c=l+r;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,p=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(p[0],n,e,0,t);if(p[0].oldPos+1>=r&&m+1>=l)return s(this.buildValues(p[0].lastComponent,n,e));let v=-1/0,b=1/0,E=()=>{for(let f=Math.max(v,-u);f<=Math.min(b,u);f+=2){let g,x=p[f-1],y=p[f+1];x&&(p[f-1]=void 0);let k=!1;if(y){let K=y.oldPos-f;k=y&&0<=K&&K<l}let L=x&&x.oldPos+1<r;if(!k&&!L){p[f]=void 0;continue}if(!L||k&&x.oldPos<y.oldPos?g=this.addToPath(y,!0,!1,0,t):g=this.addToPath(x,!1,!0,1,t),m=this.extractCommon(g,n,e,f,t),g.oldPos+1>=r&&m+1>=l)return s(this.buildValues(g.lastComponent,n,e))||!0;p[f]=g,g.oldPos+1>=r&&(b=Math.min(b,f-1)),m+1>=l&&(v=Math.max(v,f+1))}u++};if(i)(function f(){setTimeout(function(){if(u>c||Date.now()>w)return i(void 0);E()||f()},0)})();else for(;u<=c&&Date.now()<=w;){let f=E();if(f)return f}}addToPath(e,n,t,i,a){let s=e.lastComponent;return s&&!a.oneChangePerToken&&s.added===n&&s.removed===t?{oldPos:e.oldPos+i,lastComponent:{count:s.count+1,added:n,removed:t,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+i,lastComponent:{count:1,added:n,removed:t,previousComponent:s}}}extractCommon(e,n,t,i,a){let s=n.length,l=t.length,r=e.oldPos,u=r-i,c=0;for(;u+1<s&&r+1<l&&this.equals(t[r+1],n[u+1],a);)u++,r++,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=r,u}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 i=[],a;for(;e;)i.push(e),a=e.previousComponent,delete e.previousComponent,e=a;i.reverse();let s=i.length,l=0,r=0,u=0;for(;l<s;l++){let c=i[l];if(c.removed)c.value=this.join(t.slice(u,u+c.count)),u+=c.count;else{if(!c.added&&this.useLongestToken){let d=n.slice(r,r+c.count);d=d.map(function(w,p){let m=t[u+p];return m.length>w.length?m:w}),c.value=this.join(d)}else c.value=this.join(n.slice(r,r+c.count));r+=c.count,c.added||(u+=c.count)}}return i}};var M=class extends C{constructor(){super(...arguments),this.tokenize=xe}equals(e,n,t){return t.ignoreWhitespace?((!t.newlineIsToken||!e.includes(`
3
3
  `))&&(e=e.trim()),(!t.newlineIsToken||!n.includes(`
4
4
  `))&&(n=n.trim())):t.ignoreNewlineAtEof&&!t.newlineIsToken&&(e.endsWith(`
5
5
  `)&&(e=e.slice(0,-1)),n.endsWith(`
6
- `)&&(n=n.slice(0,-1))),super.equals(e,n,t)}},me=new M;function j(o,e,n){return me.diff(o,e,n)}function he(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 i=0;i<t.length;i++){let c=t[i];i%2&&!e.newlineIsToken?n[n.length-1]+=c:n.push(c)}return n}function pe(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(!pe(o))return o;let e='"',n=new TextEncoder().encode(o),t=0;for(;t<n.length;){let i=n[t];i===7?e+="\\a":i===8?e+="\\b":i===9?e+="\\t":i===10?e+="\\n":i===11?e+="\\v":i===12?e+="\\f":i===13?e+="\\r":i===34?e+='\\"':i===92?e+="\\\\":i>=32&&i<=126?e+=String.fromCharCode(i):e+="\\"+i.toString(8).padStart(3,"0"),t++}return e+='"',e}var A={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function O(o,e,n,t,i,c,s){let l;s?typeof s=="function"?l={callback:s}:l=s:l={},typeof l.context>"u"&&(l.context=4);let r=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:a}=l;j(n,t,Object.assign(Object.assign({},l),{callback:d=>{let m=f(d);a(m)}}))}else return f(j(n,t,l));function f(a){if(!a)return;a.push({value:"",lines:[]});function d(u){return u.map(function(p){return" "+p})}let m=[],h=0,w=0,y=[],x=1,E=1;for(let u=0;u<a.length;u++){let p=a[u],b=p.lines||ge(p.value);if(p.lines=b,p.added||p.removed){if(!h){let v=a[u-1];h=x,w=E,v&&(y=r>0?d(v.lines.slice(-r)):[],h-=y.length,w-=y.length)}for(let v of b)y.push((p.added?"+":"-")+v);p.added?E+=b.length:x+=b.length}else{if(h)if(b.length<=r*2&&u<a.length-2)for(let v of d(b))y.push(v);else{let v=Math.min(b.length,r);for(let L of d(b.slice(0,v)))y.push(L);let P={oldStart:h,oldLines:x-h+v,newStart:w,newLines:E-w+v,lines:y};m.push(P),h=0,w=0,y=[]}x+=b.length,E+=b.length}}for(let u of m)for(let p=0;p<u.lines.length;p++)u.lines[p].endsWith(`
8
- `)?u.lines[p]=u.lines[p].slice(0,-1):(u.lines.splice(p+1,0,"\"),p++);return{oldFileName:o,newFileName:e,oldHeader:i,newHeader:c,hunks:m}}}function T(o,e){var n,t,i,c,s,l;if(e||(e=A),Array.isArray(o)){if(o.length>1&&!e.includeFileHeaders&&!o.every(a=>a.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(a=>T(a,e)).join(`
9
- `)}let r=[];if(o.isGit){if(e=A,!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 a=o.oldFileName,d=o.newFileName;o.isCreate&&a==="/dev/null"?a=d.replace(/^b\//,"a/"):o.isDelete&&d==="/dev/null"&&(d=a.replace(/^a\//,"b/")),r.push("diff --git "+k(a)+" "+k(d)),o.isDelete&&r.push("deleted file mode "+((n=o.oldMode)!==null&&n!==void 0?n:"100644")),o.isCreate&&r.push("new file mode "+((t=o.newMode)!==null&&t!==void 0?t:"100644")),o.oldMode&&o.newMode&&!o.isDelete&&!o.isCreate&&(r.push("old mode "+o.oldMode),r.push("new mode "+o.newMode)),o.isRename&&(r.push("rename from "+k(((i=o.oldFileName)!==null&&i!==void 0?i:"").replace(/^a\//,""))),r.push("rename to "+k(((c=o.newFileName)!==null&&c!==void 0?c:"").replace(/^b\//,"")))),o.isCopy&&(r.push("copy from "+k(((s=o.oldFileName)!==null&&s!==void 0?s:"").replace(/^a\//,""))),r.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&&r.push("Index: "+o.oldFileName),e.includeUnderline&&r.push("===================================================================");let f=o.hunks.length>0;e.includeFileHeaders&&o.oldFileName!==void 0&&o.newFileName!==void 0&&(!o.isGit||f)&&(r.push("--- "+k(o.oldFileName)+(o.oldHeader?" "+o.oldHeader:"")),r.push("+++ "+k(o.newFileName)+(o.newHeader?" "+o.newHeader:"")));for(let a=0;a<o.hunks.length;a++){let d=o.hunks[a],m=d.oldLines===0?d.oldStart-1:d.oldStart,h=d.newLines===0?d.newStart-1:d.newStart;r.push("@@ -"+m+","+d.oldLines+" +"+h+","+d.newLines+" @@");for(let w of d.lines)r.push(w)}return r.join(`
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 xe(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 i=0;i<t.length;i++){let a=t[i];i%2&&!e.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n}function ye(o){for(let e=0;e<o.length;e++)if(o[e]<" "||o[e]>"~"||o[e]==='"'||o[e]==="\\")return!0;return!1}function _(o){if(!ye(o))return o;let e='"',n=new TextEncoder().encode(o),t=0;for(;t<n.length;){let i=n[t];i===7?e+="\\a":i===8?e+="\\b":i===9?e+="\\t":i===10?e+="\\n":i===11?e+="\\v":i===12?e+="\\f":i===13?e+="\\r":i===34?e+='\\"':i===92?e+="\\\\":i>=32&&i<=126?e+=String.fromCharCode(i):e+="\\"+i.toString(8).padStart(3,"0"),t++}return e+='"',e}var O={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function U(o,e,n,t,i,a,s){let l;s?typeof s=="function"?l={callback:s}:l=s:l={},typeof l.context>"u"&&(l.context=4);let r=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=u(d);c(w)}}))}else return u(j(n,t,l));function u(c){if(!c)return;c.push({value:"",lines:[]});function d(f){return f.map(function(g){return" "+g})}let w=[],p=0,m=0,v=[],b=1,E=1;for(let f=0;f<c.length;f++){let g=c[f],x=g.lines||Ee(g.value);if(g.lines=x,g.added||g.removed){if(!p){let y=c[f-1];p=b,m=E,y&&(v=r>0?d(y.lines.slice(-r)):[],p-=v.length,m-=v.length)}for(let y of x)v.push((g.added?"+":"-")+y);g.added?E+=x.length:b+=x.length}else{if(p)if(x.length<=r*2&&f<c.length-2)for(let y of d(x))v.push(y);else{let y=Math.min(x.length,r);for(let L of d(x.slice(0,y)))v.push(L);let k={oldStart:p,oldLines:b-p+y,newStart:m,newLines:E-m+y,lines:v};w.push(k),p=0,m=0,v=[]}b+=x.length,E+=x.length}}for(let f of w)for(let g=0;g<f.lines.length;g++)f.lines[g].endsWith(`
8
+ `)?f.lines[g]=f.lines[g].slice(0,-1):(f.lines.splice(g+1,0,"\"),g++);return{oldFileName:o,newFileName:e,oldHeader:i,newHeader:a,hunks:w}}}function F(o,e){var n,t,i,a,s,l;if(e||(e=O),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 r=[];if(o.isGit){if(e=O,!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/")),r.push("diff --git "+_(c)+" "+_(d)),o.isDelete&&r.push("deleted file mode "+((n=o.oldMode)!==null&&n!==void 0?n:"100644")),o.isCreate&&r.push("new file mode "+((t=o.newMode)!==null&&t!==void 0?t:"100644")),o.oldMode&&o.newMode&&!o.isDelete&&!o.isCreate&&(r.push("old mode "+o.oldMode),r.push("new mode "+o.newMode)),o.isRename&&(r.push("rename from "+_(((i=o.oldFileName)!==null&&i!==void 0?i:"").replace(/^a\//,""))),r.push("rename to "+_(((a=o.newFileName)!==null&&a!==void 0?a:"").replace(/^b\//,"")))),o.isCopy&&(r.push("copy from "+_(((s=o.oldFileName)!==null&&s!==void 0?s:"").replace(/^a\//,""))),r.push("copy to "+_(((l=o.newFileName)!==null&&l!==void 0?l:"").replace(/^b\//,""))))}else e.includeIndex&&o.oldFileName==o.newFileName&&o.oldFileName!==void 0&&r.push("Index: "+o.oldFileName),e.includeUnderline&&r.push("===================================================================");let u=o.hunks.length>0;e.includeFileHeaders&&o.oldFileName!==void 0&&o.newFileName!==void 0&&(!o.isGit||u)&&(r.push("--- "+_(o.oldFileName)+(o.oldHeader?" "+o.oldHeader:"")),r.push("+++ "+_(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,p=d.newLines===0?d.newStart-1:d.newStart;r.push("@@ -"+w+","+d.oldLines+" +"+p+","+d.newLines+" @@");for(let m of d.lines)r.push(m)}return r.join(`
10
10
  `)+`
11
- `}function W(o,e,n,t,i,c,s){if(typeof s=="function"&&(s={callback:s}),s?.callback){let{callback:l}=s;O(o,e,n,t,i,c,Object.assign(Object.assign({},s),{callback:r=>{l(r?T(r,s.headerOptions):void 0)}}))}else{let l=O(o,e,n,t,i,c,s);return l?T(l,s?.headerOptions):void 0}}function ge(o){let e=o.endsWith(`
11
+ `}function H(o,e,n,t,i,a,s){if(typeof s=="function"&&(s={callback:s}),s?.callback){let{callback:l}=s;U(o,e,n,t,i,a,Object.assign(Object.assign({},s),{callback:r=>{l(r?F(r,s.headerOptions):void 0)}}))}else{let l=U(o,e,n,t,i,a,s);return l?F(l,s?.headerOptions):void 0}}function Ee(o){let e=o.endsWith(`
12
12
  `),n=o.split(`
13
13
  `).map(t=>t+`
14
- `);return e?n.pop():n.push(n.pop().slice(0,-1)),n}var Ce=new Set(["node_modules",".git","dist","build",".next",".nuxt",".svelte-kit","coverage",".venv","venv","__pycache__",".turbo",".cache","Pods","DerivedData"]),Le=/^(\.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,Te=/^\.env\.(example|sample|template)$/i,Se=1e5,Y=400,Fe=12e3,S=class{root;constructor(e){this.root=H(e)}resolve(e){if(typeof e!="string"||e.trim()==="")throw new Error("path is required");let n=e.trim(),t=G(n);if(t)throw new Error(t);let i=Pe(this.root,n);if(!I(this.root,i))throw new Error(`${n} is outside the project`);let c=this.root;for(let l of de(this.root,i).split($e).filter(Boolean)){c=z(c,l);let r;try{r=be(c)}catch{break}if(r.isSymbolicLink()){let f;try{f=H(c)}catch{throw new Error(`${n} goes through a broken symlink; refusing`)}if(!I(this.root,f))throw new Error(`${n} is outside the project`)}}let s=[B(fe(i))];if(V())try{s.push(fe(H.native(i)))}catch{}if(s.some(l=>Le.test(l)&&!Te.test(l)))throw new Error(`${n} looks like a secret file; flint does not read or change it`);return i}rel(e){return X(de(this.root,e))||"."}async listFiles(e="."){let n=this.resolve(e),t;try{t=ye("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,Y).join(`
15
- `)+(t.length>Y?`
16
- \u2026 ${t.length-Y} more files`:"")||"(empty)"}async walk(e,n){if(!(n.length>5e3))for(let t of await Ee(e,{withFileTypes:!0}))t.isDirectory()?Ce.has(t.name)||await this.walk(z(e,t.name),n):t.isFile()&&n.push(this.rel(z(e,t.name)))}async readFile(e,n,t){let i=this.resolve(e),c=await ce(i);if(!c.isFile())throw new Error(`${e} is not a file`);let s=await U(i);if(s.subarray(0,8e3).includes(0))return`[binary file, ${c.size} bytes]`;let l=s.toString("utf8").split(/\r?\n/);l.at(-1)===""&&l.pop();let r=Math.max(1,n??1),f=Math.min(l.length,t??l.length),a="";for(let d=r;d<=f;d++){let m=`${d} ${l[d-1]}`;if(a.length+m.length>Se){a+=`
17
- [truncated at line ${d-1} of ${l.length}; read more with start_line]`;break}a+=(a?`
18
- `:"")+m}return a}async search(e,n="."){let t;try{t=new RegExp(e)}catch{throw new Error("invalid regular expression")}let i=(await this.listFiles(n)).split(`
19
- `).filter(s=>s&&!s.startsWith("\u2026 ")),c=[];for(let s of i){if(c.length>=200)break;let l;try{let r=this.resolve(s);if((await ce(r)).size>4e5)continue;let f=await U(r);if(f.subarray(0,8e3).includes(0))continue;l=f.toString("utf8")}catch{continue}l.split(/\r?\n/).forEach((r,f)=>{c.length<200&&t.test(r)&&c.push(`${s}:${f+1}:${r.slice(0,300)}`)})}return c.join(`
20
- `)||"No matches."}async plan(e,n){let t=this.resolve(n.path),i=this.rel(t),c=xe(t)?await U(t,"utf8"):null,s=c!==null&&K(c)==="crlf",l=c!==null&&s?$(c):c,r;if(e==="write_file"){if(typeof n.content!="string")throw new Error("content is required");r=s?$(n.content):n.content}else{if(l===null)throw new Error(`${i} 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?$(n.old_text):n.old_text,m=s?$(n.new_text):n.new_text,h=l.split(d).length-1;if(h===0)throw new Error(`old_text not found in ${i}`);if(h>1)throw new Error(`old_text matches ${h} times in ${i}; include more context`);r=l.replace(d,()=>m)}let f=W(`a/${i}`,`b/${i}`,l??"",r,"","",{context:3}),a=s?J(r):r;return{path:i,diff:f,created:c===null,apply:async()=>{await ve(_e(t),{recursive:!0}),await ke(t,a)}}}runCommand(e,n=12e4,t){return new Promise(i=>{if(t?.aborted)return i("[interrupted by the user before it started]");let c=Q(e),s;try{s=we(c.file,c.args,{...c.options,cwd:this.root,env:{...process.env,FORCE_COLOR:"0",CI:"1"}})}catch(x){return i(`[could not run command: ${x.message}]`)}let l="",r="",f=0,a=x=>{let E=x.toString("utf8");if(l.length<4e3){let u=4e3-l.length;l+=E.slice(0,u),r+=E.slice(u)}else r+=E;r.length>8e3&&(f+=r.length-8e3,r=r.slice(-8e3))};s.stdout.on("data",a),s.stderr.on("data",a);let d=!1,m=!1,h=()=>Z(s.pid,process.platform,()=>s.kill("SIGKILL")),w=setTimeout(()=>{d=!0,h()},n),y=()=>{m=!0,h()};t?.addEventListener("abort",y,{once:!0}),s.on("close",x=>{clearTimeout(w),t?.removeEventListener("abort",y);let E=(l+(f?`
21
- [\u2026 ${f} characters omitted \u2026]
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=B(n);if(t)throw new Error(t);let i=Se(this.root,n);if(!D(this.root,i))throw new Error(`${n} is outside the project`);let a=this.root;for(let l of pe(this.root,i).split(Ne).filter(Boolean)){a=Y(a,l);let r;try{r=Te(a)}catch{break}if(r.isSymbolicLink()){let u;try{u=W(a)}catch{throw new Error(`${n} goes through a broken symlink; refusing`)}if(!D(this.root,u))throw new Error(`${n} is outside the project`)}}let s=[J(me(i))];if(G())try{s.push(me(W.native(i)))}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 i}rel(e){return X(pe(this.root,e))||"."}async listFiles(e="."){let n=this.resolve(e),t;try{t=_e("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 Ce(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 i=this.resolve(e),a=await ue(i);if(!a.isFile())throw new Error(`${e} is not a file`);let s=await q(i);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 r=Math.max(1,n??1),u=Math.min(l.length,t??l.length),c="";for(let d=r;d<=u;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 i=(await this.listFiles(n)).split(`
19
+ `).filter(s=>s&&!s.startsWith("\u2026 ")),a=[];for(let s of i){if(a.length>=200)break;let l;try{let r=this.resolve(s);if((await ue(r)).size>4e5)continue;let u=await q(r);if(u.subarray(0,8e3).includes(0))continue;l=u.toString("utf8")}catch{continue}l.split(/\r?\n/).forEach((r,u)=>{a.length<200&&t.test(r)&&a.push(`${s}:${u+1}:${r.slice(0,300)}`)})}return a.join(`
20
+ `)||"No matches."}async plan(e,n){let t=this.resolve(n.path),i=this.rel(t),a=ke(t)?await q(t,"utf8"):null,s=a!==null&&Q(a)==="crlf",l=a!==null&&s?P(a):a,r;if(e==="write_file"){if(typeof n.content!="string")throw new Error("content is required");r=s?P(n.content):n.content}else{if(l===null)throw new Error(`${i} 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?P(n.old_text):n.old_text,w=s?P(n.new_text):n.new_text,p=l.split(d).length-1;if(p===0)throw new Error(`old_text not found in ${i}`);if(p>1)throw new Error(`old_text matches ${p} times in ${i}; include more context`);r=l.replace(d,()=>w)}let u=H(`a/${i}`,`b/${i}`,l??"",r,"","",{context:3}),c=s?Z(r):r;return{path:i,diff:u,created:a===null,apply:async()=>{await Pe(Fe(t),{recursive:!0}),await Le(t,c)}}}runCommand(e,n=12e4,t){return new Promise(i=>{if(t?.aborted)return i("[interrupted by the user before it started]");let a=ee(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 i(`[could not run command: ${b.message}]`)}let l="",r="",u=0,c=b=>{let E=b.toString("utf8");if(l.length<4e3){let f=4e3-l.length;l+=E.slice(0,f),r+=E.slice(f)}else r+=E;r.length>8e3&&(u+=r.length-8e3,r=r.slice(-8e3))};s.stdout.on("data",c),s.stderr.on("data",c);let d=!1,w=!1,p=()=>te(s.pid,process.platform,()=>s.kill("SIGKILL")),m=setTimeout(()=>{d=!0,p()},n),v=()=>{w=!0,p()};t?.addEventListener("abort",v,{once:!0}),s.on("close",b=>{clearTimeout(m),t?.removeEventListener("abort",v);let E=(l+(u?`
21
+ [\u2026 ${u} characters omitted \u2026]
22
22
  `:"")+r).replace(/\r\n/g,`
23
- `),u=m?"[interrupted by the user]":d?`[timed out after ${Math.round(n/1e3)}s]`:`[exit code ${x}]`;i(`${E.slice(0,Fe)}
24
- ${u}`.trim())}),s.on("error",x=>{clearTimeout(w),t?.removeEventListener("abort",y),i(`[could not run command: ${x.message}]`)})})}};var _="0.2.1",Ne=()=>`
25
- ${g.ember("\u2726")} ${g.bold(oe("FlintMaker"))} ${g.bold("flint")} ${g.grey(`v${_}`)} ${g.grey("\u2014 the AI coding agent for your terminal")}
23
+ `),f=w?"[interrupted by the user]":d?`[timed out after ${Math.round(n/1e3)}s]`:`[exit code ${b}]`;i(`${E.slice(0,Me)}
24
+ ${f}`.trim())}),s.on("error",b=>{clearTimeout(m),t?.removeEventListener("abort",v),i(`[could not run command: ${b.message}]`)})})}};var $=V,je=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/,N=je.test(process.env.FLINT_JUST_UPDATED??"")?process.env.FLINT_JUST_UPDATED:null,Oe=!!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 Ue=()=>`
25
+ ${h.ember("\u2726")} ${h.bold(re("FlintMaker"))} ${h.bold("flint")} ${h.grey(`v${$}`)} ${h.grey("\u2014 the AI coding agent for your terminal")}
26
26
 
27
- ${g.bold("Usage")}
27
+ ${h.bold("Usage")}
28
28
  flint start an interactive session in this folder
29
29
  flint "task" do one task, then exit (plain output, good for scripts)
30
30
  flint login connect this computer to your FlintMaker account
@@ -32,25 +32,30 @@ ${u}`.trim())}),s.on("error",x=>{clearTimeout(w),t?.removeEventListener("abort",
32
32
  flint whoami show account and credits
33
33
  flint update update flint now (it also updates itself automatically)
34
34
 
35
- ${g.bold("Options")}
35
+ ${h.bold("Options")}
36
36
  --smart use the Smart model (paid plans, more credits)
37
37
  --plan plan only: read the project, change nothing
38
38
  --yes approve every change and command (careful!)
39
39
  --help, --version
40
40
 
41
- ${g.bold("In a session")}
41
+ ${h.bold("In a session")}
42
42
  /help /model /mode /clear /compact /credits /init /login /logout /exit
43
43
  @path attaches a file \xB7 shift+tab switches mode \xB7 esc interrupts
44
- `;function Ie(o){let e=new Set(o.filter(t=>t.startsWith("--"))),n=o.filter(t=>!t.startsWith("--"));return{flags:e,rest:n}}async function ue(){let o=new N(R(null));console.log();let e=await o.deviceLogin((n,t)=>{console.log(` ${g.ember("\u2726")} Your code: ${g.bold(g.gold(n))}`),console.log(` ${g.grey("Opening")} ${t}`),console.log(` ${g.grey("Approve it in the browser. Waiting\u2026")}`),ne(t)});ie({token:e.token,email:e.user.email,api:o.base}),console.log(`
45
- ${g.green("\u2713")} Signed in as ${g.bold(e.user.email)}. Run ${g.bold("flint")} in any project folder.
46
- `)}async function De(){let o="";process.stdin.setEncoding("utf8");for await(let e of process.stdin)o+=e;return o.trim()}function Re(){setTimeout(()=>{import("./chunks/update-YGHTGBDV.js").then(o=>o.autoUpdate({current:_,notify:e=>le(e),preload:()=>Promise.all([import("./chunks/repl-LUJ6BCT7.js"),import("./chunks/plain-EQXWFHTX.js"),import("./chunks/highlight-QJIBHZTN.js")])})).catch(()=>{})},200).unref()}async function Me(){if(!ee())for(let m of[process.stdout,process.stderr])m.isTTY&&te(m);let{flags:o,rest:e}=Ie(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(Ne());if(e[0]==="login")return ue();if(e[0]==="__update"&&e[1]){let{updateWorker:m}=await import("./chunks/update-YGHTGBDV.js");return m(e[1])}if(e[0]==="update"&&e.length===1){let{updateNow:m}=await import("./chunks/update-YGHTGBDV.js");return m(_,h=>console.log(` ${h}`))}if(e[0]==="logout")return re(),console.log(`
47
- Signed out. ${g.grey("Disconnect old terminals any time on your account page.")}
48
- `);let n=!!process.stdin.isTTY&&!!process.stdout.isTTY;if(!D()){if(!n)return process.stderr.write(`flint: not signed in. Run: flint login
49
- `),1;let{welcome:m,shortPath:h}=await import("./chunks/render-Q3KDKHPR.js"),{homedir:w}=await import("node:os"),y=Math.max(40,process.stdout.columns||80);console.log();let x={version:_,model:o.has("--smart")?"smart":"standard",cwd:h(process.cwd(),w(),28),status:"not signed in yet"};for(let E of m(x,y))console.log(E);console.log(`
50
- ${g.ember("\u2726")} Welcome to ${g.bold("flint")}. Let's connect your FlintMaker account (opening your browser):`),await ue()}let t=D(),i=R(t);if(i!==t.api)throw new F(`This token belongs to ${t.api}. Run flint login to use ${i}.`);let c=new N(i,t.token);if(e[0]==="whoami"){let m=await c.me();return console.log(`
51
- ${g.bold(m.user.email)} \xB7 ${m.user.plan} \xB7 ${ae(m.usage)}
52
- `)}let s=new S(process.cwd()),l=o.has("--smart")?"smart":"standard",r=o.has("--plan")?"plan":"ask",f=o.has("--yes");Re();let a=e.join(" ").trim();if(!a&&!process.stdin.isTTY&&(a=await De()),a||!n){if(!a)throw new F('Nothing to do. Pass a task: flint "fix the failing test"');let{oneShot:m}=await import("./chunks/plain-EQXWFHTX.js");return m(a,{client:c,ws:s,model:l,autoYes:f,mode:r})}let{interactive:d}=await import("./chunks/repl-LUJ6BCT7.js");await d({version:_,client:c,ws:s,model:l,autoYes:f,mode:r})}Me().then(o=>{typeof o=="number"&&o!==0&&(process.exitCode=o),setTimeout(()=>process.exit(),20).unref()},o=>{let e=se(o);process.stderr.write(`
53
- ${g.red("\u2717")} ${g.bold(e.title)}
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 he(){let o=new I(R(null));console.log();let e=await o.deviceLogin((n,t)=>{console.log(` ${h.ember("\u2726")} Your code: ${h.bold(h.gold(n))}`),console.log(` ${h.grey("Opening")} ${t}`),console.log(` ${h.grey("Approve it in the browser. Waiting\u2026")}`),ie(t)});se({token:e.token,email:e.user.email,api:o.base}),console.log(`
45
+ ${h.green("\u2713")} Signed in as ${h.bold(e.user.email)}. Run ${h.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 ge=()=>Promise.all([import("./chunks/repl-J2NVJC7D.js"),import("./chunks/plain-OGDYVC2R.js"),import("./chunks/highlight-QJIBHZTN.js"),import("./chunks/render-HTHFGYJZ.js")]);function qe(o){let e=!1,n=()=>import("./chunks/update-2THO6BFM.js").then(t=>t.autoUpdate({current:$,notify:i=>ce(i),preload:ge,ready:()=>{e=!0,de("Update ready \u2014 restart flint")}})).then(t=>{(t==="disabled"||t==="hint"||t==="failed")&&(e=!0)}).catch(()=>{});setTimeout(n,200).unref(),o&&import("./chunks/update-2THO6BFM.js").then(t=>{let i=setInterval(()=>e?clearInterval(i):void n(),t.CHECK_EVERY_MS+1e3);i.unref()}).catch(()=>{})}function we(o){let e=["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D","\u273B","\u2736","\u2733","\u2722"],n=0,t=()=>process.stdout.write(`\r ${h.ember(e[n++%e.length])} ${o}\x1B[K`);process.stdout.write("\x1B[?25l"),t();let i=setInterval(t,100);return()=>{clearInterval(i),process.stdout.write("\r\x1B[K\x1B[?25h")}}async function Ye(){if(Oe||N)return null;let o=await import("./chunks/update-2THO6BFM.js"),e=await o.foregroundUpdate({current:$,interactive:!0,spinner:we,preload:ge});return e.status==="reexec"?e.code??0:(e.status==="failed"&&console.log(` ${h.ember("\u2726")} ${h.grey(`Could not update to v${e.latest}; continuing with v${$}. Details: ${o.stateDir()}${process.platform==="win32"?"\\":"/"}update.log`)}`),e.status==="cancelled"&&console.log(` ${h.ember("\u2726")} ${h.grey(`Update skipped; continuing with v${$}.`)}`),null)}async function ve(o){let e=!!process.stdin.isTTY&&!!process.stdout.isTTY,n=await import("./chunks/update-2THO6BFM.js");if(e&&!N){let a=await n.foregroundUpdate({current:$,interactive:!0,force:!0,spinner:we});if(a.status==="reexec")return a.code??0}let t=n.currentInstall(),i=t.kind==="npx"?"npx flintmaker@latest":t.kind==="flintmaker"?"flint update":"npm i -g flintmaker@latest";return process.stderr.write(`
47
+ ${h.red("\u2717")} ${h.bold("flint needs an update")}
48
+ ${o.message}
49
+ Run: ${i}
50
+
51
+ `),1}async function ze(){if(!ne())for(let m of[process.stdout,process.stderr])m.isTTY&&oe(m);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(Ue());if(e[0]==="login")return he();if(e[0]==="__update"&&e[1]){let{updateWorker:m}=await import("./chunks/update-2THO6BFM.js");return m(e[1])}if(e[0]==="update"&&e.length===1){let{updateNow:m}=await import("./chunks/update-2THO6BFM.js");return m($,v=>console.log(` ${v}`))}if(e[0]==="logout")return le(),console.log(`
52
+ Signed out. ${h.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 m=await Ye();if(m!==null)return m}if(!A()){if(!n)return process.stderr.write(`flint: not signed in. Run: flint login
54
+ `),1;let{welcome:m,shortPath:v}=await import("./chunks/render-HTHFGYJZ.js"),{homedir:b}=await import("node:os"),E=Math.max(40,process.stdout.columns||80);console.log();let f={version:$,model:o.has("--smart")?"smart":"standard",cwd:v(process.cwd(),b(),28),status:"not signed in yet",updated:N?$:void 0};for(let g of m(f,E))console.log(g);console.log(`
55
+ ${h.ember("\u2726")} Welcome to ${h.bold("flint")}. Let's connect your FlintMaker account (opening your browser):`),await he()}let i=A(),a=R(i);if(a!==i.api)throw new T(`This token belongs to ${i.api}. Run flint login to use ${a}.`);let s=new I(a,i.token);if(e[0]==="whoami"){let m=await s.me();return console.log(`
56
+ ${h.bold(m.user.email)} \xB7 ${m.user.plan} \xB7 ${fe(m.usage)}
57
+ `)}let l=new S(process.cwd()),r=o.has("--smart")?"smart":"standard",u=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:m}=await import("./chunks/plain-OGDYVC2R.js");return m(d,{client:s,ws:l,model:r,autoYes:c,mode:u})}let{interactive:w}=await import("./chunks/repl-J2NVJC7D.js"),p=null;if(await w({version:$,client:s,ws:l,model:r,autoYes:c,mode:u,updated:N?$:void 0,onUpdateRequired:()=>p=new T(`FlintMaker no longer serves flint v${$}.`,"update_required",426)}),p)return ve(p)}ze().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=ae(o);process.stderr.write(`
58
+ ${h.red("\u2717")} ${h.bold(e.title)}
54
59
  ${e.lines.map(n=>` ${n}
55
60
  `).join("")}
56
61
  `),process.exit(1)});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "flintmaker",
3
- "version": "0.2.1",
4
- "description": "flint \u2014 the FlintMaker AI coding agent for your terminal.",
3
+ "version": "0.2.3",
4
+ "description": "flint — the FlintMaker AI coding agent for your terminal.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "PT Jiji Labs Digital",
7
7
  "homepage": "https://flintmaker.com",
@@ -1,23 +0,0 @@
1
- import{c as b,n as _}from"./chunk-K3ZZ2VJH.js";var S="Interrupted by the user before this finished.",h=class extends Error{},D={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 L(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),R(t.start_line),R(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 R=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0;function F(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 X(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 h))throw g;s=F(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,(D[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 L(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 $(){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 p=class extends Error{constructor(t,r="error",i=0){super(t);this.reason=r;this.status=i}reason;status},U=e=>e?new Date(e).toLocaleString(void 0,{weekday:"short",hour:"2-digit",minute:"2-digit"}):"soon";async function C(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 ${U(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);default:return new p(`Request failed (${e.status} ${t.reason??""})${r}`,t.reason??"error",e.status)}}var M=class{constructor(n,t){this.base=n;this.token=t}base;token;headers(){return{"content-type":"application/json","user-agent":"flint-cli",...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 C(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 h;if(!o.ok||!o.body)throw await C(o,this.base);let l=$(),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 A="https://flintmaker.com/pricing";function W(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 oe(e,n={}){let t=n.interactive?"Run /login to connect your FlintMaker account.":"Run: flint login",r=n.retry?[n.retry]:[];if(W(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: ${A}`],tone:"warn"};case"upgrade_required":return{title:"Smart needs a paid plan",lines:["Switch back with /model standard, or upgrade:",A],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"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 k=null,N=[];function ae(e){k?k(e):N.push(e)}function le(e){if(k=e,e)for(let n of N.splice(0))e(n)}import{readdirSync as q}from"node:fs";import{join as B,sep as z}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:"login",description:"Connect another FlintMaker account"},{name:"logout",description:"Disconnect this computer"},{name:"exit",description:"Quit flint",aliases:["quit","q"]}];function pe(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 G(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 me(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:G(e,i);s<t&&(t=s,n=r.name)}return t<=Math.max(2,Math.floor(e.length/3))?n:null}function ge(e){let n=e.replace(/^\//,"").toLowerCase();return y.filter(t=>t.name.startsWith(n)||t.aliases?.some(r=>r.startsWith(n)))}function he(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 J=new Set(["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__","DerivedData","Pods"]);function fe(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=q(B(e,r.split("/").join(z)),{withFileTypes:!0})}catch{return[]}return s.filter(o=>o.name.startsWith(i)&&!J.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 P(e){let n=new Set;for(let t of e.matchAll(/(?:^|\s)@((?:[\w.-]+\/)*[\w.-]+)/g))n.add(t[1]);return[...n]}import{readFileSync as I,statSync as Y}from"node:fs";import{join as K}from"node:path";var x="FLINT.md",j=2e4,f=e=>e.toLocaleString("en-US");function ke(e){return e.creditsLeftToday!==null?`${f(e.creditsLeftToday)} credits left today`:`${f(e.creditsLeftMonth)} credits left`}function ve(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: ${f(e.creditsLeftToday)} credits left (resets ${n(e.resetAt)})`),t.push(`This period: ${f(e.creditsLeftMonth)} of ${f(e.monthlyCredits)} credits left (resets ${n(e.monthResetAt)})`),t}var Ee={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"}},_e=`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.`,Te=`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.`,H="[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 V(e){let n=K(e,x);try{return Y(n).size>j?I(n,"utf8").slice(0,j)+`
16
- [truncated]`:I(n,"utf8")}catch{return null}}async function Re(e,n,t){let r=[],i=[],s=!1;if(t.first){i.push(_());let o=V(e.root);o&&(s=!0,i.push(`<project-memory file="${x}">
17
- ${o.trim()}
18
- </project-memory>`))}t.mode==="plan"&&i.push(H),i.push(n);for(let o of P(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"]),Q=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"]),O=new Set(["node","py","python","python3","ruby","perl","php","deno","bun","npx","pnpx","bunx"]);function $e(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&&Q.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()}`)||O.has(o)&&l===r||O.has(o)&&["npx","pnpx","bunx"].includes(o)?null:l}export{S as a,h as b,F as c,X as d,p as e,M as f,A as g,oe as h,ae as i,le as j,y as k,pe as l,me as m,ge as n,he as o,fe as p,x as q,f as r,ke as s,ve as t,Ee as u,_e as v,Te as w,Re as x,$e as y};
@@ -1,17 +0,0 @@
1
- import{c as u,d}from"./chunk-K3ZZ2VJH.js";import{spawn as z,spawnSync as Y}from"node:child_process";import{accessSync as O,chmodSync as K,closeSync as q,constants as F,existsSync as I,mkdirSync as T,openSync as G,readFileSync as U,realpathSync as Z,rmSync as B,writeFileSync as w}from"node:fs";import{homedir as D}from"node:os";var f="flintmaker",Q=`https://registry.npmjs.org/${f}/latest`,X=3600*1e3,_=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,x=n=>typeof n=="string"&&_.test(n);function nn(n,e){let r=_.exec(n),t=_.exec(e);if(!r||!t)return 0;for(let a=1;a<=3;a++){let l=Number(r[a])-Number(t[a]);if(l)return l>0?1:-1}let o=r[4],s=t[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]),m=/^\d+$/.test(c[a]);return l&&m?Number(i[a])>Number(c[a])?1:-1:l!==m?l?-1:1:i[a]>c[a]?1:-1}return 0}var v=(n,e)=>x(n)&&x(e)&&nn(n,e)>0,P=n=>!!n&&n!=="0"&&n.toLowerCase()!=="false";function en(n=process.env,e=""){return P(n.FLINT_NO_UPDATE)?"FLINT_NO_UPDATE is set":P(n.CI)?"running in CI":P(n.NO_UPDATE_NOTIFIER)?"NO_UPDATE_NOTIFIER is set":!x(e)||e.startsWith("0.0.0")?"development build":null}var $=(n=process.env)=>n.FLINT_UPDATE_DIR||d().join(D(),".flintmaker");function b(n=$()){try{let e=JSON.parse(U(d().join(n,"update.json"),"utf8"));return e&&typeof e=="object"?e:{}}catch{return{}}}function p(n,e=$()){try{T(e,{recursive:!0,mode:448}),w(d().join(e,"update.json"),JSON.stringify(n,null,2)+`
2
- `)}catch{}}var tn=(n,e=Date.now())=>!n.checkedAt||e-n.checkedAt>=X||n.checkedAt>e;function rn(n,e={}){let r=e.platform??process.platform,t=d(r),o=u(r),s=e.env??process.env,i=e.exists??I,c=g=>o?t.normalize(g).toLowerCase():t.normalize(g),a=(g,W)=>c(g).startsWith(c(W).replace(/[\\/]+$/,"")+t.sep),l=t.normalize(n);if(c(l).split(t.sep).includes("_npx"))return{kind:"npx"};let N=`${t.sep}node_modules${t.sep}${f}${t.sep}`,j=c(l).lastIndexOf(c(N));if(j<0)return{kind:"dev"};let J=l.slice(0,j+N.length-f.length-2),h=t.dirname(J),V=e.home??D(),M=t.join(V,".flintmaker");if(a(l,M))return{kind:"flintmaker",prefix:M};if(o){let g=s.APPDATA?t.join(s.APPDATA,"npm"):null;return g&&c(h)===c(g)||i(t.join(h,"npm.cmd"))||i(t.join(h,"node.exe"))?{kind:"npm-global",prefix:h}:{kind:"local"}}return t.basename(h)==="lib"?{kind:"npm-global",prefix:t.dirname(h)}:{kind:"local"}}var E=(n,e=process.platform)=>u(e)?d(e).join(n,"node_modules"):d(e).join(n,"lib","node_modules");function on(n,e){let r=d(e),t=r.dirname(n);return u(e)?r.join(t,"node_modules","npm","bin","npm-cli.js"):r.join(t,"..","lib","node_modules","npm","bin","npm-cli.js")}function S(n,e,r={}){if(n.kind!=="flintmaker"&&n.kind!=="npm-global"||!x(e))return null;let t=r.platform??process.platform,o=d(t),s=r.exists??I,i=["install","-g","--prefix",n.prefix,"--no-fund","--no-audit",`${f}@${e}`],c=[];n.kind==="flintmaker"&&c.push(u(t)?o.join(n.prefix,"node","node.exe"):o.join(n.prefix,"node","bin","node")),c.push(r.execPath??process.execPath);for(let a of c){let l=on(a,t);if(s(a)&&s(l))return{file:a,args:[l,...i],options:{windowsHide:!0}}}if(u(t)){let a=i.map(l=>/[\s&()^]/.test(l)?`"${l}"`:l).join(" ");return{file:r.env?.ComSpec||"cmd.exe",args:["/d","/s","/c",`"npm ${a}"`],options:{windowsVerbatimArguments:!0,windowsHide:!0}}}return{file:"npm",args:i,options:{}}}function H(n,e=process.platform){if(n.kind!=="flintmaker"&&n.kind!=="npm-global")return!1;try{return O(E(n.prefix,e),F.W_OK),u(e)||O(d(e).join(n.prefix,"bin"),F.W_OK),!0}catch{return!1}}function A(){try{return rn(Z(process.argv[1]??""))}catch{return{kind:"dev"}}}var k=(n,e)=>n.kind==="flintmaker"?`Update available v${e}: run flint update`:n.kind==="npx"?`Update available v${e}: run npx flintmaker@latest`:`Update available v${e}: run npm i -g ${f}`;async function C(n=3e3,e=process.env.FLINT_UPDATE_URL||Q){try{let r=await fetch(e,{signal:AbortSignal.timeout(n),headers:{accept:"application/json"}});if(!r.ok)return null;let t=await r.json();return x(t?.version)?t.version:null}catch{return null}}function sn(n){let e="dist/flint.js";if(typeof n=="string")e=n;else if(n&&typeof n=="object"){let r=n,t=r.flint??r.flintmaker??Object.values(r)[0];typeof t=="string"&&(e=t)}return e.replace(/^\.[\\/]/,"")}var y=["flint","flintmaker"];function an(n,e=process.platform){let r=d(e);return u(e)?y.flatMap(t=>["",".cmd",".ps1"].map(o=>r.join(n,t+o))):y.map(t=>r.join(n,"bin",t))}function cn(n,e,r=process.platform){let t=d(r);if(u(r)){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\\${e.replace(/\//g,"\\")}" %*`,""].join(`\r
3
- `);return y.map(c=>({path:t.join(n,`${c}.cmd`),content:i}))}let o=i=>i.replace(/[\\"$`]/g,"\\$&"),s=`#!/bin/sh
4
- # FlintMaker CLI launcher (written by https://flintmaker.com/install.sh)
5
- FM_HOME="${o(n)}"
6
- ENTRY="$FM_HOME/lib/node_modules/flintmaker/${o(e)}"
7
- if [ -x "$FM_HOME/node/bin/node" ]; then
8
- PATH="$FM_HOME/node/bin:$PATH"; export PATH
9
- exec "$FM_HOME/node/bin/node" "$ENTRY" "$@"
10
- fi
11
- if command -v node >/dev/null 2>&1; then exec node "$ENTRY" "$@"; fi
12
- echo "flint: Node.js 20+ is missing. Reinstall: curl -fsSL https://flintmaker.com/install.sh | sh" >&2
13
- exit 127
14
- `;return y.map(i=>({path:t.join(n,"bin",i),content:s,mode:493}))}function L(n){for(let e of an(n))B(e,{force:!0})}function ln(n,e=process.platform){let r=d(e),t;try{t=JSON.parse(U(r.join(E(n,e),f,"package.json"),"utf8")).bin}catch{}L(n);for(let o of cn(n,sn(t),e))T(r.dirname(o.path),{recursive:!0}),w(o.path,o.content,o.mode?{mode:o.mode}:{}),o.mode&&K(o.path,o.mode)}function R(n,e,r="inherit"){let t=S(n,e);if(!t)return-1;let o=n.kind==="flintmaker";o&&L(n.prefix);let s=-1;try{s=Y(t.file,t.args,{...t.options,stdio:["ignore",r,r],env:{...process.env,npm_config_update_notifier:"false"}}).status??-1}finally{if(o)try{ln(n.prefix)}catch(i){typeof r=="number"&&w(r,`could not write launchers: ${i.message}
15
- `),s=s===0?1:s}}return s}function gn(n){if(!x(n))return 2;let e=R(A(),n,"inherit");return p({...b(),attempted:n,...e===0?{installed:n,failed:void 0}:{failed:n}}),e}function dn(n,e){return new Promise(r=>{let t="ignore";try{t=G(e,"a"),w(t,`
16
- [${new Date().toISOString()}] updating to ${f}@${n}
17
- `)}catch{t="ignore"}try{let o=z(process.execPath,[process.argv[1],"__update",n],{detached:!0,windowsHide:!0,stdio:["ignore",t,t],env:{...process.env,FLINT_NO_UPDATE:"1"}});o.on("error",()=>r(-1)),o.on("exit",s=>r(s??-1)),o.unref()}catch{r(-1)}finally{typeof t=="number"&&q(t)}})}async function hn(n){let e=n.env??process.env;if(en(e,n.current))return"disabled";let r=n.dir??$(e),t=n.now??Date.now(),o=b(r),s=n.install??A();if(!tn(o,t)){let m=o.failed??(s.kind==="flintmaker"||s.kind==="npm-global"?void 0:o.latest);return m&&v(m,n.current)?(n.notify(k(s,m),"info"),"hint"):"throttled"}let i=await(n.fetchLatest??C)();if(!i)return"offline";let c={...o,checkedAt:t,latest:i};return v(i,n.current)?!((n.run||H(s))&&S(s,i)!==null)||o.attempted===i?(p(c,r),n.notify(k(s,i),"info"),"hint"):(p({...c,attempted:i},r),await n.preload?.().catch(()=>{}),await(n.run??dn)(i,d().join(r,"update.log"))===0?(p({...c,attempted:i,installed:i,failed:void 0},r),n.notify(`Updated to v${i} \u2014 restart flint to use it`,"ok"),"updated"):(p({...c,attempted:i,failed:i},r),n.notify(k(s,i),"info"),"failed")):(p({checkedAt:t,latest:i},r),"current")}async function xn(n,e){let r=await C(15e3);if(!r)return e("Could not reach the npm registry. Check your connection and try again."),1;if(!v(r,n))return e(`flint is up to date (v${n}).`),p({...b(),checkedAt:Date.now(),latest:r}),0;let t=A();if(!H(t)||!S(t,r))return t.kind==="npm-global"?e(`v${r} is available, but ${E(t.prefix)} is not writable by you. Run: npm i -g ${f} (without sudo, from a user-owned Node such as nvm), or use the FlintMaker installer.`):e(k(t,r).replace(/^Update available /,"Available: ")),1;e(`Updating flint v${n} \u2192 v${r}\u2026`);let o=R(t,r,"inherit"),s=o===0;return p({...b(),checkedAt:Date.now(),latest:r,attempted:r,...s?{installed:r,failed:void 0}:{failed:r}}),e(s?`Updated to v${r}.`:`Update failed (exit ${o}). Try: npm i -g ${f}`),s?0:1}export{X as CHECK_EVERY_MS,f as PACKAGE,Q as REGISTRY_URL,hn as autoUpdate,nn as compareVersions,A as currentInstall,rn as detectInstall,C as fetchLatest,E as globalModules,R as installVersion,v as isNewer,x as isVersion,sn as launcherEntry,cn as launcherFiles,an as launcherPaths,k as manualHint,b as readState,dn as runDetached,tn as shouldCheck,$ as stateDir,S as updateCommand,en as updateDisabled,xn as updateNow,gn as updateWorker,H as writable,ln as writeLaunchers,p as writeState};