localcode-agent 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/localcode.js +71 -71
  2. package/package.json +1 -1
package/dist/localcode.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import i,{useState,useRef,useEffect,useCallback}from'react';import {render,useApp,useInput,Box,Text}from'ink';import Z from'chalk';import Lt from'ink-text-input';import {readFile,mkdir,rm,copyFile,readdir,unlink,rename,writeFile,appendFile}from'fs/promises';import*as j from'fs';import {existsSync,readdirSync,statSync,cpSync}from'fs';import*as Pe from'path';import {join,resolve,basename,extname,dirname}from'path';import*as Ht from'os';import {exec,execSync}from'child_process';import {EventEmitter}from'events';import {promisify}from'util';import {createRequire}from'module';var Oo=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var St={llm:{provider:"ollama",model:"deepseek-coder:latest",baseURL:"http://localhost:11434",temperature:.1,maxTokens:8192},theme:"dark",fontSize:14,shell:process.platform==="win32"?"powershell.exe":process.platform==="darwin"?process.env.SHELL||"zsh":process.env.SHELL||"bash",workspaceDir:Ht.homedir(),security:{allowDangerousCommands:false,requireConfirmation:["rm -rf","sudo rm","shutdown","reboot","git push --force","git reset --hard","DROP TABLE","DROP DATABASE"]}},Xt=`You are LocalCode, an elite autonomous AI software engineering agent running inside a futuristic developer terminal. You analyze codebases, fix bugs, create features, run tests, and manage projects with surgical precision.
2
+ import i,{useState,useRef,useEffect,useCallback}from'react';import {render,useApp,useInput,Box,Text}from'ink';import V from'chalk';import {Transform}from'stream';import Mt from'ink-text-input';import {readFile,mkdir,rm,copyFile,readdir,unlink,rename,writeFile,appendFile}from'fs/promises';import*as U from'fs';import {existsSync,readdirSync,statSync,cpSync}from'fs';import*as Pe from'path';import {join,resolve,basename,extname,dirname}from'path';import*as Jt from'os';import {exec,execSync}from'child_process';import {EventEmitter}from'events';import {promisify}from'util';import {createRequire}from'module';var Ho=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var $t={llm:{provider:"ollama",model:"deepseek-coder:latest",baseURL:"http://localhost:11434",temperature:.1,maxTokens:8192},theme:"dark",fontSize:14,shell:process.platform==="win32"?"powershell.exe":process.platform==="darwin"?process.env.SHELL||"zsh":process.env.SHELL||"bash",workspaceDir:Jt.homedir(),security:{allowDangerousCommands:false,requireConfirmation:["rm -rf","sudo rm","shutdown","reboot","git push --force","git reset --hard","DROP TABLE","DROP DATABASE"]}},Vt=`You are LocalCode, an elite autonomous AI software engineering agent running inside a futuristic developer terminal. You analyze codebases, fix bugs, create features, run tests, and manage projects with surgical precision.
3
3
 
4
4
  ## IMPORTANT: When NOT to use tools
5
5
 
@@ -105,7 +105,7 @@ When you need to take an action, respond with ONLY a JSON object in this exact f
105
105
  When the task is fully complete, respond with exactly:
106
106
  DONE: [Clear summary of all changes made and results]
107
107
 
108
- The word DONE: must be at the very start of your final response.`;var Gt=`You are LocalCode in PLAN MODE. Your job is to think deeply and produce a clear, structured implementation plan \u2014 do NOT call any tools or execute anything.
108
+ The word DONE: must be at the very start of your final response.`;var Qt=`You are LocalCode in PLAN MODE. Your job is to think deeply and produce a clear, structured implementation plan \u2014 do NOT call any tools or execute anything.
109
109
 
110
110
  Analyze the request and respond with a detailed plan in this format:
111
111
 
@@ -124,89 +124,89 @@ List of all files that will be changed.
124
124
  ## Open questions
125
125
  Any ambiguities or decisions that need user input before starting.
126
126
 
127
- End with: DONE: <one-line summary of the plan>`,qt=30,Ve=[{cmd:"/plugin",description:"Manage plugins (list/install/remove/reload)"},{cmd:"/plugin install ",description:"Install plugin from path"},{cmd:"/plugin remove ",description:"Remove plugin by name"},{cmd:"/plugin reload",description:"Reload all plugins"},{cmd:"/connect",description:"Connect to server (popup)"},{cmd:"/model",description:"Select model (popup)"},{cmd:"/attach",description:"Attach file or image (@-picker)"},{cmd:"/compact",description:"Summarize & compress conversation"},{cmd:"/session",description:"List saved sessions"},{cmd:"/session save ",description:"Save session as <name>"},{cmd:"/session load ",description:"Load session <name>"},{cmd:"/session delete ",description:"Delete session <name>"},{cmd:"/config",description:"Show current configuration"},{cmd:"/config model ",description:"Switch model"},{cmd:"/config provider ollama",description:"Use Ollama (localhost:11434)"},{cmd:"/config provider lmstudio",description:"Use LM Studio (localhost:1234)"},{cmd:"/config url ",description:"Set base URL"},{cmd:"/help",description:"Show help"},{cmd:"/lsp",description:"Run diagnostics (tsc/cargo/pylint/eslint)"},{cmd:"/models",description:"List available models"},{cmd:"/doctor",description:"Check system status"},{cmd:"/clear",description:"Clear screen"},{cmd:"/exit",description:"Quit"}],lt=["fix auth bug","fix typescript errors","analyze architecture","explain this codebase","create REST API for users","add unit tests","optimize database queries","refactor api layer","scan for security issues","create nextjs dashboard","run tests","explain docker-compose.yml"];var jo=["\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 ","\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],Uo=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],Jt=["Start inside a project folder so the agent has codebase context","Run shell commands directly: $ npm test or ! git status","LM Studio: /config provider lmstudio | Ollama: /config provider ollama","Try: fix auth bug \xB7 analyze architecture \xB7 add unit tests","Drag & drop a file into the terminal to attach it automatically","Type @filename to attach a file inline \u2014 e.g. @src/app.ts explain this","Use /model to browse and switch models from the running server","Tab autocompletes commands or toggles BUILD \u2194 PLAN mode","/compact summarizes long conversations to free up context window","/session save <name> to bookmark a conversation, /session load to resume","/doctor checks your LLM connection and shows current configuration","Plan before you build: tab to switch to PLAN mode, then describe the feature"];function Wo(r,e){if(r.length<2)return "";let o=e.find(s=>s!==r&&s.toLowerCase().startsWith(r.toLowerCase()));if(o)return o.slice(r.length);let t=Ve.find(s=>s.cmd.startsWith(r)&&s.cmd!==r);if(t)return t.cmd.slice(r.length);let n=lt.find(s=>s.startsWith(r)&&s!==r);return n?n.slice(r.length):""}var Vt=({config:r,history:e,onSubmit:o})=>{let[t,n]=useState(""),[s,l]=useState(-1),c=Jt[new Date().getDate()%Jt.length],a=Wo(t,e);useInput((y,x)=>{if(x.tab&&a){n(t+a);return}if(x.upArrow){let S=Math.min(s+1,e.length-1);l(S),e[S]&&n(e[S]);}if(x.downArrow){let S=Math.max(s-1,-1);l(S),n(S===-1?"":e[S]||"");}x.escape&&(n(""),l(-1));});let u=useCallback(y=>{n(y),l(-1);},[]),d=useCallback(y=>{y.trim()&&(l(-1),o(y.trim()),n(""));},[o]),p=Math.max(1,Math.floor((process.stdout.rows||24)/2)-10);return i.createElement(Box,{flexDirection:"column",alignItems:"center"},Array.from({length:p}).map((y,x)=>i.createElement(Text,{key:x}," ")),jo.map((y,x)=>i.createElement(Box,{key:x},i.createElement(Text,{color:"#d8d8d8"},y),i.createElement(Text,{color:"#3B82F6"},Uo[x]))),i.createElement(Text,null," "),i.createElement(Box,{flexDirection:"column",borderStyle:"single",borderColor:"#1E3A5F",minWidth:60},i.createElement(Box,{paddingX:1},i.createElement(Text,{color:"#3B82F6",bold:true},"> "),i.createElement(Lt,{value:t,onChange:u,onSubmit:d,placeholder:"ask anything \xB7 / for commands \xB7 @ to attach"}),a&&i.createElement(Text,{color:"#1F2937"},a)),i.createElement(Box,{paddingX:1,justifyContent:"space-between"},i.createElement(Box,null,i.createElement(Text,{color:"#4B5563"},"\u21B5 "),i.createElement(Text,{color:"#6B7280"},"send "),i.createElement(Text,{color:"#4B5563"},"tab "),i.createElement(Text,{color:"#6B7280"},a?"complete":"autocomplete")),i.createElement(Box,null,i.createElement(Text,{backgroundColor:"#1D4ED8",color:"#BFDBFE"}," BUILD "),i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#9CA3AF"},r.llm.model.length>20?r.llm.model.slice(0,20)+"\u2026":r.llm.model)))),i.createElement(Box,{paddingLeft:2,marginTop:1},i.createElement(Text,{color:"#4B5563"},"\u2191\u2193 "),i.createElement(Text,{color:"#6B7280"},"history "),i.createElement(Text,{color:"#4B5563"},"@ "),i.createElement(Text,{color:"#6B7280"},"attach "),i.createElement(Text,{color:"#4B5563"},"ctrl+c "),i.createElement(Text,{color:"#6B7280"},"quit")),i.createElement(Text,null," "),i.createElement(Box,{paddingLeft:2},i.createElement(Text,{color:"#F59E0B",bold:true},"\u25CF Tip "),i.createElement(Text,{color:"#4B5563"},c)))};var Kt=process.env.HOME||process.env.USERPROFILE||"";function Xo(r){try{return execSync("git rev-parse --abbrev-ref HEAD",{cwd:r,stdio:["ignore","pipe","ignore"],timeout:800}).toString().trim()}catch{return ""}}var Go={idle:"",running:"#1D4ED8",thinking:"#92400E",error:"#7F1D1D"},Zt={idle:"",running:"RUNNING",thinking:"THINKING",error:"ERROR"},wt=({config:r,cwd:e,agentStatus:o,tokenCount:t,mode:n="build"})=>{let s=useRef(""),l=useRef("");l.current!==e&&(l.current=e,s.current=Xo(e));let c=e.startsWith(Kt)?e.replace(Kt,"~"):e,a=s.current;return i.createElement(Box,{justifyContent:"space-between"},i.createElement(Box,null,i.createElement(Text,{bold:true,color:"#60A5FA"},"localcode "),i.createElement(Text,{color:"#374151"},"v0.1.0 "),i.createElement(Text,{color:"#6B7280"},c),a&&i.createElement(Text,{color:"#4B5563"}," (",a,")"),t>0&&i.createElement(Text,{color:"#374151"}," ~",t,"t")),i.createElement(Box,null,Zt[o]&&i.createElement(Text,{backgroundColor:Go[o],color:"#BFDBFE"}," ",Zt[o]," "),i.createElement(Text,{color:"#374151"}," tab "),i.createElement(Text,{backgroundColor:n==="plan"?"#166534":"#1D4ED8",color:n==="plan"?"#86EFAC":"#BFDBFE"}," ",n==="plan"?"PLAN MODE":"BUILD MODE"," ")))};var Rt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],at=({label:r="Thinking"})=>{let[e,o]=useState(0);return useEffect(()=>{let t=setInterval(()=>o(n=>(n+1)%Rt.length),80);return ()=>clearInterval(t)},[]),i.createElement(Text,{color:"#3B82F6"},Rt[e]," ",r,"...")};var Ct=({filePath:r,oldLines:e,newLines:o,startLine:t,contextBefore:n,contextAfter:s})=>{let l=[],c=t-n.length;n.forEach((d,p)=>{let y=c+p;l.push({type:"context",content:d,left:y,right:y});});let a=t,u=t;return e.forEach(d=>l.push({type:"removed",content:d,left:a++,right:null})),o.forEach(d=>l.push({type:"added",content:d,left:null,right:u++})),s.forEach((d,p)=>l.push({type:"context",content:d,left:a+p,right:u+p})),i.createElement(Box,{flexDirection:"column",marginY:1,marginX:1},i.createElement(Box,{paddingX:2,paddingY:0},i.createElement(Text,{color:"#6B7280"},"Edit "),i.createElement(Text,{color:"#9CA3AF"},r)),i.createElement(Box,{flexDirection:"column",borderStyle:"single",borderColor:"#374151"},l.map((d,p)=>{let y=d.left!==null?String(d.left).padStart(4):" ",x=d.right!==null?String(d.right).padStart(4):" ";return d.type==="removed"?i.createElement(Box,{key:p},i.createElement(Text,{color:"#EF4444"}," ",y," "),i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#EF4444"}," - "),i.createElement(Text,{color:"#FCA5A5"},d.content)):d.type==="added"?i.createElement(Box,{key:p},i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#22C55E"}," ",x," "),i.createElement(Text,{color:"#22C55E"}," + "),i.createElement(Text,{color:"#86EFAC"},d.content)):i.createElement(Box,{key:p},i.createElement(Text,{color:"#4B5563"}," ",y," "),i.createElement(Text,{color:"#4B5563"}," ",x," "),i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#6B7280"},d.content))})))};var At=({text:r})=>{let e=[],o=r;for(;o;){let t=o.match(/^`([^`]*)`/);if(t){e.push({t:t[1],code:true}),o=o.slice(t[0].length);continue}let n=o.match(/^\*\*([^*]+)\*\*/);if(n){e.push({t:n[1],bold:true}),o=o.slice(n[0].length);continue}let s=o.match(/^\*([^*]+)\*/);if(s){e.push({t:s[1],italic:true}),o=o.slice(s[0].length);continue}let l=o.search(/`|\*\*|\*(?!\*)/);if(l===-1){e.push({t:o});break}if(l===0){e.push({t:o[0]}),o=o.slice(1);continue}e.push({t:o.slice(0,l)}),o=o.slice(l);}return i.createElement(i.Fragment,null,e.map((t,n)=>t.code?i.createElement(Text,{key:n,color:"#7DD3FC"},t.t):t.bold?i.createElement(Text,{key:n,bold:true,color:"#E5E7EB"},t.t):t.italic?i.createElement(Text,{key:n,color:"#D1D5DB",italic:true},t.t):i.createElement(Text,{key:n,color:"#D1D5DB"},t.t)))},Bt=({content:r})=>{let e=r.split(`
128
- `),o=[],t=false,n="",s=[],l=c=>{o.push(i.createElement(Box,{key:c,flexDirection:"column"},n&&i.createElement(Box,null,i.createElement(Text,{color:"#1D4ED8"}," \u250C\u2500 "),i.createElement(Text,{color:"#60A5FA"},n)),s.map((a,u)=>i.createElement(Box,{key:u},i.createElement(Text,{color:"#374151"}," \u2502 "),i.createElement(Text,{color:"#7DD3FC",wrap:"wrap"},a||" "))),i.createElement(Text,{color:"#1D4ED8"}," \u2514","\u2500".repeat(Math.min(40,Math.max(8,...s.map(a=>a.length+1))))))),s=[],n="";};for(let c=0;c<e.length;c++){let a=e[c];if(a.startsWith("```")){t?(t=false,l(`c${c}`)):(t=true,n=a.slice(3).trim());continue}if(t){s.push(a);continue}if(a.startsWith("### "))o.push(i.createElement(Text,{key:c,bold:true,color:"#93C5FD",wrap:"wrap"},a.slice(4)));else if(a.startsWith("## "))o.push(i.createElement(Text,{key:c,bold:true,color:"#60A5FA",wrap:"wrap"},a.slice(3)));else if(a.startsWith("# "))o.push(i.createElement(Text,{key:c,bold:true,color:"#3B82F6",wrap:"wrap"},a.slice(2)));else if(/^[-*+] /.test(a))o.push(i.createElement(Box,{key:c},i.createElement(Text,{color:"#6B7280"}," \u2022 "),i.createElement(Box,{flexWrap:"wrap"},i.createElement(At,{text:a.slice(2)}))));else if(/^\d+\. /.test(a)){let u=a.match(/^(\d+)\. (.*)/);o.push(i.createElement(Box,{key:c},i.createElement(Text,{color:"#6B7280"}," ",u[1],". "),i.createElement(Box,{flexWrap:"wrap"},i.createElement(At,{text:u[2]}))));}else /^---+$/.test(a.trim())?o.push(i.createElement(Text,{key:c,color:"#374151"},"\u2500".repeat(48))):a.trim()?o.push(i.createElement(Box,{key:c,flexWrap:"wrap"},i.createElement(At,{text:a}))):o.push(i.createElement(Text,{key:c}," "));}return t&&s.length&&l("end"),i.createElement(Box,{flexDirection:"column"},o)};var eo=[{id:"ollama",label:"Ollama",defaultPort:"11434",urlSuffix:""},{id:"lmstudio",label:"LM Studio",defaultPort:"1234",urlSuffix:"/v1"}],to=({onConnect:r,onCancel:e})=>{let[o,t]=useState("provider"),[n,s]=useState(""),[l,c]=useState(0),[a,u]=useState(eo[0]),[d,p]=useState("localhost"),[y,x]=useState("11434"),S=eo.filter(T=>T.label.toLowerCase().includes(n.toLowerCase())||T.id.toLowerCase().includes(n.toLowerCase()));useInput((T,$)=>{if(o==="provider"){if($.upArrow){c(b=>Math.max(0,b-1));return}if($.downArrow){c(b=>Math.min(S.length-1,b+1));return}if($.escape){e();return}if($.return){let b=S[Math.min(l,S.length-1)];if(!b)return;u(b),p("localhost"),x(b.defaultPort),t("ip");return}}if(o==="ip"){if($.escape){t("provider");return}if($.return){t("port");return}}if(o==="port"){if($.escape){t("ip");return}if($.return){let b=a.id,J=`http://${d}:${y}${a.urlSuffix}`;r(b,J);return}}});let G=o==="provider"?"\u203A Choose provider":o==="ip"?`\u203A ${a.label} \u203A IP address`:`\u203A ${a.label} \u203A Port`;return i.createElement(Box,{flexDirection:"column",borderStyle:"round",borderColor:"#3B82F6",marginX:1},i.createElement(Box,{paddingX:2},i.createElement(Text,{color:"#3B82F6",bold:true}," Connect "),i.createElement(Text,{color:"#4B5563"},G)),o==="provider"&&i.createElement(i.Fragment,null,i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#1E3A5F"},i.createElement(Text,{color:"#6B7280"},"/ "),i.createElement(Lt,{value:n,onChange:T=>{s(T),c(0);},placeholder:"Search provider ...",focus:true})),S.length===0?i.createElement(Box,{paddingX:4},i.createElement(Text,{color:"#6B7280"},"No provider found")):S.map((T,$)=>{let b=$===l;return i.createElement(Box,{key:T.id,paddingX:2},i.createElement(Text,{color:b?"#3B82F6":"#374151"},b?"\u25B6 ":" "),i.createElement(Text,{color:b?"#93C5FD":"#9CA3AF",bold:b},T.label),i.createElement(Text,{color:b?"#4B5563":"#2D3748"}," :",T.defaultPort))})),o==="ip"&&i.createElement(Box,{paddingX:2,paddingY:1,flexDirection:"column"},i.createElement(Text,{color:"#6B7280"},"IP address:"),i.createElement(Box,{marginTop:1,borderStyle:"single",borderColor:"#1E3A5F",paddingX:1},i.createElement(Lt,{value:d,onChange:p,focus:true}))),o==="port"&&i.createElement(Box,{paddingX:2,paddingY:1,flexDirection:"column"},i.createElement(Text,{color:"#6B7280"},"Port:"),i.createElement(Box,{marginTop:1,borderStyle:"single",borderColor:"#1E3A5F",paddingX:1},i.createElement(Lt,{value:y,onChange:x,focus:true}))),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#1E3A5F"},o==="provider"?i.createElement(i.Fragment,null,i.createElement(Text,{color:"#374151"},"\u2191\u2193 "),i.createElement(Text,{color:"#4B5563"},"select "),i.createElement(Text,{color:"#374151"},"enter "),i.createElement(Text,{color:"#4B5563"},"next "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"close")):o==="ip"?i.createElement(i.Fragment,null,i.createElement(Text,{color:"#374151"},"enter "),i.createElement(Text,{color:"#4B5563"},"next "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"back")):i.createElement(i.Fragment,null,i.createElement(Text,{color:"#22C55E"},"enter "),i.createElement(Text,{color:"#4B5563"},"connect "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"back"))))};var ro=({models:r,loading:e,currentModel:o,onSelect:t,onCancel:n})=>{let[s,l]=useState(""),[c,a]=useState(0),u=r.filter(p=>p.toLowerCase().includes(s.toLowerCase()));useInput((p,y)=>{if(e){if(y.escape){n();return}return}if(y.upArrow){a(x=>Math.max(0,x-1));return}if(y.downArrow){a(x=>Math.min(u.length-1,x+1));return}if(y.escape){n();return}if(y.return){let x=u[Math.min(c,u.length-1)];x&&t(x);return}});let d=u.slice(0,8);return i.createElement(Box,{flexDirection:"column",borderStyle:"round",borderColor:"#6366F1",marginX:1},i.createElement(Box,{paddingX:2},i.createElement(Text,{color:"#6366F1",bold:true}," Model "),i.createElement(Text,{color:"#4B5563"},"\u203A Select a model "),i.createElement(Text,{color:"#374151"},"current: "),i.createElement(Text,{color:"#9CA3AF"},o)),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#312E81"},i.createElement(Text,{color:"#6B7280"},"/ "),i.createElement(Lt,{value:s,onChange:p=>{l(p),a(0);},placeholder:"Search model ...",focus:!e})),e?i.createElement(Box,{paddingX:4,paddingY:1},i.createElement(Text,{color:"#6B7280"},"Loading models from server ...")):d.length===0?i.createElement(Box,{paddingX:4,paddingY:1},i.createElement(Text,{color:"#6B7280"},r.length===0?"No models found \u2014 is the server reachable?":"No matches")):d.map((p,y)=>{let x=y===c;return i.createElement(Box,{key:p,paddingX:2},i.createElement(Text,{color:x?"#6366F1":"#374151"},x?"\u25B6 ":" "),p===o?i.createElement(Text,{color:x?"#A5B4FC":"#6366F1",bold:true},"\u2713 ",p):i.createElement(Text,{color:x?"#A5B4FC":"#9CA3AF"}," ",p))}),u.length>8&&i.createElement(Box,{paddingX:4},i.createElement(Text,{color:"#374151"},"\u2026 ",u.length-8," more (refine search)")),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#312E81"},i.createElement(Text,{color:"#374151"},"\u2191\u2193 "),i.createElement(Text,{color:"#4B5563"},"select "),i.createElement(Text,{color:"#374151"},"enter "),i.createElement(Text,{color:"#4B5563"},"apply "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"close")))};var tr=new Set([".jpg",".jpeg",".png",".gif",".webp",".bmp",".svg"]),so=({files:r,onSelect:e,onCancel:o})=>{let[t,n]=useState(""),[s,l]=useState(0),c=r.filter(a=>a.toLowerCase().includes(t.toLowerCase())).slice(0,8);return useInput((a,u)=>{if(u.upArrow){l(d=>Math.max(0,d-1));return}if(u.downArrow){l(d=>Math.min(c.length-1,d+1));return}if(u.escape){o();return}if(u.return){let d=c[Math.min(s,c.length-1)];d&&e(d);return}}),i.createElement(Box,{flexDirection:"column",borderStyle:"round",borderColor:"#22C55E",marginX:1},i.createElement(Box,{paddingX:2},i.createElement(Text,{color:"#22C55E",bold:true}," @ Attach "),i.createElement(Text,{color:"#4B5563"},"\u203A Datei oder Bild ausw\xE4hlen")),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#15803D"},i.createElement(Text,{color:"#6B7280"},"/ "),i.createElement(Lt,{value:t,onChange:a=>{n(a),l(0);},placeholder:"Search file...",focus:true})),c.length===0?i.createElement(Box,{paddingX:4,paddingY:1},i.createElement(Text,{color:"#6B7280"},"No files found")):c.map((a,u)=>{let d=u===s,p=tr.has(extname(a).toLowerCase());return i.createElement(Box,{key:a,paddingX:2},i.createElement(Text,{color:d?"#22C55E":"#374151"},d?"\u25B6 ":" "),i.createElement(Text,{color:d?"#86EFAC":"#9CA3AF"},p?"[img] ":"[file] ",a))}),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#15803D"},i.createElement(Text,{color:"#374151"},"\u2191\u2193 "),i.createElement(Text,{color:"#4B5563"},"select "),i.createElement(Text,{color:"#374151"},"enter "),i.createElement(Text,{color:"#4B5563"},"attach "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"close")))};var ct=class{async stream(e,o,t){let n=o.baseURL||"http://localhost:11434",s="",l=await fetch(`${n}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:o.model||"deepseek-coder",messages:e.map(u=>{let d={role:u.role,content:u.content};return u.images?.length&&(d.images=u.images),d}),stream:true,options:{temperature:o.temperature??.1,num_predict:o.maxTokens??8192}})});if(!l.ok){let u=await l.text();throw new Error(`Ollama error ${l.status}: ${u}`)}let c=l.body.getReader(),a=new TextDecoder;for(;;){let{done:u,value:d}=await c.read();if(u)break;let p=a.decode(d,{stream:true});for(let y of p.split(`
129
- `).filter(x=>x.trim()))try{let x=JSON.parse(y),S=x.message?.content||"";if(S&&(t(S),s+=S),x.done)return s}catch{}}return s}async listModels(e="http://localhost:11434"){try{let o=await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(5e3)});return o.ok?((await o.json()).models||[]).map(n=>n.name):[]}catch{return []}}async checkHealth(e="http://localhost:11434"){try{return (await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(3e3)})).ok}catch{return false}}};var $t="http://localhost:1234/v1",ut=class{async stream(e,o,t){let n=(o.baseURL||$t).replace(/\/$/,""),s="",l=await fetch(`${n}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:o.model,messages:e.map(d=>d.images?.length?{role:d.role,content:[{type:"text",text:d.content},...d.images.map(p=>({type:"image_url",image_url:{url:`data:image/png;base64,${p}`}}))]}:{role:d.role,content:d.content}),stream:true,temperature:o.temperature??.1,max_tokens:o.maxTokens??8192})});if(!l.ok){let d=await l.text();throw new Error(`LM Studio error ${l.status}: ${d}`)}let c=l.body.getReader(),a=new TextDecoder,u="";for(;;){let{done:d,value:p}=await c.read();if(d)break;u+=a.decode(p,{stream:true});let y=u.split(`
130
- `);u=y.pop()||"";for(let x of y){if(!x.startsWith("data: "))continue;let S=x.slice(6).trim();if(S==="[DONE]")return s;try{let T=JSON.parse(S).choices?.[0]?.delta?.content;T&&(t(T),s+=T);}catch{}}}return s}async checkHealth(e){try{let o=(e||$t).replace(/\/$/,"");return (await fetch(`${o}/models`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return false}}async listModels(e){try{let o=(e||$t).replace(/\/$/,""),t=await fetch(`${o}/models`,{signal:AbortSignal.timeout(3e3)});return t.ok?((await t.json()).data??[]).map(s=>s.id):[]}catch{return []}}};var io=new ct,lo=new ut,oe=class{static async stream(e,o,t){switch(o.provider){case "ollama":return io.stream(e,o,t);case "lmstudio":return lo.stream(e,o,t);default:throw new Error(`Unknown provider: ${o.provider}. Use "ollama" or "lmstudio".`)}}static getOllamaProvider(){return io}static getLMStudioProvider(){return lo}};var Qe=promisify(exec);async function dt(r,e){let o=e?resolve(r,e):void 0;return existsSync(join(r,"tsconfig.json"))?sr(r,o):existsSync(join(r,"Cargo.toml"))?ir(r):existsSync(join(r,"go.mod"))?lr(r,o):existsSync(join(r,"pyproject.toml"))||existsSync(join(r,"setup.py"))||existsSync(join(r,"requirements.txt"))?ar(r,o):existsSync(join(r,".eslintrc.js"))||existsSync(join(r,".eslintrc.cjs"))||existsSync(join(r,".eslintrc.json"))||existsSync(join(r,".eslintrc.yml"))?cr(r,o):{diagnostics:[],tool:"none",error:"No supported project detected (tsconfig.json, Cargo.toml, go.mod, setup.py, .eslintrc)"}}async function sr(r,e){try{let o=e?`"${e}"`:"",{stdout:t}=await Qe(`npx --yes tsc --noEmit --pretty false ${o} 2>&1 || true`,{cwd:r,timeout:3e4});return {diagnostics:ur(t),tool:"tsc"}}catch(o){return {diagnostics:[],tool:"tsc",error:String(o)}}}async function ir(r){try{let{stdout:e,stderr:o}=await Qe("cargo check --message-format short 2>&1 || true",{cwd:r,timeout:6e4});return {diagnostics:dr(e+o),tool:"cargo check"}}catch(e){return {diagnostics:[],tool:"cargo check",error:String(e)}}}async function lr(r,e){try{let o=e?`"${e}"`:"./...",{stdout:t,stderr:n}=await Qe(`go vet ${o} 2>&1 || true`,{cwd:r,timeout:3e4});return {diagnostics:mr(t+n),tool:"go vet"}}catch(o){return {diagnostics:[],tool:"go vet",error:String(o)}}}async function ar(r,e){try{let o=e?`"${e}"`:".",{stdout:t,stderr:n}=await Qe(`python -m pyflakes ${o} 2>&1 || true`,{cwd:r,timeout:15e3});return {diagnostics:pr(t+n),tool:"pyflakes"}}catch(o){return {diagnostics:[],tool:"pyflakes",error:String(o)}}}async function cr(r,e){try{let o=e?`"${e}"`:".",{stdout:t}=await Qe(`npx --yes eslint --format json ${o} 2>/dev/null || true`,{cwd:r,timeout:2e4});return {diagnostics:fr(t),tool:"eslint"}}catch(o){return {diagnostics:[],tool:"eslint",error:String(o)}}}function ur(r){let e=[],o=/^(.+)\((\d+),(\d+)\):\s+(error|warning|info)\s+TS\d+:\s+(.+)$/gm,t;for(;(t=o.exec(r))!==null;)e.push({file:t[1].trim(),line:+t[2],col:+t[3],severity:t[4],message:t[5].trim()});return e}function dr(r){let e=[],o=/^(.+):(\d+):(\d+):\s+(error|warning|note)\[?[^\]]*\]?:\s+(.+)$/gm,t;for(;(t=o.exec(r))!==null;)e.push({file:t[1].trim(),line:+t[2],col:+t[3],severity:t[4]==="note"?"info":t[4],message:t[5].trim()});return e}function mr(r){let e=[],o=/^(.+):(\d+):(\d+):\s+(.+)$/gm,t;for(;(t=o.exec(r))!==null;)e.push({file:t[1].trim(),line:+t[2],col:+t[3],severity:"error",message:t[4].trim()});return e}function pr(r){let e=[],o=/^(.+):(\d+):(\d+):\s+(.+)$/gm,t;for(;(t=o.exec(r))!==null;)e.push({file:t[1].trim(),line:+t[2],col:+t[3],severity:"error",message:t[4].trim()});return e}function fr(r){let e=[];try{let o=JSON.parse(r);for(let t of o)for(let n of t.messages??[])e.push({file:t.filePath,line:n.line,col:n.column,severity:n.severity===2?"error":"warning",message:n.message,code:n.ruleId??void 0});}catch{}return e}var mt=createRequire(import.meta.url),ge=join(Ht.homedir(),".localcode","plugins"),he=class r{static _inst;_plugins=[];_errors=[];_loaded=false;static getInstance(){return r._inst||(r._inst=new r),r._inst}getPluginDir(){return ge}load(){if(this._loaded||(this._loaded=true,!existsSync(ge)))return;let e;try{e=readdirSync(ge);}catch{return}for(let o of e){let t=join(ge,o),n=null;try{if(statSync(t).isDirectory()){let s=join(t,"index.js"),l=join(t,"index.cjs");n=existsSync(s)?s:existsSync(l)?l:null;}else (o.endsWith(".js")||o.endsWith(".cjs"))&&(n=t);}catch{continue}if(n)try{let s=mt(n),l=s.default??s;l&&typeof l.name=="string"&&l.name?this._plugins.push(l):this._errors.push({file:n,error:'Missing or invalid "name" field'});}catch(s){this._errors.push({file:n,error:String(s)});}}}reload(){for(let e of Object.keys(mt.cache??{}))e.startsWith(ge)&&delete mt.cache[e];this._loaded=false,this._plugins=[],this._errors=[],this.load();}getAll(){return this._plugins}getErrors(){return this._errors}getCommands(){return this._plugins.flatMap(e=>e.commands??[])}getTools(){return this._plugins.flatMap(e=>e.tools??[])}getTool(e){return this.getTools().find(o=>o.name===e)}async install(e){let o=resolve(e);if(!existsSync(o))return {ok:false,error:`Not found: ${o}`};let t=statSync(o).isDirectory(),n=t?existsSync(join(o,"index.js"))?join(o,"index.js"):join(o,"index.cjs"):o;if(!existsSync(n))return {ok:false,error:"No index.js / index.cjs found in directory"};let s;try{let l=mt(n);s=l.default??l;}catch(l){return {ok:false,error:`Failed to load plugin: ${String(l)}`}}if(!s?.name)return {ok:false,error:'Plugin must export a "name" field'};try{await mkdir(ge,{recursive:!0});let l=join(ge,s.name);t?(existsSync(l)&&await rm(l,{recursive:!0,force:!0}),cpSync(o,l,{recursive:!0})):(await mkdir(l,{recursive:!0}),await copyFile(o,join(l,"index.js")));}catch(l){return {ok:false,error:`Copy failed: ${String(l)}`}}return this.reload(),{ok:true,name:s.name}}async remove(e){let o=join(ge,e),t=join(ge,`${e}.js`);if(existsSync(o))await rm(o,{recursive:true,force:true});else if(existsSync(t))await rm(t,{force:true});else return {ok:false,error:`Plugin "${e}" not found in ${ge}`};return this.reload(),{ok:true}}};var xo=promisify(exec);function Br(){return (process.platform==="win32"?["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",`${process.env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.LOCALAPPDATA}\\Chromium\\Application\\chrome.exe`,"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",`${process.env.LOCALAPPDATA}\\Microsoft\\Edge\\Application\\msedge.exe`]:process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"]:["/usr/bin/google-chrome","/usr/bin/chromium-browser","/usr/bin/chromium","/usr/bin/microsoft-edge"]).find(e=>existsSync(e))??null}async function yo(r,e){let{tool:o,arguments:t}=r;try{switch(o){case "run_shell":return De(String(t.command||""),String(t.cwd||e));case "read_file":return Lr(String(t.path||""),e);case "write_file":return $r(String(t.path||""),String(t.content||""),e);case "append_file":return Er(String(t.path||""),String(t.content||""),e);case "edit_file":return Pr(String(t.path||""),String(t.old||""),String(t.new||""),e);case "delete_file":return Mr(String(t.path||""),e,!!t.recursive);case "move_file":return Dr(String(t.from||""),String(t.to||""),e);case "copy_file":return Fr(String(t.from||""),String(t.to||""),e);case "create_dir":return Or(String(t.path||""),e);case "list_files":return kr(String(t.path||"."),e,!!t.recursive);case "find_files":return Ir(String(t.pattern||""),String(t.path||"."),e);case "search_files":return _r(String(t.pattern||""),String(t.path||"."),e);case "git_status":return De("git status",e);case "git_diff":return De(t.staged?"git diff --staged":"git diff",e);case "git_log":return De(`git log --oneline -${Number(t.limit)||20}`,e);case "git_commit":return De(`git add -A && git commit -m ${JSON.stringify(String(t.message||"chore: update"))}`,e);case "web_fetch":return Nr(String(t.url||""),String(t.format||"text"));case "http_request":return jr(String(t.method||"GET"),String(t.url||""),t.headers,t.body);case "lsp_check":return Ur(String(t.path||"."),e);default:{let n=he.getInstance().getTool(o);return n?n.handler(t,{cwd:e}):{success:!1,output:"",error:`Unknown tool: ${o}`}}}}catch(n){return {success:false,output:"",error:String(n)}}}async function De(r,e){try{let o=process.platform==="win32",{stdout:t,stderr:n}=await xo(r,{cwd:e,timeout:6e4,maxBuffer:1024*1024*10,shell:o?"cmd.exe":"/bin/sh"});return {success:!0,output:(t+(n?`
127
+ End with: DONE: <one-line summary of the plan>`,Kt=30,ze=[{cmd:"/plugin",description:"Manage plugins (list/install/remove/reload)"},{cmd:"/plugin install ",description:"Install plugin from path"},{cmd:"/plugin remove ",description:"Remove plugin by name"},{cmd:"/plugin reload",description:"Reload all plugins"},{cmd:"/connect",description:"Connect to server (popup)"},{cmd:"/model",description:"Select model (popup)"},{cmd:"/attach",description:"Attach file or image (@-picker)"},{cmd:"/compact",description:"Summarize & compress conversation"},{cmd:"/session",description:"List saved sessions"},{cmd:"/session save ",description:"Save session as <name>"},{cmd:"/session load ",description:"Load session <name>"},{cmd:"/session delete ",description:"Delete session <name>"},{cmd:"/config",description:"Show current configuration"},{cmd:"/config model ",description:"Switch model"},{cmd:"/config provider ollama",description:"Use Ollama (localhost:11434)"},{cmd:"/config provider lmstudio",description:"Use LM Studio (localhost:1234)"},{cmd:"/config url ",description:"Set base URL"},{cmd:"/help",description:"Show help"},{cmd:"/lsp",description:"Run diagnostics (tsc/cargo/pylint/eslint)"},{cmd:"/models",description:"List available models"},{cmd:"/doctor",description:"Check system status"},{cmd:"/clear",description:"Clear screen"},{cmd:"/exit",description:"Quit"}],st=["fix auth bug","fix typescript errors","analyze architecture","explain this codebase","create REST API for users","add unit tests","optimize database queries","refactor api layer","scan for security issues","create nextjs dashboard","run tests","explain docker-compose.yml"];var qo=["\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 ","\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],Yo=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],eo=["Start inside a project folder so the agent has codebase context","Run shell commands directly: $ npm test or ! git status","LM Studio: /config provider lmstudio | Ollama: /config provider ollama","Try: fix auth bug \xB7 analyze architecture \xB7 add unit tests","Drag & drop a file into the terminal to attach it automatically","Type @filename to attach a file inline \u2014 e.g. @src/app.ts explain this","Use /model to browse and switch models from the running server","Tab autocompletes commands or toggles BUILD \u2194 PLAN mode","/compact summarizes long conversations to free up context window","/session save <name> to bookmark a conversation, /session load to resume","/doctor checks your LLM connection and shows current configuration","Plan before you build: tab to switch to PLAN mode, then describe the feature"];function zo(r,e){if(r.length<2)return "";let o=e.find(s=>s!==r&&s.toLowerCase().startsWith(r.toLowerCase()));if(o)return o.slice(r.length);let t=ze.find(s=>s.cmd.startsWith(r)&&s.cmd!==r);if(t)return t.cmd.slice(r.length);let n=st.find(s=>s.startsWith(r)&&s!==r);return n?n.slice(r.length):""}var to=({config:r,history:e,onSubmit:o})=>{let[t,n]=useState(""),[s,l]=useState(-1),a=eo[new Date().getDate()%eo.length],c=zo(t,e);useInput((T,h)=>{if(h.tab&&c){n(t+c);return}if(h.upArrow){let y=Math.min(s+1,e.length-1);l(y),e[y]&&n(e[y]);}if(h.downArrow){let y=Math.max(s-1,-1);l(y),n(y===-1?"":e[y]||"");}h.escape&&(n(""),l(-1));});let u=useCallback(T=>{n(T),l(-1);},[]),d=useCallback(T=>{T.trim()&&(l(-1),o(T.trim()),n(""));},[o]),p=Math.max(1,Math.floor((process.stdout.rows||24)/2)-10);return i.createElement(Box,{flexDirection:"column",alignItems:"center"},Array.from({length:p}).map((T,h)=>i.createElement(Text,{key:h}," ")),qo.map((T,h)=>i.createElement(Box,{key:h},i.createElement(Text,{color:"#d8d8d8"},T),i.createElement(Text,{color:"#3B82F6"},Yo[h]))),i.createElement(Text,null," "),i.createElement(Box,{flexDirection:"column",borderStyle:"single",borderColor:"#1E3A5F",minWidth:60},i.createElement(Box,{paddingX:1},i.createElement(Text,{color:"#3B82F6",bold:true},"> "),i.createElement(Mt,{value:t,onChange:u,onSubmit:d,placeholder:"ask anything \xB7 / for commands \xB7 @ to attach"}),c&&i.createElement(Text,{color:"#1F2937"},c)),i.createElement(Box,{paddingX:1,justifyContent:"space-between"},i.createElement(Box,null,i.createElement(Text,{color:"#4B5563"},"\u21B5 "),i.createElement(Text,{color:"#6B7280"},"send "),i.createElement(Text,{color:"#4B5563"},"tab "),i.createElement(Text,{color:"#6B7280"},c?"complete":"autocomplete")),i.createElement(Box,null,i.createElement(Text,{backgroundColor:"#1D4ED8",color:"#BFDBFE"}," BUILD "),i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#9CA3AF"},r.llm.model.length>20?r.llm.model.slice(0,20)+"\u2026":r.llm.model)))),i.createElement(Box,{paddingLeft:2,marginTop:1},i.createElement(Text,{color:"#4B5563"},"\u2191\u2193 "),i.createElement(Text,{color:"#6B7280"},"history "),i.createElement(Text,{color:"#4B5563"},"PgUp/PgDn "),i.createElement(Text,{color:"#6B7280"},"scroll "),i.createElement(Text,{color:"#4B5563"},"@ "),i.createElement(Text,{color:"#6B7280"},"attach "),i.createElement(Text,{color:"#4B5563"},"ctrl+c "),i.createElement(Text,{color:"#6B7280"},"quit")),i.createElement(Text,null," "),i.createElement(Box,{paddingLeft:2},i.createElement(Text,{color:"#F59E0B",bold:true},"\u25CF Tip "),i.createElement(Text,{color:"#4B5563"},a)))};var ro=process.env.HOME||process.env.USERPROFILE||"";function Vo(r){try{return execSync("git rev-parse --abbrev-ref HEAD",{cwd:r,stdio:["ignore","pipe","ignore"],timeout:800}).toString().trim()}catch{return ""}}var Qo={idle:"",running:"#1D4ED8",thinking:"#92400E",error:"#7F1D1D"},no={idle:"",running:"RUNNING",thinking:"THINKING",error:"ERROR"},kt=({config:r,cwd:e,agentStatus:o,tokenCount:t,mode:n="build"})=>{let s=useRef(""),l=useRef("");l.current!==e&&(l.current=e,s.current=Vo(e));let a=e.startsWith(ro)?e.replace(ro,"~"):e,c=s.current;return i.createElement(Box,{justifyContent:"space-between"},i.createElement(Box,null,i.createElement(Text,{bold:true,color:"#60A5FA"},"localcode "),i.createElement(Text,{color:"#374151"},"v0.1.0 "),i.createElement(Text,{color:"#6B7280"},a),c&&i.createElement(Text,{color:"#4B5563"}," (",c,")"),t>0&&i.createElement(Text,{color:"#374151"}," ~",t,"t")),i.createElement(Box,null,no[o]&&i.createElement(Text,{backgroundColor:Qo[o],color:"#BFDBFE"}," ",no[o]," "),i.createElement(Text,{color:"#374151"}," tab "),i.createElement(Text,{backgroundColor:n==="plan"?"#166534":"#1D4ED8",color:n==="plan"?"#86EFAC":"#BFDBFE"}," ",n==="plan"?"PLAN MODE":"BUILD MODE"," ")))};var so=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],it=({label:r="Thinking"})=>{let[e,o]=useState(0);return useEffect(()=>{let t=setInterval(()=>o(n=>(n+1)%so.length),80);return ()=>clearInterval(t)},[]),i.createElement(Text,{color:"#3B82F6"},so[e]," ",r,"...")};var Pt=({filePath:r,oldLines:e,newLines:o,startLine:t,contextBefore:n,contextAfter:s})=>{let l=[],a=t-n.length;n.forEach((d,p)=>{let T=a+p;l.push({type:"context",content:d,left:T,right:T});});let c=t,u=t;return e.forEach(d=>l.push({type:"removed",content:d,left:c++,right:null})),o.forEach(d=>l.push({type:"added",content:d,left:null,right:u++})),s.forEach((d,p)=>l.push({type:"context",content:d,left:c+p,right:u+p})),i.createElement(Box,{flexDirection:"column",marginY:1,marginX:1},i.createElement(Box,{paddingX:2,paddingY:0},i.createElement(Text,{color:"#6B7280"},"Edit "),i.createElement(Text,{color:"#9CA3AF"},r)),i.createElement(Box,{flexDirection:"column",borderStyle:"single",borderColor:"#374151"},l.map((d,p)=>{let T=d.left!==null?String(d.left).padStart(4):" ",h=d.right!==null?String(d.right).padStart(4):" ";return d.type==="removed"?i.createElement(Box,{key:p},i.createElement(Text,{color:"#EF4444"}," ",T," "),i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#EF4444"}," - "),i.createElement(Text,{color:"#FCA5A5"},d.content)):d.type==="added"?i.createElement(Box,{key:p},i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#22C55E"}," ",h," "),i.createElement(Text,{color:"#22C55E"}," + "),i.createElement(Text,{color:"#86EFAC"},d.content)):i.createElement(Box,{key:p},i.createElement(Text,{color:"#4B5563"}," ",T," "),i.createElement(Text,{color:"#4B5563"}," ",h," "),i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#6B7280"},d.content))})))};var _t=({text:r})=>{let e=[],o=r;for(;o;){let t=o.match(/^`([^`]*)`/);if(t){e.push({t:t[1],code:true}),o=o.slice(t[0].length);continue}let n=o.match(/^\*\*([^*]+)\*\*/);if(n){e.push({t:n[1],bold:true}),o=o.slice(n[0].length);continue}let s=o.match(/^\*([^*]+)\*/);if(s){e.push({t:s[1],italic:true}),o=o.slice(s[0].length);continue}let l=o.search(/`|\*\*|\*(?!\*)/);if(l===-1){e.push({t:o});break}if(l===0){e.push({t:o[0]}),o=o.slice(1);continue}e.push({t:o.slice(0,l)}),o=o.slice(l);}return i.createElement(i.Fragment,null,e.map((t,n)=>t.code?i.createElement(Text,{key:n,color:"#7DD3FC"},t.t):t.bold?i.createElement(Text,{key:n,bold:true,color:"#E5E7EB"},t.t):t.italic?i.createElement(Text,{key:n,color:"#D1D5DB",italic:true},t.t):i.createElement(Text,{key:n,color:"#D1D5DB"},t.t)))},Et=({content:r})=>{let e=r.split(`
128
+ `),o=[],t=false,n="",s=[],l=a=>{o.push(i.createElement(Box,{key:a,flexDirection:"column"},n&&i.createElement(Box,null,i.createElement(Text,{color:"#1D4ED8"}," \u250C\u2500 "),i.createElement(Text,{color:"#60A5FA"},n)),s.map((c,u)=>i.createElement(Box,{key:u},i.createElement(Text,{color:"#374151"}," \u2502 "),i.createElement(Text,{color:"#7DD3FC",wrap:"wrap"},c||" "))),i.createElement(Text,{color:"#1D4ED8"}," \u2514","\u2500".repeat(Math.min(40,Math.max(8,...s.map(c=>c.length+1))))))),s=[],n="";};for(let a=0;a<e.length;a++){let c=e[a];if(c.startsWith("```")){t?(t=false,l(`c${a}`)):(t=true,n=c.slice(3).trim());continue}if(t){s.push(c);continue}if(c.startsWith("### "))o.push(i.createElement(Text,{key:a,bold:true,color:"#93C5FD",wrap:"wrap"},c.slice(4)));else if(c.startsWith("## "))o.push(i.createElement(Text,{key:a,bold:true,color:"#60A5FA",wrap:"wrap"},c.slice(3)));else if(c.startsWith("# "))o.push(i.createElement(Text,{key:a,bold:true,color:"#3B82F6",wrap:"wrap"},c.slice(2)));else if(/^[-*+] /.test(c))o.push(i.createElement(Box,{key:a},i.createElement(Text,{color:"#6B7280"}," \u2022 "),i.createElement(Box,{flexWrap:"wrap"},i.createElement(_t,{text:c.slice(2)}))));else if(/^\d+\. /.test(c)){let u=c.match(/^(\d+)\. (.*)/);o.push(i.createElement(Box,{key:a},i.createElement(Text,{color:"#6B7280"}," ",u[1],". "),i.createElement(Box,{flexWrap:"wrap"},i.createElement(_t,{text:u[2]}))));}else /^---+$/.test(c.trim())?o.push(i.createElement(Text,{key:a,color:"#374151"},"\u2500".repeat(48))):c.trim()?o.push(i.createElement(Box,{key:a,flexWrap:"wrap"},i.createElement(_t,{text:c}))):o.push(i.createElement(Text,{key:a}," "));}return t&&s.length&&l("end"),i.createElement(Box,{flexDirection:"column"},o)};var io=[{id:"ollama",label:"Ollama",defaultPort:"11434",urlSuffix:""},{id:"lmstudio",label:"LM Studio",defaultPort:"1234",urlSuffix:"/v1"}],lo=({onConnect:r,onCancel:e})=>{let[o,t]=useState("provider"),[n,s]=useState(""),[l,a]=useState(0),[c,u]=useState(io[0]),[d,p]=useState("localhost"),[T,h]=useState("11434"),y=io.filter(D=>D.label.toLowerCase().includes(n.toLowerCase())||D.id.toLowerCase().includes(n.toLowerCase()));useInput((D,x)=>{if(o==="provider"){if(x.upArrow){a(E=>Math.max(0,E-1));return}if(x.downArrow){a(E=>Math.min(y.length-1,E+1));return}if(x.escape){e();return}if(x.return){let E=y[Math.min(l,y.length-1)];if(!E)return;u(E),p("localhost"),h(E.defaultPort),t("ip");return}}if(o==="ip"){if(x.escape){t("provider");return}if(x.return){t("port");return}}if(o==="port"){if(x.escape){t("ip");return}if(x.return){let E=c.id,B=`http://${d}:${T}${c.urlSuffix}`;r(E,B);return}}});let Q=o==="provider"?"\u203A Choose provider":o==="ip"?`\u203A ${c.label} \u203A IP address`:`\u203A ${c.label} \u203A Port`;return i.createElement(Box,{flexDirection:"column",borderStyle:"round",borderColor:"#3B82F6",marginX:1},i.createElement(Box,{paddingX:2},i.createElement(Text,{color:"#3B82F6",bold:true}," Connect "),i.createElement(Text,{color:"#4B5563"},Q)),o==="provider"&&i.createElement(i.Fragment,null,i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#1E3A5F"},i.createElement(Text,{color:"#6B7280"},"/ "),i.createElement(Mt,{value:n,onChange:D=>{s(D),a(0);},placeholder:"Search provider ...",focus:true})),y.length===0?i.createElement(Box,{paddingX:4},i.createElement(Text,{color:"#6B7280"},"No provider found")):y.map((D,x)=>{let E=x===l;return i.createElement(Box,{key:D.id,paddingX:2},i.createElement(Text,{color:E?"#3B82F6":"#374151"},E?"\u25B6 ":" "),i.createElement(Text,{color:E?"#93C5FD":"#9CA3AF",bold:E},D.label),i.createElement(Text,{color:E?"#4B5563":"#2D3748"}," :",D.defaultPort))})),o==="ip"&&i.createElement(Box,{paddingX:2,paddingY:1,flexDirection:"column"},i.createElement(Text,{color:"#6B7280"},"IP address:"),i.createElement(Box,{marginTop:1,borderStyle:"single",borderColor:"#1E3A5F",paddingX:1},i.createElement(Mt,{value:d,onChange:p,focus:true}))),o==="port"&&i.createElement(Box,{paddingX:2,paddingY:1,flexDirection:"column"},i.createElement(Text,{color:"#6B7280"},"Port:"),i.createElement(Box,{marginTop:1,borderStyle:"single",borderColor:"#1E3A5F",paddingX:1},i.createElement(Mt,{value:T,onChange:h,focus:true}))),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#1E3A5F"},o==="provider"?i.createElement(i.Fragment,null,i.createElement(Text,{color:"#374151"},"\u2191\u2193 "),i.createElement(Text,{color:"#4B5563"},"select "),i.createElement(Text,{color:"#374151"},"enter "),i.createElement(Text,{color:"#4B5563"},"next "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"close")):o==="ip"?i.createElement(i.Fragment,null,i.createElement(Text,{color:"#374151"},"enter "),i.createElement(Text,{color:"#4B5563"},"next "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"back")):i.createElement(i.Fragment,null,i.createElement(Text,{color:"#22C55E"},"enter "),i.createElement(Text,{color:"#4B5563"},"connect "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"back"))))};var co=({models:r,loading:e,currentModel:o,onSelect:t,onCancel:n})=>{let[s,l]=useState(""),[a,c]=useState(0),u=r.filter(p=>p.toLowerCase().includes(s.toLowerCase()));useInput((p,T)=>{if(e){if(T.escape){n();return}return}if(T.upArrow){c(h=>Math.max(0,h-1));return}if(T.downArrow){c(h=>Math.min(u.length-1,h+1));return}if(T.escape){n();return}if(T.return){let h=u[Math.min(a,u.length-1)];h&&t(h);return}});let d=u.slice(0,8);return i.createElement(Box,{flexDirection:"column",borderStyle:"round",borderColor:"#6366F1",marginX:1},i.createElement(Box,{paddingX:2},i.createElement(Text,{color:"#6366F1",bold:true}," Model "),i.createElement(Text,{color:"#4B5563"},"\u203A Select a model "),i.createElement(Text,{color:"#374151"},"current: "),i.createElement(Text,{color:"#9CA3AF"},o)),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#312E81"},i.createElement(Text,{color:"#6B7280"},"/ "),i.createElement(Mt,{value:s,onChange:p=>{l(p),c(0);},placeholder:"Search model ...",focus:!e})),e?i.createElement(Box,{paddingX:4,paddingY:1},i.createElement(Text,{color:"#6B7280"},"Loading models from server ...")):d.length===0?i.createElement(Box,{paddingX:4,paddingY:1},i.createElement(Text,{color:"#6B7280"},r.length===0?"No models found \u2014 is the server reachable?":"No matches")):d.map((p,T)=>{let h=T===a;return i.createElement(Box,{key:p,paddingX:2},i.createElement(Text,{color:h?"#6366F1":"#374151"},h?"\u25B6 ":" "),p===o?i.createElement(Text,{color:h?"#A5B4FC":"#6366F1",bold:true},"\u2713 ",p):i.createElement(Text,{color:h?"#A5B4FC":"#9CA3AF"}," ",p))}),u.length>8&&i.createElement(Box,{paddingX:4},i.createElement(Text,{color:"#374151"},"\u2026 ",u.length-8," more (refine search)")),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#312E81"},i.createElement(Text,{color:"#374151"},"\u2191\u2193 "),i.createElement(Text,{color:"#4B5563"},"select "),i.createElement(Text,{color:"#374151"},"enter "),i.createElement(Text,{color:"#4B5563"},"apply "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"close")))};var lr=new Set([".jpg",".jpeg",".png",".gif",".webp",".bmp",".svg"]),mo=({files:r,onSelect:e,onCancel:o})=>{let[t,n]=useState(""),[s,l]=useState(0),a=r.filter(c=>c.toLowerCase().includes(t.toLowerCase())).slice(0,8);return useInput((c,u)=>{if(u.upArrow){l(d=>Math.max(0,d-1));return}if(u.downArrow){l(d=>Math.min(a.length-1,d+1));return}if(u.escape){o();return}if(u.return){let d=a[Math.min(s,a.length-1)];d&&e(d);return}}),i.createElement(Box,{flexDirection:"column",borderStyle:"round",borderColor:"#22C55E",marginX:1},i.createElement(Box,{paddingX:2},i.createElement(Text,{color:"#22C55E",bold:true}," @ Attach "),i.createElement(Text,{color:"#4B5563"},"\u203A Datei oder Bild ausw\xE4hlen")),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#15803D"},i.createElement(Text,{color:"#6B7280"},"/ "),i.createElement(Mt,{value:t,onChange:c=>{n(c),l(0);},placeholder:"Search file...",focus:true})),a.length===0?i.createElement(Box,{paddingX:4,paddingY:1},i.createElement(Text,{color:"#6B7280"},"No files found")):a.map((c,u)=>{let d=u===s,p=lr.has(extname(c).toLowerCase());return i.createElement(Box,{key:c,paddingX:2},i.createElement(Text,{color:d?"#22C55E":"#374151"},d?"\u25B6 ":" "),i.createElement(Text,{color:d?"#86EFAC":"#9CA3AF"},p?"[img] ":"[file] ",c))}),i.createElement(Box,{paddingX:2,borderStyle:"single",borderTop:true,borderColor:"#15803D"},i.createElement(Text,{color:"#374151"},"\u2191\u2193 "),i.createElement(Text,{color:"#4B5563"},"select "),i.createElement(Text,{color:"#374151"},"enter "),i.createElement(Text,{color:"#4B5563"},"attach "),i.createElement(Text,{color:"#374151"},"esc "),i.createElement(Text,{color:"#4B5563"},"close")))};var lt=class{async stream(e,o,t){let n=o.baseURL||"http://localhost:11434",s="",l=await fetch(`${n}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:o.model||"deepseek-coder",messages:e.map(u=>{let d={role:u.role,content:u.content};return u.images?.length&&(d.images=u.images),d}),stream:true,options:{temperature:o.temperature??.1,num_predict:o.maxTokens??8192}})});if(!l.ok){let u=await l.text();throw new Error(`Ollama error ${l.status}: ${u}`)}let a=l.body.getReader(),c=new TextDecoder;for(;;){let{done:u,value:d}=await a.read();if(u)break;let p=c.decode(d,{stream:true});for(let T of p.split(`
129
+ `).filter(h=>h.trim()))try{let h=JSON.parse(T),y=h.message?.content||"";if(y&&(t(y),s+=y),h.done)return s}catch{}}return s}async listModels(e="http://localhost:11434"){try{let o=await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(5e3)});return o.ok?((await o.json()).models||[]).map(n=>n.name):[]}catch{return []}}async checkHealth(e="http://localhost:11434"){try{return (await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(3e3)})).ok}catch{return false}}};var Dt="http://localhost:1234/v1",at=class{async stream(e,o,t){let n=(o.baseURL||Dt).replace(/\/$/,""),s="",l=await fetch(`${n}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:o.model,messages:e.map(d=>d.images?.length?{role:d.role,content:[{type:"text",text:d.content},...d.images.map(p=>({type:"image_url",image_url:{url:`data:image/png;base64,${p}`}}))]}:{role:d.role,content:d.content}),stream:true,temperature:o.temperature??.1,max_tokens:o.maxTokens??8192})});if(!l.ok){let d=await l.text();throw new Error(`LM Studio error ${l.status}: ${d}`)}let a=l.body.getReader(),c=new TextDecoder,u="";for(;;){let{done:d,value:p}=await a.read();if(d)break;u+=c.decode(p,{stream:true});let T=u.split(`
130
+ `);u=T.pop()||"";for(let h of T){if(!h.startsWith("data: "))continue;let y=h.slice(6).trim();if(y==="[DONE]")return s;try{let D=JSON.parse(y).choices?.[0]?.delta?.content;D&&(t(D),s+=D);}catch{}}}return s}async checkHealth(e){try{let o=(e||Dt).replace(/\/$/,"");return (await fetch(`${o}/models`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return false}}async listModels(e){try{let o=(e||Dt).replace(/\/$/,""),t=await fetch(`${o}/models`,{signal:AbortSignal.timeout(3e3)});return t.ok?((await t.json()).data??[]).map(s=>s.id):[]}catch{return []}}};var po=new lt,fo=new at,Z=class{static async stream(e,o,t){switch(o.provider){case "ollama":return po.stream(e,o,t);case "lmstudio":return fo.stream(e,o,t);default:throw new Error(`Unknown provider: ${o.provider}. Use "ollama" or "lmstudio".`)}}static getOllamaProvider(){return po}static getLMStudioProvider(){return fo}};var Je=promisify(exec);async function ct(r,e){let o=e?resolve(r,e):void 0;return existsSync(join(r,"tsconfig.json"))?dr(r,o):existsSync(join(r,"Cargo.toml"))?mr(r):existsSync(join(r,"go.mod"))?pr(r,o):existsSync(join(r,"pyproject.toml"))||existsSync(join(r,"setup.py"))||existsSync(join(r,"requirements.txt"))?fr(r,o):existsSync(join(r,".eslintrc.js"))||existsSync(join(r,".eslintrc.cjs"))||existsSync(join(r,".eslintrc.json"))||existsSync(join(r,".eslintrc.yml"))?gr(r,o):{diagnostics:[],tool:"none",error:"No supported project detected (tsconfig.json, Cargo.toml, go.mod, setup.py, .eslintrc)"}}async function dr(r,e){try{let o=e?`"${e}"`:"",{stdout:t}=await Je(`npx --yes tsc --noEmit --pretty false ${o} 2>&1 || true`,{cwd:r,timeout:3e4});return {diagnostics:hr(t),tool:"tsc"}}catch(o){return {diagnostics:[],tool:"tsc",error:String(o)}}}async function mr(r){try{let{stdout:e,stderr:o}=await Je("cargo check --message-format short 2>&1 || true",{cwd:r,timeout:6e4});return {diagnostics:xr(e+o),tool:"cargo check"}}catch(e){return {diagnostics:[],tool:"cargo check",error:String(e)}}}async function pr(r,e){try{let o=e?`"${e}"`:"./...",{stdout:t,stderr:n}=await Je(`go vet ${o} 2>&1 || true`,{cwd:r,timeout:3e4});return {diagnostics:yr(t+n),tool:"go vet"}}catch(o){return {diagnostics:[],tool:"go vet",error:String(o)}}}async function fr(r,e){try{let o=e?`"${e}"`:".",{stdout:t,stderr:n}=await Je(`python -m pyflakes ${o} 2>&1 || true`,{cwd:r,timeout:15e3});return {diagnostics:Tr(t+n),tool:"pyflakes"}}catch(o){return {diagnostics:[],tool:"pyflakes",error:String(o)}}}async function gr(r,e){try{let o=e?`"${e}"`:".",{stdout:t}=await Je(`npx --yes eslint --format json ${o} 2>/dev/null || true`,{cwd:r,timeout:2e4});return {diagnostics:br(t),tool:"eslint"}}catch(o){return {diagnostics:[],tool:"eslint",error:String(o)}}}function hr(r){let e=[],o=/^(.+)\((\d+),(\d+)\):\s+(error|warning|info)\s+TS\d+:\s+(.+)$/gm,t;for(;(t=o.exec(r))!==null;)e.push({file:t[1].trim(),line:+t[2],col:+t[3],severity:t[4],message:t[5].trim()});return e}function xr(r){let e=[],o=/^(.+):(\d+):(\d+):\s+(error|warning|note)\[?[^\]]*\]?:\s+(.+)$/gm,t;for(;(t=o.exec(r))!==null;)e.push({file:t[1].trim(),line:+t[2],col:+t[3],severity:t[4]==="note"?"info":t[4],message:t[5].trim()});return e}function yr(r){let e=[],o=/^(.+):(\d+):(\d+):\s+(.+)$/gm,t;for(;(t=o.exec(r))!==null;)e.push({file:t[1].trim(),line:+t[2],col:+t[3],severity:"error",message:t[4].trim()});return e}function Tr(r){let e=[],o=/^(.+):(\d+):(\d+):\s+(.+)$/gm,t;for(;(t=o.exec(r))!==null;)e.push({file:t[1].trim(),line:+t[2],col:+t[3],severity:"error",message:t[4].trim()});return e}function br(r){let e=[];try{let o=JSON.parse(r);for(let t of o)for(let n of t.messages??[])e.push({file:t.filePath,line:n.line,col:n.column,severity:n.severity===2?"error":"warning",message:n.message,code:n.ruleId??void 0});}catch{}return e}var ut=createRequire(import.meta.url),ge=join(Jt.homedir(),".localcode","plugins"),he=class r{static _inst;_plugins=[];_errors=[];_loaded=false;static getInstance(){return r._inst||(r._inst=new r),r._inst}getPluginDir(){return ge}load(){if(this._loaded||(this._loaded=true,!existsSync(ge)))return;let e;try{e=readdirSync(ge);}catch{return}for(let o of e){let t=join(ge,o),n=null;try{if(statSync(t).isDirectory()){let s=join(t,"index.js"),l=join(t,"index.cjs");n=existsSync(s)?s:existsSync(l)?l:null;}else (o.endsWith(".js")||o.endsWith(".cjs"))&&(n=t);}catch{continue}if(n)try{let s=ut(n),l=s.default??s;l&&typeof l.name=="string"&&l.name?this._plugins.push(l):this._errors.push({file:n,error:'Missing or invalid "name" field'});}catch(s){this._errors.push({file:n,error:String(s)});}}}reload(){for(let e of Object.keys(ut.cache??{}))e.startsWith(ge)&&delete ut.cache[e];this._loaded=false,this._plugins=[],this._errors=[],this.load();}getAll(){return this._plugins}getErrors(){return this._errors}getCommands(){return this._plugins.flatMap(e=>e.commands??[])}getTools(){return this._plugins.flatMap(e=>e.tools??[])}getTool(e){return this.getTools().find(o=>o.name===e)}async install(e){let o=resolve(e);if(!existsSync(o))return {ok:false,error:`Not found: ${o}`};let t=statSync(o).isDirectory(),n=t?existsSync(join(o,"index.js"))?join(o,"index.js"):join(o,"index.cjs"):o;if(!existsSync(n))return {ok:false,error:"No index.js / index.cjs found in directory"};let s;try{let l=ut(n);s=l.default??l;}catch(l){return {ok:false,error:`Failed to load plugin: ${String(l)}`}}if(!s?.name)return {ok:false,error:'Plugin must export a "name" field'};try{await mkdir(ge,{recursive:!0});let l=join(ge,s.name);t?(existsSync(l)&&await rm(l,{recursive:!0,force:!0}),cpSync(o,l,{recursive:!0})):(await mkdir(l,{recursive:!0}),await copyFile(o,join(l,"index.js")));}catch(l){return {ok:false,error:`Copy failed: ${String(l)}`}}return this.reload(),{ok:true,name:s.name}}async remove(e){let o=join(ge,e),t=join(ge,`${e}.js`);if(existsSync(o))await rm(o,{recursive:true,force:true});else if(existsSync(t))await rm(t,{force:true});else return {ok:false,error:`Plugin "${e}" not found in ${ge}`};return this.reload(),{ok:true}}};var wo=promisify(exec);function Er(){return (process.platform==="win32"?["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",`${process.env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.LOCALAPPDATA}\\Chromium\\Application\\chrome.exe`,"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",`${process.env.LOCALAPPDATA}\\Microsoft\\Edge\\Application\\msedge.exe`]:process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"]:["/usr/bin/google-chrome","/usr/bin/chromium-browser","/usr/bin/chromium","/usr/bin/microsoft-edge"]).find(e=>existsSync(e))??null}async function Co(r,e){let{tool:o,arguments:t}=r;try{switch(o){case "run_shell":return De(String(t.command||""),String(t.cwd||e));case "read_file":return Mr(String(t.path||""),e);case "write_file":return Dr(String(t.path||""),String(t.content||""),e);case "append_file":return Nr(String(t.path||""),String(t.content||""),e);case "edit_file":return Fr(String(t.path||""),String(t.old||""),String(t.new||""),e);case "delete_file":return jr(String(t.path||""),e,!!t.recursive);case "move_file":return Ur(String(t.from||""),String(t.to||""),e);case "copy_file":return Wr(String(t.from||""),String(t.to||""),e);case "create_dir":return Hr(String(t.path||""),e);case "list_files":return Or(String(t.path||"."),e,!!t.recursive);case "find_files":return Xr(String(t.pattern||""),String(t.path||"."),e);case "search_files":return Ir(String(t.pattern||""),String(t.path||"."),e);case "git_status":return De("git status",e);case "git_diff":return De(t.staged?"git diff --staged":"git diff",e);case "git_log":return De(`git log --oneline -${Number(t.limit)||20}`,e);case "git_commit":return De(`git add -A && git commit -m ${JSON.stringify(String(t.message||"chore: update"))}`,e);case "web_fetch":return Gr(String(t.url||""),String(t.format||"text"));case "http_request":return qr(String(t.method||"GET"),String(t.url||""),t.headers,t.body);case "lsp_check":return Yr(String(t.path||"."),e);default:{let n=he.getInstance().getTool(o);return n?n.handler(t,{cwd:e}):{success:!1,output:"",error:`Unknown tool: ${o}`}}}}catch(n){return {success:false,output:"",error:String(n)}}}async function De(r,e){try{let o=process.platform==="win32",{stdout:t,stderr:n}=await wo(r,{cwd:e,timeout:6e4,maxBuffer:1024*1024*10,shell:o?"cmd.exe":"/bin/sh"});return {success:!0,output:(t+(n?`
131
131
  STDERR:
132
- ${n}`:"")).trim()||"(no output)"}}catch(o){let t=o;return {success:false,output:t.stdout||"",error:t.stderr||t.message||String(o)}}}async function Lr(r,e){let o=resolve(e,r),s=(await readFile(o,"utf-8")).split(`
133
- `).map((l,c)=>`${String(c+1).padStart(4)} \u2502 ${l}`).join(`
132
+ ${n}`:"")).trim()||"(no output)"}}catch(o){let t=o;return {success:false,output:t.stdout||"",error:t.stderr||t.message||String(o)}}}async function Mr(r,e){let o=resolve(e,r),s=(await readFile(o,"utf-8")).split(`
133
+ `).map((l,a)=>`${String(a+1).padStart(4)} \u2502 ${l}`).join(`
134
134
  `);return {success:true,output:`// ${o}
135
- ${s}`}}async function $r(r,e,o){let t=resolve(o,r),n=dirname(t);return existsSync(n)||await mkdir(n,{recursive:true}),await writeFile(t,e,"utf-8"),{success:true,output:`Written: ${t} (${e.length} chars, ${e.split(`
136
- `).length} lines)`}}async function Pr(r,e,o,t){let n=resolve(t,r),s=await readFile(n,"utf-8");if(!s.includes(e))return {success:false,output:"",error:`Pattern not found in ${r}. Check for exact whitespace and line endings.`};let l=s.indexOf(e),c=s.slice(0,l).split(`
137
- `).length,a=s.split(`
135
+ ${s}`}}async function Dr(r,e,o){let t=resolve(o,r),n=dirname(t);return existsSync(n)||await mkdir(n,{recursive:true}),await writeFile(t,e,"utf-8"),{success:true,output:`Written: ${t} (${e.length} chars, ${e.split(`
136
+ `).length} lines)`}}async function Fr(r,e,o,t){let n=resolve(t,r),s=await readFile(n,"utf-8");if(!s.includes(e))return {success:false,output:"",error:`Pattern not found in ${r}. Check for exact whitespace and line endings.`};let l=s.indexOf(e),a=s.slice(0,l).split(`
137
+ `).length,c=s.split(`
138
138
  `),u=e.split(`
139
- `),d=3,p=a.slice(Math.max(0,c-1-d),c-1),y=a.slice(c-1+u.length,c-1+u.length+d);return await writeFile(n,s.replace(e,o),"utf-8"),{success:true,output:`Edited: ${n}`,meta:{diffPath:r,diffOld:u,diffNew:o.split(`
140
- `),diffStartLine:c,diffContextBefore:p,diffContextAfter:y}}}async function kr(r,e,o){let t=resolve(e,r),n=new Set(["node_modules","dist",".git","__pycache__","target",".next","build","AppData","appdata",".cache","cache","Cache","Temp","temp","tmp","OneDrive","OneDriveConsumer","Pictures","Videos","Music",".npm",".yarn",".pnpm-store","venv",".venv","env"]),s=4,l=300,c=0;async function a(d,p="",y=0){if(y>s||c>=l)return [];let x;try{x=await readdir(d,{withFileTypes:!0});}catch{return [`${p}(permission denied)`]}let S=[];for(let G of x){if(c>=l){S.push(`${p}\u2026 (limit reached)`);break}let T=G.isDirectory();if(n.has(G.name)){T&&S.push(`${p}${G.name}/ (skipped)`);continue}if(S.push(`${p}${G.name}${T?"/":""}`),c++,T&&o&&y<s){let $=await a(join(d,G.name),`${p} `,y+1);S.push(...$);}}return S}return {success:true,output:(await a(t)).join(`
141
- `)||"(empty directory)"}}async function _r(r,e,o){let t=resolve(o,e);if(process.platform==="win32"){let c=`findstr /s /n /i /r "${r}" "${t}\\*.ts" "${t}\\*.tsx" "${t}\\*.js" "${t}\\*.jsx" "${t}\\*.py" "${t}\\*.go" "${t}\\*.json" "${t}\\*.md" 2>nul`;return De(c,o)}let l=`grep -rn ${["ts","tsx","js","jsx","py","go","rs","java","cs","cpp","c","h","json","yaml","yml","md"].map(c=>`--include="*.${c}"`).join(" ")} "${r}" "${t}" 2>/dev/null | head -60`;return De(l,o)}async function Er(r,e,o){let t=resolve(o,r),n=dirname(t);return existsSync(n)||await mkdir(n,{recursive:true}),await appendFile(t,e,"utf-8"),{success:true,output:`Appended ${e.length} chars to ${t}`}}async function Mr(r,e,o){let t=resolve(e,r);return await rm(t,{recursive:o,force:true}),{success:true,output:`Deleted: ${t}`}}async function Dr(r,e,o){let t=resolve(o,r),n=resolve(o,e),s=dirname(n);return existsSync(s)||await mkdir(s,{recursive:true}),await rename(t,n),{success:true,output:`Moved: ${t} \u2192 ${n}`}}async function Fr(r,e,o){let t=resolve(o,r),n=resolve(o,e),s=dirname(n);return existsSync(s)||await mkdir(s,{recursive:true}),await copyFile(t,n),{success:true,output:`Copied: ${t} \u2192 ${n}`}}async function Or(r,e){let o=resolve(e,r);return await mkdir(o,{recursive:true}),{success:true,output:`Created directory: ${o}`}}async function Ir(r,e,o){let t=resolve(o,e);process.platform==="win32";let s=new Set(["node_modules",".git","dist","__pycache__",".next","build","target"]),l=[],c=new RegExp("^"+r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$","i");async function a(u){if(l.length>=200)return;let d;try{d=await readdir(u,{withFileTypes:!0});}catch{return}for(let p of d){if(s.has(p.name))continue;let y=join(u,p.name);p.isDirectory()?await a(y):c.test(p.name)&&l.push(y);}}return await a(t),{success:true,output:l.join(`
142
- `)||"No files found."}}async function Nr(r,e){if(/^[A-Za-z]:[\\\/]/.test(r)||/^\/[^\s]/.test(r)||r.startsWith("file://"))return {success:false,output:"",error:`"${r}" is a local path. Use read_file to read local files.`};if(!r.startsWith("http://")&&!r.startsWith("https://"))return {success:false,output:"",error:"URL must start with http:// or https://"};let t=Br(),n=join(Ht.tmpdir(),`localcode_web_${Date.now()}.png`);if(t)try{let l=["--headless=new","--disable-gpu","--no-sandbox","--disable-dev-shm-usage",`--screenshot="${n}"`,"--window-size=1280,900","--hide-scrollbars",`"${r}"`].join(" ");await xo(`"${t}" ${l}`,{timeout:2e4});let a=(await readFile(n)).toString("base64");await unlink(n).catch(()=>{});let{text:u}=await po(r);return {success:!0,output:`[screenshot taken] ${r}
139
+ `),d=3,p=c.slice(Math.max(0,a-1-d),a-1),T=c.slice(a-1+u.length,a-1+u.length+d);return await writeFile(n,s.replace(e,o),"utf-8"),{success:true,output:`Edited: ${n}`,meta:{diffPath:r,diffOld:u,diffNew:o.split(`
140
+ `),diffStartLine:a,diffContextBefore:p,diffContextAfter:T}}}async function Or(r,e,o){let t=resolve(e,r),n=new Set(["node_modules","dist",".git","__pycache__","target",".next","build","AppData","appdata",".cache","cache","Cache","Temp","temp","tmp","OneDrive","OneDriveConsumer","Pictures","Videos","Music",".npm",".yarn",".pnpm-store","venv",".venv","env"]),s=4,l=300,a=0;async function c(d,p="",T=0){if(T>s||a>=l)return [];let h;try{h=await readdir(d,{withFileTypes:!0});}catch{return [`${p}(permission denied)`]}let y=[];for(let Q of h){if(a>=l){y.push(`${p}\u2026 (limit reached)`);break}let D=Q.isDirectory();if(n.has(Q.name)){D&&y.push(`${p}${Q.name}/ (skipped)`);continue}if(y.push(`${p}${Q.name}${D?"/":""}`),a++,D&&o&&T<s){let x=await c(join(d,Q.name),`${p} `,T+1);y.push(...x);}}return y}return {success:true,output:(await c(t)).join(`
141
+ `)||"(empty directory)"}}async function Ir(r,e,o){let t=resolve(o,e);if(process.platform==="win32"){let a=`findstr /s /n /i /r "${r}" "${t}\\*.ts" "${t}\\*.tsx" "${t}\\*.js" "${t}\\*.jsx" "${t}\\*.py" "${t}\\*.go" "${t}\\*.json" "${t}\\*.md" 2>nul`;return De(a,o)}let l=`grep -rn ${["ts","tsx","js","jsx","py","go","rs","java","cs","cpp","c","h","json","yaml","yml","md"].map(a=>`--include="*.${a}"`).join(" ")} "${r}" "${t}" 2>/dev/null | head -60`;return De(l,o)}async function Nr(r,e,o){let t=resolve(o,r),n=dirname(t);return existsSync(n)||await mkdir(n,{recursive:true}),await appendFile(t,e,"utf-8"),{success:true,output:`Appended ${e.length} chars to ${t}`}}async function jr(r,e,o){let t=resolve(e,r);return await rm(t,{recursive:o,force:true}),{success:true,output:`Deleted: ${t}`}}async function Ur(r,e,o){let t=resolve(o,r),n=resolve(o,e),s=dirname(n);return existsSync(s)||await mkdir(s,{recursive:true}),await rename(t,n),{success:true,output:`Moved: ${t} \u2192 ${n}`}}async function Wr(r,e,o){let t=resolve(o,r),n=resolve(o,e),s=dirname(n);return existsSync(s)||await mkdir(s,{recursive:true}),await copyFile(t,n),{success:true,output:`Copied: ${t} \u2192 ${n}`}}async function Hr(r,e){let o=resolve(e,r);return await mkdir(o,{recursive:true}),{success:true,output:`Created directory: ${o}`}}async function Xr(r,e,o){let t=resolve(o,e);process.platform==="win32";let s=new Set(["node_modules",".git","dist","__pycache__",".next","build","target"]),l=[],a=new RegExp("^"+r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$","i");async function c(u){if(l.length>=200)return;let d;try{d=await readdir(u,{withFileTypes:!0});}catch{return}for(let p of d){if(s.has(p.name))continue;let T=join(u,p.name);p.isDirectory()?await c(T):a.test(p.name)&&l.push(T);}}return await c(t),{success:true,output:l.join(`
142
+ `)||"No files found."}}async function Gr(r,e){if(/^[A-Za-z]:[\\\/]/.test(r)||/^\/[^\s]/.test(r)||r.startsWith("file://"))return {success:false,output:"",error:`"${r}" is a local path. Use read_file to read local files.`};if(!r.startsWith("http://")&&!r.startsWith("https://"))return {success:false,output:"",error:"URL must start with http:// or https://"};let t=Er(),n=join(Jt.tmpdir(),`localcode_web_${Date.now()}.png`);if(t)try{let l=["--headless=new","--disable-gpu","--no-sandbox","--disable-dev-shm-usage",`--screenshot="${n}"`,"--window-size=1280,900","--hide-scrollbars",`"${r}"`].join(" ");await wo(`"${t}" ${l}`,{timeout:2e4});let c=(await readFile(n)).toString("base64");await unlink(n).catch(()=>{});let{text:u}=await To(r);return {success:!0,output:`[screenshot taken] ${r}
143
143
 
144
- ${u.slice(0,8e3)}`,images:[a]}}catch{await unlink(n).catch(()=>{});}let{text:s}=await po(r);return {success:true,output:`[no browser found \u2014 text only] ${r}
144
+ ${u.slice(0,8e3)}`,images:[c]}}catch{await unlink(n).catch(()=>{});}let{text:s}=await To(r);return {success:true,output:`[no browser found \u2014 text only] ${r}
145
145
 
146
- ${s.slice(0,2e4)}`}}async function po(r){let e=await fetch(r,{headers:{"User-Agent":"Mozilla/5.0 (compatible; LocalCode/1.0)"},signal:AbortSignal.timeout(15e3)}),o=e.headers.get("content-type")||"";if(o.startsWith("image/")){let n=await e.arrayBuffer();return {text:`[image: ${r}]`,imageB64:Buffer.from(n).toString("base64")}}let t=await e.text();if(o.includes("application/json"))try{return {text:JSON.stringify(JSON.parse(t),null,2)}}catch{}return {text:t.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/[ \t]{2,}/g," ").replace(/\n{3,}/g,`
146
+ ${s.slice(0,2e4)}`}}async function To(r){let e=await fetch(r,{headers:{"User-Agent":"Mozilla/5.0 (compatible; LocalCode/1.0)"},signal:AbortSignal.timeout(15e3)}),o=e.headers.get("content-type")||"";if(o.startsWith("image/")){let n=await e.arrayBuffer();return {text:`[image: ${r}]`,imageB64:Buffer.from(n).toString("base64")}}let t=await e.text();if(o.includes("application/json"))try{return {text:JSON.stringify(JSON.parse(t),null,2)}}catch{}return {text:t.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/[ \t]{2,}/g," ").replace(/\n{3,}/g,`
147
147
 
148
- `).trim()}}async function jr(r,e,o,t){if(!e.startsWith("http://")&&!e.startsWith("https://"))return {success:false,output:"",error:"URL must start with http:// or https://"};let n={method:r.toUpperCase(),headers:{"Content-Type":"application/json",...o},signal:AbortSignal.timeout(15e3)};t!==void 0&&r.toUpperCase()!=="GET"&&(n.body=typeof t=="string"?t:JSON.stringify(t));let s=await fetch(e,n),l=await s.text(),c;try{c=JSON.stringify(JSON.parse(l),null,2);}catch{c=l;}return {success:s.ok,output:`HTTP ${s.status} ${s.statusText}
148
+ `).trim()}}async function qr(r,e,o,t){if(!e.startsWith("http://")&&!e.startsWith("https://"))return {success:false,output:"",error:"URL must start with http:// or https://"};let n={method:r.toUpperCase(),headers:{"Content-Type":"application/json",...o},signal:AbortSignal.timeout(15e3)};t!==void 0&&r.toUpperCase()!=="GET"&&(n.body=typeof t=="string"?t:JSON.stringify(t));let s=await fetch(e,n),l=await s.text(),a;try{a=JSON.stringify(JSON.parse(l),null,2);}catch{a=l;}return {success:s.ok,output:`HTTP ${s.status} ${s.statusText}
149
149
 
150
- ${c.slice(0,1e4)}`,error:s.ok?void 0:`HTTP ${s.status}`}}async function Ur(r,e){let o=r==="."?void 0:resolve(e,r),{diagnostics:t,tool:n,error:s}=await dt(e,o);if(s&&t.length===0)return {success:false,output:"",error:s};if(t.length===0)return {success:true,output:`\u2713 No issues found (${n})`};let l=t.filter(u=>u.severity==="error").length,c=t.filter(u=>u.severity==="warning").length,a=[`${n}: ${l} error${l!==1?"s":""}, ${c} warning${c!==1?"s":""}`,"",...t.slice(0,60).map(u=>`${u.file}:${u.line}:${u.col} ${u.severity} ${u.message}${u.code?` [${u.code}]`:""}`)];return t.length>60&&a.push(`\u2026 and ${t.length-60} more`),{success:l===0,output:a.join(`
151
- `),error:l>0?`${l} error(s)`:void 0}}var Fe=Pe.join(Ht.homedir(),".localcode"),ft=Pe.join(Fe,"config.json"),Et=Pe.join(Fe,"history.json"),Ge=Pe.join(Fe,"sessions"),ke=class r{static instance;config;constructor(){this.config=this.load();}static getInstance(){return r.instance||(r.instance=new r),r.instance}load(){try{if(j.existsSync(Fe)||j.mkdirSync(Fe,{recursive:!0}),j.existsSync(ft)){let e=j.readFileSync(ft,"utf-8");return {...St,...JSON.parse(e)}}}catch{}return {...St}}get(){return this.config}set(e){this.config={...this.config,...e},this.save();}setLLM(e){this.config.llm={...this.config.llm,...e},this.save();}save(){try{j.existsSync(Fe)||j.mkdirSync(Fe,{recursive:!0}),j.writeFileSync(ft,JSON.stringify(this.config,null,2),"utf-8");}catch{}}getHistory(){try{if(j.existsSync(Et))return JSON.parse(j.readFileSync(Et,"utf-8"))}catch{}return []}addHistory(e){try{let o=this.getHistory(),t=[e,...o.filter(n=>n!==e)].slice(0,500);j.writeFileSync(Et,JSON.stringify(t),"utf-8");}catch{}}getConfigPath(){return ft}ensureSessions(){j.existsSync(Ge)||j.mkdirSync(Ge,{recursive:true});}listSessions(){try{return this.ensureSessions(),j.readdirSync(Ge).filter(e=>e.endsWith(".json")).map(e=>e.slice(0,-5)).sort()}catch{return []}}saveSession(e,o){try{this.ensureSessions();let t=Pe.join(Ge,`${e}.json`);j.writeFileSync(t,JSON.stringify(o,null,2),"utf-8");}catch{}}loadSession(e){try{let o=Pe.join(Ge,`${e}.json`);return j.existsSync(o)?JSON.parse(j.readFileSync(o,"utf-8")):null}catch{return null}}deleteSession(e){try{let o=Pe.join(Ge,`${e}.json`);j.existsSync(o)&&j.unlinkSync(o);}catch{}}};var Wr=[{pattern:/rm\s+-[rf]{1,3}\s+[/~]/i,reason:"Recursive deletion of system or home paths"},{pattern:/rm\s+--recursive.*--force/i,reason:"Force-recursive file deletion"},{pattern:/sudo\s+rm/i,reason:"Privileged file deletion via sudo"},{pattern:/:\(\)\s*\{.*\|.*\}/,reason:"Fork bomb \u2014 infinite process spawn"},{pattern:/\bshutdown\b/i,reason:"System shutdown command"},{pattern:/\breboot\b/i,reason:"System reboot command"},{pattern:/\bhalt\b/i,reason:"System halt command"},{pattern:/\bmkfs\b/i,reason:"Disk formatting command"},{pattern:/dd\s+if=.*of=\/dev/i,reason:"Direct disk write via dd"},{pattern:/git\s+push\s+.*--force/i,reason:"Force-push overwrites remote history"},{pattern:/git\s+reset\s+--hard\s+HEAD~\d+/i,reason:"Hard reset discards committed history"},{pattern:/DROP\s+(TABLE|DATABASE)/i,reason:"Destructive SQL operation (DROP)"},{pattern:/TRUNCATE\s+TABLE/i,reason:"Destructive SQL operation (TRUNCATE)"},{pattern:/rd\s+\/s\s+\/q/i,reason:"Recursive directory deletion (cmd.exe)"},{pattern:/rmdir\s+\/s/i,reason:"Recursive directory deletion (cmd.exe)"},{pattern:/del\s+.*\/[fFsS].*\/[qQ]/i,reason:"Force-delete all files (cmd.exe)"},{pattern:/format\s+[A-Za-z]:/i,reason:"Disk format command (Windows)"},{pattern:/Remove-Item\s+.*-Recurse\s+.*-Force/i,reason:"Force-recursive deletion (PowerShell)"},{pattern:/Remove-Item\s+.*-Force\s+.*-Recurse/i,reason:"Force-recursive deletion (PowerShell)"},{pattern:/Clear-Disk\b/i,reason:"Disk wipe command (PowerShell)"},{pattern:/Reset-ComputerMachinePassword\b/i,reason:"System credential reset (PowerShell)"}],Hr=[/git\s+push(?!\s+--dry-run)/i,/git\s+reset/i,/npm\s+publish/i,/docker\s+rm/i,/kubectl\s+delete/i,/terraform\s+destroy/i,/\bmkdir\b/i,/\btouch\b/i,/\bcp\b/i,/\bmv\b/i,/\brename\b/i,/\brm\b/i,/\brmdir\b/i],gt=class{static check(e){let o=e.trim();for(let{pattern:t,reason:n}of Wr)if(t.test(o))return {safe:false,reason:n};for(let t of Hr)if(t.test(o))return {safe:true,requiresConfirmation:true,reason:"This command may have irreversible effects"};return {safe:true}}};var zr=/^(hi|hey|hello|sup|yo|hallo|hej|ciao|howdy|how are you|what can you do|what are you|who are you|thanks|thank you|danke|ok|okay|cool|nice|great|good|yes|no|nope|yep|sure|help me|what\??)[\s!?.]*$/i,Yr=new Set(["read_file","list_files","find_files","search_files","git_status","git_diff","git_log","lsp_check"]),ht=class extends EventEmitter{aborted=false;confirmResolve=null;injectionQueue=[];abort(){this.aborted=true,this.confirmResolve?.(false),this.confirmResolve=null;}confirm(e){this.confirmResolve?.(e),this.confirmResolve=null;}inject(e){this.injectionQueue.push(e);}async run(e,o,t=[],n="build"){this.aborted=false;let s=ke.getInstance().get(),l=o||s.workspaceDir||Ht.homedir(),c=t.filter(T=>T.type==="file").map(T=>`<file path="${T.name}">
152
- ${T.data}
150
+ ${a.slice(0,1e4)}`,error:s.ok?void 0:`HTTP ${s.status}`}}async function Yr(r,e){let o=r==="."?void 0:resolve(e,r),{diagnostics:t,tool:n,error:s}=await ct(e,o);if(s&&t.length===0)return {success:false,output:"",error:s};if(t.length===0)return {success:true,output:`\u2713 No issues found (${n})`};let l=t.filter(u=>u.severity==="error").length,a=t.filter(u=>u.severity==="warning").length,c=[`${n}: ${l} error${l!==1?"s":""}, ${a} warning${a!==1?"s":""}`,"",...t.slice(0,60).map(u=>`${u.file}:${u.line}:${u.col} ${u.severity} ${u.message}${u.code?` [${u.code}]`:""}`)];return t.length>60&&c.push(`\u2026 and ${t.length-60} more`),{success:l===0,output:c.join(`
151
+ `),error:l>0?`${l} error(s)`:void 0}}var Fe=Pe.join(Jt.homedir(),".localcode"),mt=Pe.join(Fe,"config.json"),Nt=Pe.join(Fe,"history.json"),Xe=Pe.join(Fe,"sessions"),_e=class r{static instance;config;constructor(){this.config=this.load();}static getInstance(){return r.instance||(r.instance=new r),r.instance}load(){try{if(U.existsSync(Fe)||U.mkdirSync(Fe,{recursive:!0}),U.existsSync(mt)){let e=U.readFileSync(mt,"utf-8");return {...$t,...JSON.parse(e)}}}catch{}return {...$t}}get(){return this.config}set(e){this.config={...this.config,...e},this.save();}setLLM(e){this.config.llm={...this.config.llm,...e},this.save();}save(){try{U.existsSync(Fe)||U.mkdirSync(Fe,{recursive:!0}),U.writeFileSync(mt,JSON.stringify(this.config,null,2),"utf-8");}catch{}}getHistory(){try{if(U.existsSync(Nt))return JSON.parse(U.readFileSync(Nt,"utf-8"))}catch{}return []}addHistory(e){try{let o=this.getHistory(),t=[e,...o.filter(n=>n!==e)].slice(0,500);U.writeFileSync(Nt,JSON.stringify(t),"utf-8");}catch{}}getConfigPath(){return mt}ensureSessions(){U.existsSync(Xe)||U.mkdirSync(Xe,{recursive:true});}listSessions(){try{return this.ensureSessions(),U.readdirSync(Xe).filter(e=>e.endsWith(".json")).map(e=>e.slice(0,-5)).sort()}catch{return []}}saveSession(e,o){try{this.ensureSessions();let t=Pe.join(Xe,`${e}.json`);U.writeFileSync(t,JSON.stringify(o,null,2),"utf-8");}catch{}}loadSession(e){try{let o=Pe.join(Xe,`${e}.json`);return U.existsSync(o)?JSON.parse(U.readFileSync(o,"utf-8")):null}catch{return null}}deleteSession(e){try{let o=Pe.join(Xe,`${e}.json`);U.existsSync(o)&&U.unlinkSync(o);}catch{}}};var zr=[{pattern:/rm\s+-[rf]{1,3}\s+[/~]/i,reason:"Recursive deletion of system or home paths"},{pattern:/rm\s+--recursive.*--force/i,reason:"Force-recursive file deletion"},{pattern:/sudo\s+rm/i,reason:"Privileged file deletion via sudo"},{pattern:/:\(\)\s*\{.*\|.*\}/,reason:"Fork bomb \u2014 infinite process spawn"},{pattern:/\bshutdown\b/i,reason:"System shutdown command"},{pattern:/\breboot\b/i,reason:"System reboot command"},{pattern:/\bhalt\b/i,reason:"System halt command"},{pattern:/\bmkfs\b/i,reason:"Disk formatting command"},{pattern:/dd\s+if=.*of=\/dev/i,reason:"Direct disk write via dd"},{pattern:/git\s+push\s+.*--force/i,reason:"Force-push overwrites remote history"},{pattern:/git\s+reset\s+--hard\s+HEAD~\d+/i,reason:"Hard reset discards committed history"},{pattern:/DROP\s+(TABLE|DATABASE)/i,reason:"Destructive SQL operation (DROP)"},{pattern:/TRUNCATE\s+TABLE/i,reason:"Destructive SQL operation (TRUNCATE)"},{pattern:/rd\s+\/s\s+\/q/i,reason:"Recursive directory deletion (cmd.exe)"},{pattern:/rmdir\s+\/s/i,reason:"Recursive directory deletion (cmd.exe)"},{pattern:/del\s+.*\/[fFsS].*\/[qQ]/i,reason:"Force-delete all files (cmd.exe)"},{pattern:/format\s+[A-Za-z]:/i,reason:"Disk format command (Windows)"},{pattern:/Remove-Item\s+.*-Recurse\s+.*-Force/i,reason:"Force-recursive deletion (PowerShell)"},{pattern:/Remove-Item\s+.*-Force\s+.*-Recurse/i,reason:"Force-recursive deletion (PowerShell)"},{pattern:/Clear-Disk\b/i,reason:"Disk wipe command (PowerShell)"},{pattern:/Reset-ComputerMachinePassword\b/i,reason:"System credential reset (PowerShell)"}],Jr=[/git\s+push(?!\s+--dry-run)/i,/git\s+reset/i,/npm\s+publish/i,/docker\s+rm/i,/kubectl\s+delete/i,/terraform\s+destroy/i,/\bmkdir\b/i,/\btouch\b/i,/\bcp\b/i,/\bmv\b/i,/\brename\b/i,/\brm\b/i,/\brmdir\b/i],pt=class{static check(e){let o=e.trim();for(let{pattern:t,reason:n}of zr)if(t.test(o))return {safe:false,reason:n};for(let t of Jr)if(t.test(o))return {safe:true,requiresConfirmation:true,reason:"This command may have irreversible effects"};return {safe:true}}};var Zr=/^(hi|hey|hello|sup|yo|hallo|hej|ciao|howdy|how are you|what can you do|what are you|who are you|thanks|thank you|danke|ok|okay|cool|nice|great|good|yes|no|nope|yep|sure|help me|what\??)[\s!?.]*$/i,Rr=new Set(["read_file","list_files","find_files","search_files","git_status","git_diff","git_log","lsp_check"]),ft=class extends EventEmitter{aborted=false;confirmResolve=null;injectionQueue=[];abort(){this.aborted=true,this.confirmResolve?.(false),this.confirmResolve=null;}confirm(e){this.confirmResolve?.(e),this.confirmResolve=null;}inject(e){this.injectionQueue.push(e);}async run(e,o,t=[],n="build",s=[]){this.aborted=false;let l=_e.getInstance().get(),a=o||l.workspaceDir||Jt.homedir(),c=t.filter(x=>x.type==="file").map(x=>`<file path="${x.name}">
152
+ ${x.data}
153
153
  </file>`).join(`
154
- `),a=t.filter(T=>T.type==="image").map(T=>T.data),u=e,d=/https?:\/\/\S+/g,p=[...e.matchAll(d)];for(let T of p){let $=T[0].replace(/[.,;!?)]+$/,"");try{let b=await fetch($,{signal:AbortSignal.timeout(1e4)});if((b.headers.get("content-type")||"").startsWith("image/")){let Ae=await b.arrayBuffer();a.push(Buffer.from(Ae).toString("base64")),u=u.replace($,"[attached image]");}}catch{}}let y=c?`${c}
154
+ `),u=t.filter(x=>x.type==="image").map(x=>x.data),d=e,p=/https?:\/\/\S+/g,T=[...e.matchAll(p)];for(let x of T){let E=x[0].replace(/[.,;!?)]+$/,"");try{let B=await fetch(E,{signal:AbortSignal.timeout(1e4)});if((B.headers.get("content-type")||"").startsWith("image/")){let se=await B.arrayBuffer();u.push(Buffer.from(se).toString("base64")),d=d.replace(E,"[attached image]");}}catch{}}let h=c?`${c}
155
155
 
156
- Task: ${u}
156
+ Task: ${d}
157
157
 
158
- Working directory: ${l}`:`Task: ${u}
158
+ Working directory: ${a}`:`Task: ${d}
159
159
 
160
- Working directory: ${l}`;if(zr.test(e.trim())&&!t.length){this.emit("thinking");let T="",$=[{role:"system",content:"You are LocalCode, a helpful AI coding agent. Reply concisely and directly. Do NOT call any tools. End your reply with DONE: <reply>."},{role:"user",content:e}];try{await oe.stream($,s.llm,b=>{this.emit("token",b),T+=b;});}catch(b){this.emit("error",Mt(b,s.llm)),this.emit("done",{response:""});return}this.emit("done",{response:T||"DONE: Hey! I'm LocalCode. Give me a coding task and I'll get to work."});return}if(n==="plan"){this.emit("thinking");let T="",$=[{role:"system",content:Gt},{role:"user",content:y,...a.length?{images:a}:{}}];try{await oe.stream($,s.llm,b=>{this.emit("token",b),T+=b;});}catch(b){this.emit("error",Mt(b,s.llm)),this.emit("done",{response:""});return}this.emit("done",{response:T});return}let x=he.getInstance().getTools(),S=x.length>0?`
160
+ Working directory: ${a}`;if(Zr.test(e.trim())&&!t.length){this.emit("thinking");let x="",E=[{role:"system",content:"You are LocalCode, a helpful AI coding agent. Reply concisely and directly. Do NOT call any tools. End your reply with DONE: <reply>."},{role:"user",content:e}];try{await Z.stream(E,l.llm,B=>{this.emit("token",B),x+=B;});}catch(B){this.emit("error",jt(B,l.llm)),this.emit("done",{response:""});return}this.emit("done",{response:x||"DONE: Hey! I'm LocalCode. Give me a coding task and I'll get to work."});return}if(n==="plan"){this.emit("thinking");let x="",E=[{role:"system",content:Qt},{role:"user",content:h,...u.length?{images:u}:{}}];try{await Z.stream(E,l.llm,B=>{this.emit("token",B),x+=B;});}catch(B){this.emit("error",jt(B,l.llm)),this.emit("done",{response:""});return}this.emit("done",{response:x});return}let y=he.getInstance().getTools(),Q=y.length>0?`
161
161
 
162
162
  ### Plugin Tools
163
- `+x.map(T=>`- **${T.name}**: ${T.description}
164
- {"tool": "${T.name}", "arguments": {}}`).join(`
165
- `):"",G=[{role:"system",content:Xt+S},{role:"user",content:y,...a.length?{images:a}:{}}];this.emit("start",{instruction:e,cwd:l}),this.injectionQueue=[];for(let T=0;T<qt;T++){if(this.aborted){this.emit("done",{response:"Task aborted by user.",aborted:true});return}for(;this.injectionQueue.length>0;){let I=this.injectionQueue.shift();this.emit("injection",{message:I}),G.push({role:"user",content:`[User message during task]: ${I}`});}this.emit("thinking");let $="";try{await oe.stream(G,s.llm,I=>{this.emit("token",I),$+=I;});}catch(I){let le=Mt(I,s.llm);this.emit("error",le),this.emit("done",{response:""});return}G.push({role:"assistant",content:$});let b=Vr($);if(!b){let I=bo($);this.emit("done",{response:I});return}if(b.tool==="run_shell"){let I=String(b.arguments.command||""),le=gt.check(I);if(!le.safe){let ne={success:false,output:"",error:`Blocked: ${le.reason}`};this.emit("tool_call",{toolCall:b,blocked:true,reason:le.reason}),this.emit("tool_result",{toolCall:b,result:ne}),G.push({role:"user",content:`Command was blocked by security guard: ${le.reason}. Choose a safer approach.`});continue}}if(!Yr.has(b.tool)){let I;if(b.tool==="edit_file"){let xe=String(b.arguments.path||""),ye=String(b.arguments.old||""),Oe=String(b.arguments.new||"");try{let Ie=await readFile(resolve(l,xe),"utf-8");if(Ie.includes(ye)){let rt=Ie.indexOf(ye),_e=Ie.slice(0,rt).split(`
166
- `).length,qe=Ie.split(`
167
- `),Ee=ye.split(`
168
- `),Me=3;I={filePath:xe,oldLines:Ee,newLines:Oe.split(`
169
- `),startLine:_e,contextBefore:qe.slice(Math.max(0,_e-1-Me),_e-1),contextAfter:qe.slice(_e-1+Ee.length,_e-1+Ee.length+Me)};}}catch{}}let le=Jr(b);this.emit("confirm_required",{toolCall:b,reason:le,diffPreview:I});let{confirmed:ne,timedOut:Be}=await this.waitForConfirmation();if(!ne){let xe={success:false,output:"",error:Be?"Confirmation timed out":"Denied by user"};this.emit("tool_result",{toolCall:b,result:xe}),this.emit("done",{response:Be?"No response in 30 seconds \u2014 task stopped.":"Task stopped \u2014 action denied by user.",aborted:true});return}}this.emit("tool_call",{toolCall:b});let J=await yo(b,l);this.emit("tool_result",{toolCall:b,result:J});let Ae={role:"user",content:`Tool "${b.tool}" result:
170
- ${J.success?J.output:`ERROR: ${J.error||"Unknown error"}`}`};if(G.push(Ae),$.includes("DONE:")){let I=bo($);if(I){this.emit("done",{response:I});return}}}this.emit("done",{response:"Reached maximum iteration limit."});}waitForConfirmation(){return new Promise(e=>{this.confirmResolve=o=>e({confirmed:o,timedOut:false}),setTimeout(()=>{this.confirmResolve&&(this.confirmResolve=null,e({confirmed:false,timedOut:true}));},3e4);})}};function Jr(r){let e=r.arguments;switch(r.tool){case "run_shell":return `Shell: ${String(e.command||"")}`;case "read_file":return `Read file: ${String(e.path||"")}`;case "write_file":return `Write file: ${String(e.path||"")}`;case "append_file":return `Append to file: ${String(e.path||"")}`;case "edit_file":return `Edit file: ${String(e.path||"")}`;case "delete_file":return `Delete: ${String(e.path||"")}`;case "move_file":return `Move: ${String(e.from||"")} \u2192 ${String(e.to||"")}`;case "copy_file":return `Copy: ${String(e.from||"")} \u2192 ${String(e.to||"")}`;case "create_dir":return `Create directory: ${String(e.path||"")}`;case "list_files":return `List files: ${String(e.path||".")}`;case "find_files":return `Find files: "${String(e.pattern||"")}" in ${String(e.path||".")}`;case "search_files":return `Search "${String(e.pattern||"")}" in ${String(e.path||".")}`;case "git_status":return "git status";case "git_diff":return "git diff";case "git_log":return `git log (last ${String(e.limit||20)})`;case "git_commit":return `git commit: ${String(e.message||"")}`;case "web_fetch":return `Fetch URL: ${String(e.url||"")}`;case "http_request":return `${String(e.method||"GET")} ${String(e.url||"")}`;case "lsp_check":return `LSP check: ${String(e.path||".")}`;default:return r.tool}}function bo(r){let e=r;e=e.replace(/```json[\s\S]*?```/gi,""),e=e.replace(/\{[\s\S]*?"tool"\s*:[\s\S]*?"arguments"\s*:[\s\S]*?\}/g,"");let o=e.match(/^([\s\S]+?)\s*DONE:\s*(?:<[^>]*>)?/i);if(o&&o[1].trim())return o[1].trim();let t=e.match(/DONE:\s*(?:<([^>]*)>|([\s\S]*))/);return t&&(e=(t[1]||t[2]||"").trim()),e.trim()}function Mt(r,e){let o=String(r),t=o.toLowerCase();return t.includes("fetch failed")||t.includes("econnrefused")||t.includes("econnreset")||t.includes("network")?e.provider==="ollama"?["Ollama is not reachable.",""," \u2022 Start Ollama: ollama serve"," \u2022 Pull model: ollama pull "+e.model," \u2022 URL: "+(e.baseURL||"http://localhost:11434"),""," Switch provider: /config provider lmstudio"].join(`
163
+ `+y.map(x=>`- **${x.name}**: ${x.description}
164
+ {"tool": "${x.name}", "arguments": {}}`).join(`
165
+ `):"",D=[{role:"system",content:Vt+Q},...s,{role:"user",content:h,...u.length?{images:u}:{}}];this.emit("start",{instruction:e,cwd:a}),this.injectionQueue=[];for(let x=0;x<Kt;x++){if(this.aborted){this.emit("done",{response:"Task aborted by user.",aborted:true});return}for(;this.injectionQueue.length>0;){let G=this.injectionQueue.shift();this.emit("injection",{message:G}),D.push({role:"user",content:`[User message during task]: ${G}`});}this.emit("thinking");let E="";try{await Z.stream(D,l.llm,G=>{this.emit("token",G),E+=G;});}catch(G){let oe=jt(G,l.llm);this.emit("error",oe),this.emit("done",{response:""});return}D.push({role:"assistant",content:E});let B=tn(E);if(!B){let G=Ao(E);this.emit("done",{response:G});return}if(B.tool==="run_shell"){let G=String(B.arguments.command||""),oe=pt.check(G);if(!oe.safe){let xe={success:false,output:"",error:`Blocked: ${oe.reason}`};this.emit("tool_call",{toolCall:B,blocked:true,reason:oe.reason}),this.emit("tool_result",{toolCall:B,result:xe}),D.push({role:"user",content:`Command was blocked by security guard: ${oe.reason}. Choose a safer approach.`});continue}}if(!Rr.has(B.tool)){let G;if(B.tool==="edit_file"){let ue=String(B.arguments.path||""),we=String(B.arguments.old||""),Tt=String(B.arguments.new||"");try{let Me=await readFile(resolve(a,ue),"utf-8");if(Me.includes(we)){let bt=Me.indexOf(we),Ce=Me.slice(0,bt).split(`
166
+ `).length,Oe=Me.split(`
167
+ `),Be=we.split(`
168
+ `),et=3;G={filePath:ue,oldLines:Be,newLines:Tt.split(`
169
+ `),startLine:Ce,contextBefore:Oe.slice(Math.max(0,Ce-1-et),Ce-1),contextAfter:Oe.slice(Ce-1+Be.length,Ce-1+Be.length+et)};}}catch{}}let oe=en(B);this.emit("confirm_required",{toolCall:B,reason:oe,diffPreview:G});let{confirmed:xe,timedOut:Ee}=await this.waitForConfirmation();if(!xe){let ue={success:false,output:"",error:Ee?"Confirmation timed out":"Denied by user"};this.emit("tool_result",{toolCall:B,result:ue}),this.emit("done",{response:Ee?"No response in 30 seconds \u2014 task stopped.":"Task stopped \u2014 action denied by user.",aborted:true});return}}this.emit("tool_call",{toolCall:B});let ce=await Co(B,a);this.emit("tool_result",{toolCall:B,result:ce});let se={role:"user",content:`Tool "${B.tool}" result:
170
+ ${ce.success?ce.output:`ERROR: ${ce.error||"Unknown error"}`}`};if(D.push(se),E.includes("DONE:")){let G=Ao(E);if(G){this.emit("done",{response:G});return}}}this.emit("done",{response:"Reached maximum iteration limit."});}waitForConfirmation(){return new Promise(e=>{this.confirmResolve=o=>e({confirmed:o,timedOut:false}),setTimeout(()=>{this.confirmResolve&&(this.confirmResolve=null,e({confirmed:false,timedOut:true}));},3e4);})}};function en(r){let e=r.arguments;switch(r.tool){case "run_shell":return `Shell: ${String(e.command||"")}`;case "read_file":return `Read file: ${String(e.path||"")}`;case "write_file":return `Write file: ${String(e.path||"")}`;case "append_file":return `Append to file: ${String(e.path||"")}`;case "edit_file":return `Edit file: ${String(e.path||"")}`;case "delete_file":return `Delete: ${String(e.path||"")}`;case "move_file":return `Move: ${String(e.from||"")} \u2192 ${String(e.to||"")}`;case "copy_file":return `Copy: ${String(e.from||"")} \u2192 ${String(e.to||"")}`;case "create_dir":return `Create directory: ${String(e.path||"")}`;case "list_files":return `List files: ${String(e.path||".")}`;case "find_files":return `Find files: "${String(e.pattern||"")}" in ${String(e.path||".")}`;case "search_files":return `Search "${String(e.pattern||"")}" in ${String(e.path||".")}`;case "git_status":return "git status";case "git_diff":return "git diff";case "git_log":return `git log (last ${String(e.limit||20)})`;case "git_commit":return `git commit: ${String(e.message||"")}`;case "web_fetch":return `Fetch URL: ${String(e.url||"")}`;case "http_request":return `${String(e.method||"GET")} ${String(e.url||"")}`;case "lsp_check":return `LSP check: ${String(e.path||".")}`;default:return r.tool}}function Ao(r){let e=r;e=e.replace(/```json[\s\S]*?```/gi,""),e=e.replace(/\{[\s\S]*?"tool"\s*:[\s\S]*?"arguments"\s*:[\s\S]*?\}/g,"");let o=e.match(/^([\s\S]+?)\s*DONE:\s*(?:<[^>]*>)?/i);if(o&&o[1].trim())return o[1].trim();let t=e.match(/DONE:\s*(?:<([^>]*)>|([\s\S]*))/);return t&&(e=(t[1]||t[2]||"").trim()),e.trim()}function jt(r,e){let o=String(r),t=o.toLowerCase();return t.includes("fetch failed")||t.includes("econnrefused")||t.includes("econnreset")||t.includes("network")?e.provider==="ollama"?["Ollama is not reachable.",""," \u2022 Start Ollama: ollama serve"," \u2022 Pull model: ollama pull "+e.model," \u2022 URL: "+(e.baseURL||"http://localhost:11434"),""," Switch provider: /config provider lmstudio"].join(`
171
171
  `):e.provider==="lmstudio"?["LM Studio is not reachable.",""," \u2022 Open LM Studio and start a Local Server"," \u2022 URL: "+(e.baseURL||"http://localhost:1234/v1"),""," Change URL: /config url http://localhost:1234/v1"].join(`
172
172
  `):[`Connection failed (${e.provider}).`," Check URL: /config url <url>"].join(`
173
173
  `):t.includes("model")&&(t.includes("not found")||t.includes("does not exist"))||t.includes("404")?[`Model "${e.model}" not found.`,""," \u2022 Switch model: /config model <name>"," \u2022 List models: /models"].join(`
174
- `):o}function Vr(r){for(let e=0;e<r.length;e++){if(r[e]!=="{")continue;let o=0,t=false,n=false,s=e;for(;s<r.length;s++){let c=r[s];if(n){n=false;continue}if(c==="\\"&&t){n=true;continue}if(c==='"'){t=!t;continue}if(!t){if(c==="{")o++;else if(c==="}"&&(o--,o===0))break}}if(o!==0)continue;let l=r.slice(e,s+1);try{let c=JSON.parse(l);if(typeof c.tool=="string"&&c.arguments!==null&&typeof c.arguments=="object")return c}catch{}}return null}var xt=class extends EventEmitter{shell=null;_cwd;_alive=false;constructor(e,o){super(),this._cwd=e;let t=o||(process.platform==="win32"?"powershell.exe":process.platform==="darwin"?process.env.SHELL||"zsh":process.env.SHELL||"bash");try{let n=Oo("node-pty");this.shell=n.spawn(t,[],{name:"xterm-256color",cols:process.stdout.columns||80,rows:10,cwd:e,env:process.env}),this._alive=!0,this.shell.onData(s=>this.emit("data",s)),this.shell.onExit(({exitCode:s})=>{this._alive=!1,this.emit("exit",s);});}catch{}}write(e){this.shell?.write(e);}resize(e,o){try{this.shell?.resize(e,o);}catch{}}get cwd(){return this._cwd}isAlive(){return this._alive}kill(){try{this.shell?.kill();}catch{}this.shell=null,this._alive=false;}};var ln=new Set([".jpg",".jpeg",".png",".gif",".webp",".bmp",".svg"]),an=new Set(["node_modules",".git","dist","__pycache__",".next","build","target"]);async function yt(r,e){let o=resolve(e,r);if(!existsSync(o))return null;let t=basename(o),n=extname(o).toLowerCase();if(ln.has(n)){let l=await readFile(o),c=n===".png"?"image/png":n===".gif"?"image/gif":n===".webp"?"image/webp":"image/jpeg";return {path:o,name:t,type:"image",data:l.toString("base64"),mimeType:c}}let s=await readFile(o,"utf-8").catch(()=>null);return s===null?null:{path:o,name:t,type:"file",data:s}}async function cn(r,e=2){let o=[];async function t(n,s,l){if(l>e||o.length>300)return;let c;try{c=await readdir(n,{withFileTypes:!0});}catch{return}for(let a of c){if(an.has(a.name))continue;let u=s?`${s}/${a.name}`:a.name;a.isDirectory()?(o.push(u+"/"),await t(join(n,a.name),u,l+1)):o.push(u);}}return await t(r,"",0),o}var un=0,dn=()=>String(++un);function mn(r){let e=[],o=[],t=()=>{o.length>0&&(e.push({type:"agent",messages:o}),o=[]);};for(let n of r)n.type==="text"&&n.content.startsWith("> ")?(t(),e.push({type:"user",content:n.content.slice(2),timestamp:n.timestamp})):o.push(n);return t(),e}function Ot(r,e){return r.split(`
175
- `).reduce((o,t)=>o+Math.max(1,Math.ceil((t.length||1)/Math.max(1,e))),0)}function pn(r,e){if(r.type==="user")return 4;let o=0;for(let t of r.messages)if(t.type==="error")o+=Ot(t.content,e);else if(t.type==="command")o+=t.content.split(`
176
- `).length+(t.commandTitle?1:0)+2;else if(t.type==="text")o+=Ot(t.content,e);else if(t.type==="done"&&t.content)o+=Ot(t.content.replace(/^DONE:\s*/i,"").trim(),e);else if(t.type==="tool_result"&&t.toolCall?.tool==="edit_file"&&t.toolResult?.meta){let n=t.toolResult.meta;o+=(n.diffContextBefore?.length??0)+(n.diffOld?.length??0)+(n.diffNew?.length??0)+(n.diffContextAfter?.length??0)+4;}else o+=1;return Math.max(2,o+2)}function fn(r,e,o,t){let n=[],s=0,l=Math.max(0,r.length-t),c=r.length-l;for(let a=l-1;a>=0;a--){let u=pn(r[a],o);if(s+u>e)return n.length===0?(n.unshift(r[a]),{visible:n,hiddenAbove:a,hiddenBelow:c}):{visible:n,hiddenAbove:a+1,hiddenBelow:c};n.unshift(r[a]),s+=u;}return {visible:n,hiddenAbove:0,hiddenBelow:c}}function wo(r){return new Date(r).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}var gn=({content:r,timestamp:e})=>i.createElement(Box,{flexDirection:"column",marginBottom:1,marginX:1,borderStyle:"single",borderColor:"#1D4ED8"},i.createElement(Box,{paddingX:1},i.createElement(Text,{color:"#3B82F6",bold:true},"# "),i.createElement(Text,{color:"#E5E7EB",bold:true},r)),i.createElement(Box,{paddingX:1},i.createElement(Text,{color:"#374151"},wo(e)))),hn=({msg:r})=>{switch(r.type){case "text":return i.createElement(Bt,{content:r.content});case "command":{let e=r.content.split(`
177
- `);return i.createElement(Box,{flexDirection:"column",marginBottom:1,paddingLeft:2},r.commandTitle&&i.createElement(Box,{marginBottom:0},i.createElement(Text,{color:"#6B7280"},"\u250C\u2500 "),i.createElement(Text,{color:"#9CA3AF",bold:true},r.commandTitle)),i.createElement(Box,{flexDirection:"column",borderStyle:"single",borderColor:"#374151",paddingX:1},e.map((o,t)=>{if(o.startsWith(" /")||o.startsWith(" $")||o.startsWith(" !")){let s=o.search(/\s{2,}/),l=s>0?o.slice(0,s):o,c=s>0?o.slice(s).trim():"";return i.createElement(Box,{key:t},i.createElement(Text,{color:"#3B82F6"},l),c?i.createElement(Text,{color:"#6B7280"}," ",c):null)}if(o.startsWith("**")&&o.endsWith("**"))return i.createElement(Text,{key:t,color:"#9CA3AF",bold:true},o.replace(/\*\*/g,""));if(o==="")return i.createElement(Text,{key:t}," ");if(/^\s{2}\S.*\s:\s/.test(o)){let s=o.indexOf(" : "),l=o.slice(0,s),c=o.slice(s+3);return i.createElement(Box,{key:t},i.createElement(Text,{color:"#6B7280"},l," "),i.createElement(Text,{color:"#374151"},": "),i.createElement(Text,{color:"#E5E7EB"},c))}return i.createElement(Text,{key:t,color:"#9CA3AF"},o)})))}case "tool_call":{if(!r.toolCall)return null;let e=r.toolCall.arguments,o=(()=>{switch(r.toolCall.tool){case "run_shell":return `$ ${String(e.command||"").slice(0,60)}`;case "read_file":return `Read ${e.path}`;case "write_file":return `Write ${e.path}`;case "append_file":return `Append ${e.path}`;case "edit_file":return null;case "delete_file":return `Delete ${e.path}`;case "move_file":return `Move ${e.from} \u2192 ${e.to}`;case "copy_file":return `Copy ${e.from} \u2192 ${e.to}`;case "create_dir":return `mkdir ${e.path}`;case "list_files":return `ls ${e.path||"."}`;case "find_files":return `find ${e.pattern}`;case "search_files":return `grep "${e.pattern}"`;case "git_status":return "git status";case "git_diff":return "git diff";case "git_log":return "git log";case "git_commit":return `git commit "${String(e.message||"").slice(0,40)}"`;case "web_fetch":return `fetch ${String(e.url||"").slice(0,55)}`;case "http_request":return `${e.method||"GET"} ${String(e.url||"").slice(0,50)}`;case "lsp_check":return `lsp check ${String(e.path||".")}`;default:return r.toolCall.tool}})();return o?i.createElement(Box,{paddingLeft:1},i.createElement(Text,{color:"#4B5563"}," "),i.createElement(Text,{color:"#6B7280"},o)):null}case "tool_result":{if(!r.toolCall||r.toolCall.tool==="edit_file")return null;if(!r.toolResult?.success)return i.createElement(Box,{paddingLeft:1},i.createElement(Text,{color:"#EF4444"}," \u2717 ",(r.toolResult?.error||"").slice(0,80)));let e=(r.toolResult.output||"").split(`
178
- `).filter(Boolean),o=e.length>1?`${e.length} lines`:(e[0]||"").slice(0,50);return i.createElement(Box,{paddingLeft:1},i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#4B5563"},o))}case "error":return i.createElement(Text,{color:"#EF4444",wrap:"wrap"}," \u2717 ",r.content);case "done":{let e=r.content.replace(/```json[\s\S]*?```/gi,"").replace(/\{[\s\S]*?"tool"\s*:[\s\S]*?\}/g,"").replace(/\s*DONE:\s*<[^>]*>/gi,"").replace(/\s*DONE:\s*.*/gi,"").trim();return e?i.createElement(Bt,{content:e}):null}default:return null}},xn=({messages:r,model:e})=>{let o=[],t=[],n=()=>{t.length&&(o.push({type:"content",msgs:t}),t=[]);};for(let a of r)a.type==="tool_result"&&a.toolCall?.tool==="edit_file"&&a.toolResult?.meta?.diffPath?(n(),o.push({type:"diff",msg:a})):t.push(a);n();let l=r.find(a=>a.type==="done")?.timestamp??r[r.length-1]?.timestamp,c=r.some(a=>a.type==="text"&&a.content&&!a.content.startsWith("> ")||a.type==="error"||a.type==="done"&&a.content||a.type==="tool_result"&&a.toolCall?.tool==="edit_file");return i.createElement(Box,{flexDirection:"column",marginBottom:1},o.map((a,u)=>{if(a.type==="diff"){let p=a.msg.toolResult.meta;return i.createElement(Ct,{key:u,filePath:p.diffPath,oldLines:p.diffOld,newLines:p.diffNew,startLine:p.diffStartLine,contextBefore:p.diffContextBefore??[],contextAfter:p.diffContextAfter??[]})}let d=u===o.length-1;return i.createElement(Box,{key:u},i.createElement(Text,{color:"#3B82F6"}," \u2502 "),i.createElement(Box,{flexDirection:"column",flexGrow:1},a.msgs.map(p=>i.createElement(hn,{key:p.id,msg:p})),d&&c&&l&&i.createElement(Box,{marginTop:0},i.createElement(Text,{color:"#374151"},e),i.createElement(Text,{color:"#1D4ED8"}," "),i.createElement(Text,{color:"#374151"},"(",wo(l),")"))))}))};function yn(r){let e=r.indexOf("<think>");if(e===-1)return {thinking:"",response:r,stillThinking:false};let o=r.indexOf("</think>",e);return o===-1?{thinking:r.slice(e+7),response:"",stillThinking:true}:{thinking:r.slice(e+7,o),response:r.slice(o+8).trimStart(),stillThinking:false}}function Tn(r,e){if(r.length<2)return "";let o=e.find(s=>s!==r&&s.toLowerCase().startsWith(r.toLowerCase()));if(o)return o.slice(r.length);let t=Ve.find(s=>s.cmd.startsWith(r)&&s.cmd!==r);if(t)return t.cmd.slice(r.length);let n=lt.find(s=>s.startsWith(r)&&s!==r);return n?n.slice(r.length):""}var Co=({initialCommand:r,cwd:e})=>{let{exit:o}=useApp(),t=ke.getInstance(),[n,s]=useState([]),[l,c]=useState("idle"),[a,u]=useState(""),[d,p]=useState(0),[y,x]=useState(()=>t.getHistory()),[S,G]=useState(null),[T,$]=useState(""),[b,J]=useState(-1),[Ae,I]=useState(0),[le,ne]=useState(0),[Be,xe]=useState(false),[ye,Oe]=useState(false),[Ie,rt]=useState([]),[_e,qe]=useState(false),[Ee,Me]=useState(false),[Lo,$o]=useState([]),[ze,nt]=useState([]),[ae,Po]=useState("build"),[ko,st]=useState([]),de=useRef(null),Tt=useRef(null),[jt,_o]=useState(process.stdout.rows||24),[Ut,Eo]=useState(process.stdout.columns||80),Wt=useRef({agentStatus:l,isRunning:false,attachments:ze,mode:ae,pickerIdx:Ae,messages:n});Wt.current={agentStatus:l,isRunning:l==="thinking"||l==="running",attachments:ze,mode:ae,pickerIdx:Ae,messages:n};let Ye=n.length===0&&l==="idle"&&!S,Mo=[...Ve,...ko],Je=T.startsWith("/")&&l==="idle"&&!Ye&&!Be&&!ye?Mo.filter(h=>h.cmd.toLowerCase().startsWith(T.toLowerCase())).slice(0,7):[],it=Je.length>0,Ne=!Ye&&!it&&!Be&&!ye&&l==="idle"?Tn(T,y):"",je=l==="thinking"||l==="running";useEffect(()=>{let h=()=>{_o(process.stdout.rows||24),Eo(process.stdout.columns||80);};return process.stdout.on("resize",h),()=>{process.stdout.off("resize",h);}},[]),useEffect(()=>{let h=A=>{let z=A.toString().match(/\x1b\[<(\d+);\d+;\d+[Mm]/);if(!z)return;let R=parseInt(z[1]);R===64&&ne(ee=>ee+3),R===65&&ne(ee=>Math.max(0,ee-3));};return process.stdin.on("data",h),()=>{process.stdin.off("data",h);}},[]),useEffect(()=>{try{Tt.current=new xt(e,t.get().shell);}catch{}return ()=>{Tt.current?.kill();}},[]),useEffect(()=>{if(r){let h=setTimeout(()=>bt(r),150);return ()=>clearTimeout(h)}},[]),useEffect(()=>{let h=he.getInstance();h.load(),st(h.getCommands().map(A=>({cmd:A.cmd,description:A.description})));},[]);let g=useCallback(h=>{s(A=>[...A,{...h,id:dn(),timestamp:Date.now()}]),ne(0);},[]),Do=useCallback(h=>{let A=h.trim().replace(/^["']|["']$/g,""),B=/^[A-Za-z]:[\\\/].{2,}/.test(A),z=/^\/[^\s\/]+\/[^\s]*/.test(A);if(B||z){$(""),J(-1),I(0),yt(A,e).then(R=>{R?nt(ee=>[...ee,R]):$(h);});return}$(h),J(-1),I(0);},[e]),bt=useCallback(async h=>{let{agentStatus:A,isRunning:B,attachments:z,mode:R,messages:ee}=Wt.current,C=h.trim();if(C){if($(""),J(-1),I(0),C.startsWith("/config")||C.toLowerCase()==="/config"){let _=C.slice(7).trim(),[L,...D]=_.split(/\s+/),f=D.join(" ").trim();if(L)switch(L.toLowerCase()){case "model":if(!f){g({type:"error",content:"Usage: /config model <model-name>"});break}t.setLLM({model:f}),g({type:"done",content:`Model \u2192 ${f}`});break;case "provider":{if(!f||!["ollama","lmstudio"].includes(f.toLowerCase())){g({type:"error",content:`Available providers: ollama lmstudio
174
+ `):o}function tn(r){for(let e=0;e<r.length;e++){if(r[e]!=="{")continue;let o=0,t=false,n=false,s=e;for(;s<r.length;s++){let a=r[s];if(n){n=false;continue}if(a==="\\"&&t){n=true;continue}if(a==='"'){t=!t;continue}if(!t){if(a==="{")o++;else if(a==="}"&&(o--,o===0))break}}if(o!==0)continue;let l=r.slice(e,s+1);try{let a=JSON.parse(l);if(typeof a.tool=="string"&&a.arguments!==null&&typeof a.arguments=="object")return a}catch{}}return null}var gt=class extends EventEmitter{shell=null;_cwd;_alive=false;constructor(e,o){super(),this._cwd=e;let t=o||(process.platform==="win32"?"powershell.exe":process.platform==="darwin"?process.env.SHELL||"zsh":process.env.SHELL||"bash");try{let n=Ho("node-pty");this.shell=n.spawn(t,[],{name:"xterm-256color",cols:process.stdout.columns||80,rows:10,cwd:e,env:process.env}),this._alive=!0,this.shell.onData(s=>this.emit("data",s)),this.shell.onExit(({exitCode:s})=>{this._alive=!1,this.emit("exit",s);});}catch{}}write(e){this.shell?.write(e);}resize(e,o){try{this.shell?.resize(e,o);}catch{}}get cwd(){return this._cwd}isAlive(){return this._alive}kill(){try{this.shell?.kill();}catch{}this.shell=null,this._alive=false;}};var pn=new Set([".jpg",".jpeg",".png",".gif",".webp",".bmp",".svg"]),fn=new Set(["node_modules",".git","dist","__pycache__",".next","build","target"]);async function yt(r,e){let o=resolve(e,r);if(!existsSync(o))return null;let t=basename(o),n=extname(o).toLowerCase();if(pn.has(n)){let l=await readFile(o),a=n===".png"?"image/png":n===".gif"?"image/gif":n===".webp"?"image/webp":"image/jpeg";return {path:o,name:t,type:"image",data:l.toString("base64"),mimeType:a}}let s=await readFile(o,"utf-8").catch(()=>null);return s===null?null:{path:o,name:t,type:"file",data:s}}async function gn(r,e=2){let o=[];async function t(n,s,l){if(l>e||o.length>300)return;let a;try{a=await readdir(n,{withFileTypes:!0});}catch{return}for(let c of a){if(fn.has(c.name))continue;let u=s?`${s}/${c.name}`:c.name;c.isDirectory()?(o.push(u+"/"),await t(join(n,c.name),u,l+1)):o.push(u);}}return await t(r,"",0),o}var hn=0,xn=()=>String(++hn);function yn(r){let e=[],o=[],t=()=>{o.length>0&&(e.push({type:"agent",messages:o}),o=[]);};for(let n of r)n.type==="text"&&n.content.startsWith("> ")?(t(),e.push({type:"user",content:n.content.slice(2),timestamp:n.timestamp})):o.push(n);return t(),e}function Wt(r,e){return r.split(`
175
+ `).reduce((o,t)=>o+Math.max(1,Math.ceil((t.length||1)/Math.max(1,e))),0)}function Tn(r,e){if(r.type==="user")return 4;let o=0;for(let t of r.messages)if(t.type==="error")o+=Wt(t.content,e);else if(t.type==="command")o+=t.content.split(`
176
+ `).length+(t.commandTitle?1:0)+2;else if(t.type==="text")o+=Wt(t.content,e);else if(t.type==="done"&&t.content)o+=Wt(t.content.replace(/^DONE:\s*/i,"").trim(),e);else if(t.type==="tool_result"&&t.toolCall?.tool==="edit_file"&&t.toolResult?.meta){let n=t.toolResult.meta;o+=(n.diffContextBefore?.length??0)+(n.diffOld?.length??0)+(n.diffNew?.length??0)+(n.diffContextAfter?.length??0)+4;}else o+=1;return Math.max(2,o+2)}function bn(r,e,o,t){let n=[],s=0,l=Math.max(0,r.length-t),a=r.length-l;for(let c=l-1;c>=0;c--){let u=Tn(r[c],o);if(s+u>e)return n.length===0?(n.unshift(r[c]),{visible:n,hiddenAbove:c,hiddenBelow:a}):{visible:n,hiddenAbove:c+1,hiddenBelow:a};n.unshift(r[c]),s+=u;}return {visible:n,hiddenAbove:0,hiddenBelow:a}}function ko(r){return new Date(r).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}var Sn=({content:r,timestamp:e})=>i.createElement(Box,{flexDirection:"column",marginBottom:1,marginX:1,borderStyle:"single",borderColor:"#1D4ED8"},i.createElement(Box,{paddingX:1},i.createElement(Text,{color:"#3B82F6",bold:true},"# "),i.createElement(Text,{color:"#E5E7EB",bold:true},r)),i.createElement(Box,{paddingX:1},i.createElement(Text,{color:"#374151"},ko(e)))),vn=({msg:r})=>{switch(r.type){case "text":return i.createElement(Et,{content:r.content});case "command":{let e=r.content.split(`
177
+ `);return i.createElement(Box,{flexDirection:"column",marginBottom:1,paddingLeft:2},r.commandTitle&&i.createElement(Box,{marginBottom:0},i.createElement(Text,{color:"#6B7280"},"\u250C\u2500 "),i.createElement(Text,{color:"#9CA3AF",bold:true},r.commandTitle)),i.createElement(Box,{flexDirection:"column",borderStyle:"single",borderColor:"#374151",paddingX:1},e.map((o,t)=>{if(o.startsWith(" /")||o.startsWith(" $")||o.startsWith(" !")){let s=o.search(/\s{2,}/),l=s>0?o.slice(0,s):o,a=s>0?o.slice(s).trim():"";return i.createElement(Box,{key:t},i.createElement(Text,{color:"#3B82F6"},l),a?i.createElement(Text,{color:"#6B7280"}," ",a):null)}if(o.startsWith("**")&&o.endsWith("**"))return i.createElement(Text,{key:t,color:"#9CA3AF",bold:true},o.replace(/\*\*/g,""));if(o==="")return i.createElement(Text,{key:t}," ");if(/^\s{2}\S.*\s:\s/.test(o)){let s=o.indexOf(" : "),l=o.slice(0,s),a=o.slice(s+3);return i.createElement(Box,{key:t},i.createElement(Text,{color:"#6B7280"},l," "),i.createElement(Text,{color:"#374151"},": "),i.createElement(Text,{color:"#E5E7EB"},a))}return i.createElement(Text,{key:t,color:"#9CA3AF"},o)})))}case "tool_call":{if(!r.toolCall)return null;let e=r.toolCall.arguments,o=(()=>{switch(r.toolCall.tool){case "run_shell":return `$ ${String(e.command||"").slice(0,60)}`;case "read_file":return `Read ${e.path}`;case "write_file":return `Write ${e.path}`;case "append_file":return `Append ${e.path}`;case "edit_file":return null;case "delete_file":return `Delete ${e.path}`;case "move_file":return `Move ${e.from} \u2192 ${e.to}`;case "copy_file":return `Copy ${e.from} \u2192 ${e.to}`;case "create_dir":return `mkdir ${e.path}`;case "list_files":return `ls ${e.path||"."}`;case "find_files":return `find ${e.pattern}`;case "search_files":return `grep "${e.pattern}"`;case "git_status":return "git status";case "git_diff":return "git diff";case "git_log":return "git log";case "git_commit":return `git commit "${String(e.message||"").slice(0,40)}"`;case "web_fetch":return `fetch ${String(e.url||"").slice(0,55)}`;case "http_request":return `${e.method||"GET"} ${String(e.url||"").slice(0,50)}`;case "lsp_check":return `lsp check ${String(e.path||".")}`;default:return r.toolCall.tool}})();return o?i.createElement(Box,{paddingLeft:1},i.createElement(Text,{color:"#4B5563"}," "),i.createElement(Text,{color:"#6B7280"},o)):null}case "tool_result":{if(!r.toolCall||r.toolCall.tool==="edit_file")return null;if(!r.toolResult?.success)return i.createElement(Box,{paddingLeft:1},i.createElement(Text,{color:"#EF4444"}," \u2717 ",(r.toolResult?.error||"").slice(0,80)));let e=(r.toolResult.output||"").split(`
178
+ `).filter(Boolean),o=e.length>1?`${e.length} lines`:(e[0]||"").slice(0,50);return i.createElement(Box,{paddingLeft:1},i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#4B5563"},o))}case "error":return i.createElement(Text,{color:"#EF4444",wrap:"wrap"}," \u2717 ",r.content);case "done":{let e=r.content.replace(/```json[\s\S]*?```/gi,"").replace(/\{[\s\S]*?"tool"\s*:[\s\S]*?\}/g,"").replace(/\s*DONE:\s*<[^>]*>/gi,"").replace(/\s*DONE:\s*.*/gi,"").trim();return e?i.createElement(Et,{content:e}):null}default:return null}},wn=({messages:r,model:e})=>{let o=[],t=[],n=()=>{t.length&&(o.push({type:"content",msgs:t}),t=[]);};for(let c of r)c.type==="tool_result"&&c.toolCall?.tool==="edit_file"&&c.toolResult?.meta?.diffPath?(n(),o.push({type:"diff",msg:c})):t.push(c);n();let l=r.find(c=>c.type==="done")?.timestamp??r[r.length-1]?.timestamp,a=r.some(c=>c.type==="text"&&c.content&&!c.content.startsWith("> ")||c.type==="error"||c.type==="done"&&c.content||c.type==="tool_result"&&c.toolCall?.tool==="edit_file");return i.createElement(Box,{flexDirection:"column",marginBottom:1},o.map((c,u)=>{if(c.type==="diff"){let p=c.msg.toolResult.meta;return i.createElement(Pt,{key:u,filePath:p.diffPath,oldLines:p.diffOld,newLines:p.diffNew,startLine:p.diffStartLine,contextBefore:p.diffContextBefore??[],contextAfter:p.diffContextAfter??[]})}let d=u===o.length-1;return i.createElement(Box,{key:u},i.createElement(Text,{color:"#3B82F6"}," \u2502 "),i.createElement(Box,{flexDirection:"column",flexGrow:1},c.msgs.map(p=>i.createElement(vn,{key:p.id,msg:p})),d&&a&&l&&i.createElement(Box,{marginTop:0},i.createElement(Text,{color:"#374151"},e),i.createElement(Text,{color:"#1D4ED8"}," "),i.createElement(Text,{color:"#374151"},"(",ko(l),")"))))}))};function Cn(r){let e=r.indexOf("<think>");if(e===-1)return {thinking:"",response:r,stillThinking:false};let o=r.indexOf("</think>",e);return o===-1?{thinking:r.slice(e+7),response:"",stillThinking:true}:{thinking:r.slice(e+7,o),response:r.slice(o+8).trimStart(),stillThinking:false}}function Bn(r,e){if(r.length<2)return "";let o=e.find(s=>s!==r&&s.toLowerCase().startsWith(r.toLowerCase()));if(o)return o.slice(r.length);let t=ze.find(s=>s.cmd.startsWith(r)&&s.cmd!==r);if(t)return t.cmd.slice(r.length);let n=st.find(s=>s.startsWith(r)&&s!==r);return n?n.slice(r.length):""}var Po=({initialCommand:r,cwd:e})=>{let{exit:o}=useApp(),t=_e.getInstance(),[n,s]=useState([]),[l,a]=useState("idle"),[c,u]=useState(""),[d,p]=useState(0),[T,h]=useState(()=>t.getHistory()),[y,Q]=useState(null),[D,x]=useState(""),[E,B]=useState(-1),[ce,se]=useState(0),[G,oe]=useState(0),[xe,Ee]=useState(false),[ue,we]=useState(false),[Tt,Me]=useState([]),[bt,Ce]=useState(false),[Oe,Be]=useState(false),[et,Do]=useState([]),[Ge,tt]=useState([]),[ie,Fo]=useState("build"),[Oo,ot]=useState([]),[qt,St]=useState([]),de=useRef(null),vt=useRef(null),wt=useRef(0),[Yt,Io]=useState(process.stdout.rows||24),[zt,No]=useState(process.stdout.columns||80),Ct=useRef({agentStatus:l,isRunning:false,attachments:Ge,mode:ie,pickerIdx:ce,messages:n,convHistory:qt});Ct.current={agentStatus:l,isRunning:l==="thinking"||l==="running",attachments:Ge,mode:ie,pickerIdx:ce,messages:n,convHistory:qt};let qe=n.length===0&&l==="idle"&&!y,jo=[...ze,...Oo],Ye=D.startsWith("/")&&l==="idle"&&!qe&&!xe&&!ue?jo.filter(S=>S.cmd.toLowerCase().startsWith(D.toLowerCase())).slice(0,7):[],rt=Ye.length>0,Ie=!qe&&!rt&&!xe&&!ue&&l==="idle"?Bn(D,T):"",Ne=l==="thinking"||l==="running";useEffect(()=>{let S=()=>{Io(process.stdout.rows||24),No(process.stdout.columns||80);};return process.stdout.on("resize",S),()=>{process.stdout.off("resize",S);}},[]),useEffect(()=>{try{vt.current=new gt(e,t.get().shell);}catch{}return ()=>{vt.current?.kill();}},[]),useEffect(()=>{if(r){let S=setTimeout(()=>Bt(r),150);return ()=>clearTimeout(S)}},[]),useEffect(()=>{let S=he.getInstance();S.load(),ot(S.getCommands().map(A=>({cmd:A.cmd,description:A.description})));},[]);let g=useCallback(S=>{s(A=>[...A,{...S,id:xn(),timestamp:Date.now()}]),oe(0);},[]),Uo=useCallback(S=>{let A=S.trim().replace(/^["']|["']$/g,""),L=/^[A-Za-z]:[\\\/].{2,}/.test(A),Ae=/^\/[^\s\/]+\/[^\s]*/.test(A);if(L||Ae){x(""),B(-1),se(0),yt(A,e).then($e=>{$e?tt(re=>[...re,$e]):x(S);});return}x(S),B(-1),se(0);},[e]),Bt=useCallback(async S=>{let{agentStatus:A,isRunning:L,attachments:Ae,mode:$e,messages:re}=Ct.current,v=S.trim();if(v){if(x(""),B(-1),se(0),v.startsWith("/config")||v.toLowerCase()==="/config"){let _=v.slice(7).trim(),[C,...F]=_.split(/\s+/),f=F.join(" ").trim();if(C)switch(C.toLowerCase()){case "model":if(!f){g({type:"error",content:"Usage: /config model <model-name>"});break}t.setLLM({model:f}),g({type:"done",content:`Model \u2192 ${f}`});break;case "provider":{if(!f||!["ollama","lmstudio"].includes(f.toLowerCase())){g({type:"error",content:`Available providers: ollama lmstudio
179
179
  /config provider ollama
180
- /config provider lmstudio`});break}let v=f==="lmstudio"?{provider:"lmstudio",baseURL:"http://localhost:1234/v1",model:t.get().llm.model}:{provider:"ollama",baseURL:"http://localhost:11434",model:t.get().llm.model};t.setLLM(v),g({type:"done",content:`Provider \u2192 ${f}
181
- URL \u2192 ${v.baseURL}`});break}case "url":case "baseurl":case "base-url":if(!f){g({type:"error",content:"Usage: /config url <url>"});break}t.setLLM({baseURL:f}),g({type:"done",content:`Base URL \u2192 ${f}`});break;case "temperature":case "temp":if(!f){g({type:"error",content:"Usage: /config temperature <0.0\u20131.0>"});break}t.setLLM({temperature:parseFloat(f)}),g({type:"done",content:`Temperature \u2192 ${f}`});break;default:g({type:"error",content:"Unknown subcommand. Type /config for an overview."});}else {let v=t.get();g({type:"command",commandTitle:"config",content:[` config path : ${t.getConfigPath()}`,"",` provider : ${v.llm.provider}`,` model : ${v.llm.model}`,` url : ${v.llm.baseURL||"(default)"}`,` temperature : ${v.llm.temperature??.1}`,"","**Commands**"," /config provider ollama Use Ollama (localhost:11434)"," /config provider lmstudio Use LM Studio (localhost:1234)"," /config model <name> Switch model"," /config url <url> Override base URL"," /config temperature <val> Set temperature (0.0\u20131.0)"].join(`
182
- `)});}t.addHistory(C),x(t.getHistory());return}if(C==="/exit"||C==="exit"||C==="quit"){o();return}if(C==="/clear"||C==="clear"){s([]);return}if(C==="/lsp"||C.startsWith("/lsp ")){let _=C.slice(4).trim()||".";c("thinking"),u("");let{diagnostics:L,tool:D,error:f}=await dt(e,_==="."?void 0:_);if(c("idle"),u(""),f&&L.length===0)g({type:"error",content:f});else if(L.length===0)g({type:"command",commandTitle:`lsp (${D})`,content:" \u2713 No issues found"});else {let v=L.filter(F=>F.severity==="error").length,k=L.filter(F=>F.severity==="warning").length,se=[` ${D}: ${v} error${v!==1?"s":""}, ${k} warning${k!==1?"s":""}`,"",...L.slice(0,40).map(F=>` ${F.file}:${F.line}:${F.col} ${F.severity} ${F.message}${F.code?` [${F.code}]`:""}`),...L.length>40?[` \u2026 and ${L.length-40} more`]:[]];g({type:"command",commandTitle:`lsp (${D})`,content:se.join(`
183
- `)});}t.addHistory(C),x(t.getHistory());return}if(C==="/attach"){Me(true),(async()=>$o(await cn(e)))();return}if(C==="/compact"){if(ee.length===0){g({type:"error",content:"Nothing to compact."});return}c("thinking"),u("");let _=ee.map(f=>f.type==="text"&&f.content.startsWith("> ")?`User: ${f.content.slice(2)}`:f.type==="done"?`Assistant: ${f.content.replace(/^DONE:\s*/i,"").trim()}`:f.type==="tool_call"&&f.toolCall?` [${f.toolCall.tool}]`:null).filter(Boolean).join(`
184
- `),L=[{role:"system",content:"You are a helpful assistant. Summarize the following conversation concisely in bullet points, preserving key decisions and results."},{role:"user",content:_}],D="";try{await oe.stream(L,t.get().llm,f=>{D+=f,u(D);});}catch{}u(""),c("idle"),s([]),g({type:"done",content:`[Compacted]
185
- ${D}`});return}if(C.startsWith("/session")){let _=C.slice(8).trim(),[L,...D]=_.split(/\s+/),f=D.join(" ").trim()||L;if(!L||L==="list"){let v=t.listSessions();g({type:"command",commandTitle:"sessions",content:v.length?v.map(k=>` \u2022 ${k}`).join(`
186
- `):" No sessions saved yet. Use /session save <name>"});}else if(L==="save"){if(!f||f==="save"){g({type:"error",content:"Usage: /session save <name>"});return}t.saveSession(f,ee),g({type:"done",content:`Session "${f}" saved (${ee.length} messages)`});}else if(L==="load"){if(!f||f==="load"){g({type:"error",content:"Usage: /session load <name>"});return}let v=t.loadSession(f);if(!v){g({type:"error",content:`Session "${f}" not found.`});return}s(v),g({type:"done",content:`Session "${f}" loaded (${v.length} messages)`});}else if(L==="delete"){if(!f||f==="delete"){g({type:"error",content:"Usage: /session delete <name>"});return}t.deleteSession(f),g({type:"done",content:`Session "${f}" deleted`});}else g({type:"error",content:"Usage: /session [list|save <name>|load <name>|delete <name>]"});t.addHistory(C),x(t.getHistory());return}if(C==="/connect"){$(""),xe(true);return}if(C==="/model"){$(""),Oe(true),qe(true),rt([]),(async()=>{let _=t.get(),D=_.llm.provider==="ollama"?await oe.getOllamaProvider().listModels(_.llm.baseURL):await oe.getLMStudioProvider().listModels(_.llm.baseURL);rt(D),qe(false);})();return}if(C==="/plugin"||C.startsWith("/plugin ")){let _=C.slice(7).trim(),[L,...D]=_.split(/\s+/),f=D.join(" ").trim(),v=he.getInstance();if(!L||L==="list"){let k=v.getAll(),se=v.getErrors(),F=[];if(k.length===0&&se.length===0)F.push(" No plugins installed."),F.push(` Plugin dir: ${v.getPluginDir()}`),F.push(""),F.push(" /plugin install <path> Install a plugin");else {for(let V of k){let be=(V.commands??[]).map(Ue=>Ue.cmd.trim()).join(", "),Q=(V.tools??[]).map(Ue=>Ue.name).join(", ");F.push(` \u2022 ${V.name} v${V.version}${V.description?" "+V.description:""}`),be&&F.push(` commands : ${be}`),Q&&F.push(` tools : ${Q}`);}for(let V of se)F.push(` \u2717 ${V.file}: ${V.error}`);}g({type:"command",commandTitle:"plugins",content:F.join(`
187
- `)});}else if(L==="install"){if(!f){g({type:"error",content:"Usage: /plugin install <path>"}),t.addHistory(C),x(t.getHistory());return}c("thinking");let k=await v.install(f);c("idle"),k.ok?(st(v.getCommands().map(se=>({cmd:se.cmd,description:se.description}))),g({type:"done",content:`Plugin "${k.name}" installed successfully`})):g({type:"error",content:`Install failed: ${k.error}`});}else if(L==="remove"){if(!f){g({type:"error",content:"Usage: /plugin remove <name>"}),t.addHistory(C),x(t.getHistory());return}c("thinking");let k=await v.remove(f);c("idle"),k.ok?(st(v.getCommands().map(se=>({cmd:se.cmd,description:se.description}))),g({type:"done",content:`Plugin "${f}" removed`})):g({type:"error",content:k.error||"Remove failed"});}else L==="reload"?(v.reload(),st(v.getCommands().map(k=>({cmd:k.cmd,description:k.description}))),g({type:"done",content:`Plugins reloaded (${v.getAll().length} loaded)`})):g({type:"error",content:"Usage: /plugin [list | install <path> | remove <name> | reload]"});t.addHistory(C),x(t.getHistory());return}if(C.startsWith("/")){let _=he.getInstance().getCommands(),L=C.trim(),D=_.find(f=>{let v=f.cmd.trimEnd();return L===v||L.startsWith(v+" ")});if(D){let f=D.cmd.trimEnd(),v=L.slice(f.length).trim();c("thinking");try{let k=await D.handler(v,{cwd:e});c("idle"),k.type==="error"?g({type:"error",content:k.content}):k.type==="command"?g({type:"command",commandTitle:k.title,content:k.content}):g({type:"done",content:k.content});}catch(k){c("idle"),g({type:"error",content:`Plugin error: ${String(k)}`});}t.addHistory(C),x(t.getHistory());return}}switch(C.trim().toLowerCase()){case "exit":case "quit":o();return;case "clear":s([]);return;case "help":case "/help":g({type:"command",commandTitle:"help",content:["**Attachments**"," /attach Attach file or image (@-picker)"," @path/to/file Include file in message (type in input)","","**Session**"," /session List saved sessions"," /session save <name> Save conversation"," /session load <name> Load conversation"," /session delete <name> Delete session"," /compact Summarize & compress conversation","","**Connection**"," /connect Connect to server (popup)"," /model Select model (popup)","","**Configuration**"," /config Show current configuration"," /config provider ollama Use Ollama (localhost:11434)"," /config provider lmstudio Use LM Studio (localhost:1234)"," /config model <name> Switch model"," /config url <url> Set base URL"," /config temperature <val> Set temperature (0.0\u20131.0)","","**System**"," /lsp Run diagnostics (tsc/cargo/go vet/pyflakes/eslint)"," /models List available models"," /doctor Check connection & status"," /clear Clear screen"," /exit Quit","","**Keyboard shortcuts**"," ctrl+c Abort running agent / quit"," ctrl+l Clear chat history"," ctrl+k Clear input line"," \u2191 \u2193 Navigate history"," tab Autocomplete / toggle BUILD\u2194PLAN mode"," PageUp / PageDown Scroll chat","","**Shell**"," $ <cmd> or ! <cmd> e.g.: $ npm test","","**Plugins**"," /plugin List installed plugins"," /plugin install <path> Install plugin from directory or .js file"," /plugin remove <name> Uninstall a plugin"," /plugin reload Reload all plugins"].join(`
188
- `)});break;case "doctor":{let _=t.get(),L=_.llm.provider==="ollama",D=L?await oe.getOllamaProvider().checkHealth(_.llm.baseURL):await oe.getLMStudioProvider().checkHealth(_.llm.baseURL),f=L?"Ollama":"LM Studio",v=L?"ollama serve":"LM Studio \u2192 start Local Server";g({type:"command",commandTitle:"doctor",content:[` Node.js : \u2713 ${process.version}`,` Platform : \u2713 ${process.platform}`,` ${f.padEnd(9)}: ${D?"\u2713 Reachable":`\u2717 Not reachable \u2014 ${v}`}`,` Provider : ${_.llm.provider}`,` Model : ${_.llm.model}`,` URL : ${_.llm.baseURL||"(default)"}`,` Config : ${t.getConfigPath()}`].join(`
189
- `)});break}case "models":{let _=t.get(),L=_.llm.provider==="ollama",D=L?await oe.getOllamaProvider().listModels(_.llm.baseURL):await oe.getLMStudioProvider().listModels(_.llm.baseURL);g({type:"command",commandTitle:"models",content:D.length?D.map(v=>` \u2022 ${v}`).join(`
190
- `):L?" No Ollama models found. Pull one with: ollama pull deepseek-coder":" No LM Studio models found. Open LM Studio and load a model."});break}default:{if(C.startsWith("$")||C.startsWith("!")){Tt.current?.write(C.slice(1).trim()+`
191
- `);break}if(B&&de.current){de.current.inject(C),g({type:"text",content:`> [btw] ${C}`});break}let _=C.trim().replace(/^["']|["']$/g,"");if(/^[A-Za-z]:[\\\/].{2,}/.test(_)||/^\/[^\s]{2,}/.test(_)){let N=await yt(_,e);if(N){nt(Se=>[...Se,N]);return}}let D=/@([^\s]+)/g,f=[],v=C,k;for(;(k=D.exec(C))!==null;)f.push(yt(k[1],e)),v=v.replace(k[0],`[${k[1]}]`);let F=(await Promise.all(f)).filter(N=>N!==null),V=[...z,...F];c("thinking"),u(""),p(0);let be=V.length?` [${V.map(N=>N.name).join(", ")}]`:"";g({type:"text",content:`> ${v}${be}`}),nt([]);let Q=new ht;de.current=Q;let Ue=0;Q.on("thinking",()=>{c("thinking"),u("");}),Q.on("token",N=>{c("running"),u(Se=>Se+N),Ue+=N.length,p(Ue);}),Q.on("tool_call",({toolCall:N})=>{u(""),g({type:"tool_call",content:N.tool,toolCall:N});}),Q.on("tool_result",({toolCall:N,result:Se})=>{g({type:"tool_result",content:"",toolCall:N,toolResult:Se});}),Q.on("confirm_required",({toolCall:N,reason:Se,diffPreview:Fo})=>{G({toolCall:N,reason:Se,diffPreview:Fo});}),Q.on("injection",({message:N})=>{}),Q.on("error",N=>{c("error"),g({type:"error",content:N});}),Q.on("done",({response:N,aborted:Se})=>{u(""),c("idle"),G(null),de.current=null,Se?g({type:"error",content:"Stopped."}):N&&g({type:"done",content:N});}),Q.run(v,e,V,R).catch(N=>{c("error"),g({type:"error",content:String(N)}),de.current=null;});break}}t.addHistory(C),x(t.getHistory());}},[g,e,o]);useInput((h,A)=>{if(h.startsWith("\x1B[<")){let B=h.match(/\x1b\[<(\d+)/);if(B){let z=parseInt(B[1]);if(z===64){ne(R=>R+3);return}if(z===65){ne(R=>Math.max(0,R-3));return}}return}if(Be||ye||Ee){A.ctrl&&h==="c"&&(xe(false),Oe(false),Me(false));return}if(!Ye){if(A.pageUp){ne(B=>B+2);return}if(A.pageDown){ne(B=>Math.max(0,B-2));return}}if(!Ye&&l==="idle"){if(it){if(A.upArrow){I(B=>Math.max(0,B-1));return}if(A.downArrow){I(B=>Math.min(Je.length-1,B+1));return}if(A.tab){let B=Je[Ae];B&&($(B.cmd.endsWith(" ")?B.cmd:B.cmd.trim()),I(0));return}if(A.escape){$(""),I(0),J(-1);return}return}if(A.tab&&!Ne){Po(B=>B==="build"?"plan":"build");return}if(A.tab&&Ne){$(T+Ne);return}if(A.upArrow){if(T===""){ne(z=>z+3);return}let B=Math.min(b+1,y.length-1);J(B),y[B]&&$(y[B]);return}if(A.downArrow){if(T===""&&le>0){ne(z=>Math.max(0,z-3));return}let B=Math.max(b-1,-1);J(B),$(B===-1?"":y[B]||"");return}if(A.escape){$(""),J(-1);return}}if(A.ctrl&&h==="c"){de.current?(de.current.abort(),de.current=null,c("idle"),u(""),g({type:"error",content:"Aborted."})):o();return}if(A.ctrl&&h==="l"){s([]);return}if(A.ctrl&&h==="k"){$(""),J(-1);return}S&&(h==="y"||h==="Y"?(de.current?.confirm(true),G(null)):(h==="n"||h==="N"||A.escape)&&(de.current?.confirm(false),G(null)));});let Te=t.get();Te.llm.provider==="lmstudio"?"LM Studio":"Ollama";return i.createElement(Box,{flexDirection:"column",height:jt},Ye?i.createElement(i.Fragment,null,i.createElement(Box,{flexGrow:1,alignItems:"center",justifyContent:"center"},i.createElement(Vt,{config:Te,history:y,onSubmit:bt})),i.createElement(wt,{config:Te,cwd:e,agentStatus:l,tokenCount:d,mode:ae})):i.createElement(i.Fragment,null,i.createElement(Box,{flexGrow:1}),(()=>{let h=it?Je.length+3:0,A=a||je?2:0,B=ze.length>0?1:0,z=S?.diffPreview?S.diffPreview.contextBefore.length+S.diffPreview.oldLines.length+S.diffPreview.newLines.length+S.diffPreview.contextAfter.length+4:0,R=S?1+z:0,L=4+B+1+h+A+R+1,D=Math.max(2,jt-L),f=Math.max(20,Ut-8),v=mn(n),k=Math.min(le,Math.max(0,v.length-1)),{visible:se,hiddenAbove:F,hiddenBelow:V}=fn(v,D,f,k);return i.createElement(i.Fragment,null,F>0?i.createElement(Box,{paddingX:2},i.createElement(Text,{color:"#374151"},"\u2191 PageUp "),i.createElement(Text,{color:"#4B5563"},F," older messages")):i.createElement(Text,null," "),se.map((be,Q)=>be.type==="user"?i.createElement(gn,{key:Q,content:be.content,timestamp:be.timestamp}):i.createElement(xn,{key:Q,messages:be.messages,model:Te.llm.model})),V>0&&i.createElement(Box,{paddingX:2},i.createElement(Text,{color:"#374151"},"\u2193 PageDown "),i.createElement(Text,{color:"#4B5563"},V," newer messages")))})(),(a||je&&!a)&&(()=>{let{thinking:h,response:A,stillThinking:B}=yn(a),z=A.replace(/```json[\s\S]*?```/g,"").replace(/\{[\s\S]*?"tool"\s*:/g,""),R=h.trimEnd().split(`
192
- `).filter(ee=>ee.trim()).slice(-3);return i.createElement(Box,{marginBottom:0,flexDirection:"column"},h&&i.createElement(Box,{flexDirection:"column"},i.createElement(Box,null,i.createElement(Text,{color:"#3B82F6"}," \u2502 "),i.createElement(Text,{color:"#6366F1",bold:true},"Reasoning"),B&&i.createElement(at,{label:""})),R.map((ee,C)=>i.createElement(Box,{key:C},i.createElement(Text,{color:"#3B82F6"}," \u2502 "),i.createElement(Text,{color:"#4B5563",italic:true},ee.slice(0,Ut-10))))),i.createElement(Box,null,i.createElement(Text,{color:"#3B82F6"}," \u2502 "),i.createElement(Box,{flexGrow:1},a?z?i.createElement(Box,null,i.createElement(Text,{color:"#D1D5DB",wrap:"wrap"},z),i.createElement(Text,{color:"#3B82F6"},"\u2588")):B?i.createElement(Box,null,i.createElement(Text,{color:"#6366F1"},"Thinking "),i.createElement(at,{label:""})):null:i.createElement(Box,null,i.createElement(Text,{color:"#6366F1"},"Thinking "),i.createElement(at,{label:""})))))})(),S&&i.createElement(Box,{flexDirection:"column",marginX:1,marginBottom:1,borderStyle:"single",borderColor:"#F59E0B"},S.diffPreview&&i.createElement(Ct,{filePath:S.diffPreview.filePath,oldLines:S.diffPreview.oldLines,newLines:S.diffPreview.newLines,startLine:S.diffPreview.startLine,contextBefore:S.diffPreview.contextBefore,contextAfter:S.diffPreview.contextAfter}),i.createElement(Box,{paddingX:2,paddingY:0},i.createElement(Text,{color:"#F59E0B"},"Allow "),i.createElement(Text,{color:"#D1D5DB"},S.reason),i.createElement(Text,{color:"#4B5563"}," "),i.createElement(Text,{color:"#22C55E"},"[y] yes"),i.createElement(Text,{color:"#4B5563"}," / "),i.createElement(Text,{color:"#EF4444"},"[n] no"))),Be&&i.createElement(to,{onConnect:(h,A)=>{t.setLLM({provider:h,baseURL:A}),xe(false),g({type:"done",content:`Connected \xB7 ${h} ${A}`});},onCancel:()=>xe(false)}),ye&&i.createElement(ro,{models:Ie,loading:_e,currentModel:Te.llm.model,onSelect:h=>{t.setLLM({model:h}),Oe(false),g({type:"done",content:`Model \u2192 ${h}`});},onCancel:()=>Oe(false)}),Ee&&i.createElement(so,{files:Lo,onSelect:async h=>{Me(false);let A=await yt(h,e);A&&nt(B=>[...B,A]);},onCancel:()=>Me(false)}),it&&i.createElement(Box,{flexDirection:"column",borderStyle:"round",borderColor:"#2D4A7A",marginX:1},Je.map((h,A)=>{let B=A===Ae;return i.createElement(Box,{key:h.cmd,paddingX:1},i.createElement(Text,{color:B?"#3B82F6":"#374151"},B?"\u25B6 ":" "),i.createElement(Text,{color:B?"#60A5FA":"#6B7280",bold:true},h.cmd.trimEnd()),i.createElement(Text,{color:B?"#4B5563":"#374151"}," ",h.description))})),i.createElement(Box,{flexDirection:"column",borderStyle:"single",borderColor:ae==="plan"?"#14532D":"#1E3A5F",marginX:1},ze.length>0&&i.createElement(Box,{paddingX:1,flexDirection:"row"},ze.map((h,A)=>i.createElement(Box,{key:A,marginRight:1},i.createElement(Text,{color:h.type==="image"?"#A78BFA":"#60A5FA"},"@",h.name)))),i.createElement(Box,{paddingX:1},i.createElement(Text,{color:je?"#F59E0B":ae==="plan"?"#22C55E":"#3B82F6",bold:true},"> "),i.createElement(Lt,{value:T,onChange:Do,onSubmit:bt,placeholder:je?"inject message to agent...":ae==="plan"?"describe what to plan...":"/ for commands \xB7 @ to attach files",focus:!S&&!Be&&!ye&&!Ee}),Ne&&!je&&i.createElement(Text,{color:"#1F2937"},Ne)),i.createElement(Box,{paddingX:1,justifyContent:"space-between"},i.createElement(Box,null,je?i.createElement(i.Fragment,null,i.createElement(Text,{color:"#F59E0B"},"ctrl+c "),i.createElement(Text,{color:"#6B7280"},"abort "),i.createElement(Text,{color:"#4B5563"},"\u21B5 "),i.createElement(Text,{color:"#6B7280"},"inject message")):i.createElement(i.Fragment,null,i.createElement(Text,{color:"#4B5563"},"\u21B5 "),i.createElement(Text,{color:"#6B7280"},"send "),i.createElement(Text,{color:"#4B5563"},"tab "),i.createElement(Text,{color:"#6B7280"},Ne?"complete":"switch mode"," "),i.createElement(Text,{color:"#4B5563"},"@ "),i.createElement(Text,{color:"#6B7280"},"attach"))),i.createElement(Box,null,i.createElement(Text,{backgroundColor:ae==="plan"?"#166534":"#1D4ED8",color:ae==="plan"?"#86EFAC":"#BFDBFE"}," ",ae==="plan"?"PLAN":"BUILD"," "),i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#9CA3AF"},Te.llm.model.length>24?Te.llm.model.slice(0,24)+"\u2026":Te.llm.model)))),i.createElement(wt,{config:Te,cwd:e,agentStatus:l,tokenCount:d,mode:ae})))};var tt=process.argv.slice(2),vn=process.cwd();(tt.includes("--help")||tt.includes("-h"))&&(process.stdout.write(`
193
- ${Z.bold.blue("\u26A1 LocalCode")} ${Z.gray("v0.1.0")} ${Z.gray("\u2014 Futuristic AI Developer Terminal")}
194
-
195
- ${Z.bold("Usage:")}
196
- ${Z.blue("localcode")} Start interactive TUI
197
- ${Z.blue("localcode")} <task> Run AI task directly
198
- ${Z.blue("localcode")} --provider <p> Override LLM provider
199
- ${Z.blue("localcode")} --model <m> Override model
200
- ${Z.blue("localcode")} --help Show this help
201
-
202
- ${Z.bold("Examples:")}
203
- ${Z.gray("localcode")}
204
- ${Z.gray("localcode fix auth bug")}
205
- ${Z.gray("localcode --provider ollama --model llama3 fix typescript errors")}
206
- ${Z.gray("localcode --provider openai --model gpt-4o create REST API")}
207
-
208
- ${Z.bold("Providers:")} ollama \xB7 openai \xB7 claude \xB7 openrouter \xB7 lmstudio
209
-
210
- ${Z.bold("Config:")} ~/.localcode/config.json
211
- `),process.exit(0));(tt.includes("--version")||tt.includes("-v"))&&(process.stdout.write(`0.1.0
212
- `),process.exit(0));var et=[...tt];function Ao(r){let e=et.indexOf(r);if(e===-1)return;let o=et[e+1];return et.splice(e,2),o}var It=Ao("--provider"),Nt=Ao("--model");(It||Nt)&&ke.getInstance().setLLM({...It&&{provider:It},...Nt&&{model:Nt}});var wn=et.length>0?et.join(" "):void 0,Bo=process.stdout.isTTY;function Cn(){Bo&&process.stdout.write("\x1B[?1049h\x1B[2J\x1B[3J\x1B[H\x1B[?1000h\x1B[?1006h");}function ot(){Bo&&process.stdout.write("\x1B[?1006l\x1B[?1000l\x1B[?1049l");}process.on("exit",ot);process.on("SIGINT",()=>{ot(),process.exit(0);});process.on("SIGTERM",()=>{ot(),process.exit(0);});process.on("uncaughtException",()=>{ot(),process.exit(1);});Cn();var{waitUntilExit:An}=render(i.createElement(Co,{initialCommand:wn,cwd:vn}),{exitOnCtrlC:false,patchConsole:true});An().then(()=>{ot(),process.exit(0);});
180
+ /config provider lmstudio`});break}let b=f==="lmstudio"?{provider:"lmstudio",baseURL:"http://localhost:1234/v1",model:t.get().llm.model}:{provider:"ollama",baseURL:"http://localhost:11434",model:t.get().llm.model};t.setLLM(b),g({type:"done",content:`Provider \u2192 ${f}
181
+ URL \u2192 ${b.baseURL}`});break}case "url":case "baseurl":case "base-url":if(!f){g({type:"error",content:"Usage: /config url <url>"});break}t.setLLM({baseURL:f}),g({type:"done",content:`Base URL \u2192 ${f}`});break;case "temperature":case "temp":if(!f){g({type:"error",content:"Usage: /config temperature <0.0\u20131.0>"});break}t.setLLM({temperature:parseFloat(f)}),g({type:"done",content:`Temperature \u2192 ${f}`});break;default:g({type:"error",content:"Unknown subcommand. Type /config for an overview."});}else {let b=t.get();g({type:"command",commandTitle:"config",content:[` config path : ${t.getConfigPath()}`,"",` provider : ${b.llm.provider}`,` model : ${b.llm.model}`,` url : ${b.llm.baseURL||"(default)"}`,` temperature : ${b.llm.temperature??.1}`,"","**Commands**"," /config provider ollama Use Ollama (localhost:11434)"," /config provider lmstudio Use LM Studio (localhost:1234)"," /config model <name> Switch model"," /config url <url> Override base URL"," /config temperature <val> Set temperature (0.0\u20131.0)"].join(`
182
+ `)});}t.addHistory(v),h(t.getHistory());return}if(v==="/exit"||v==="exit"||v==="quit"){o();return}if(v==="/clear"||v==="clear"){s([]),St([]);return}if(v==="/lsp"||v.startsWith("/lsp ")){let _=v.slice(4).trim()||".";a("thinking"),u("");let{diagnostics:C,tool:F,error:f}=await ct(e,_==="."?void 0:_);if(a("idle"),u(""),f&&C.length===0)g({type:"error",content:f});else if(C.length===0)g({type:"command",commandTitle:`lsp (${F})`,content:" \u2713 No issues found"});else {let b=C.filter(O=>O.severity==="error").length,k=C.filter(O=>O.severity==="warning").length,z=[` ${F}: ${b} error${b!==1?"s":""}, ${k} warning${k!==1?"s":""}`,"",...C.slice(0,40).map(O=>` ${O.file}:${O.line}:${O.col} ${O.severity} ${O.message}${O.code?` [${O.code}]`:""}`),...C.length>40?[` \u2026 and ${C.length-40} more`]:[]];g({type:"command",commandTitle:`lsp (${F})`,content:z.join(`
183
+ `)});}t.addHistory(v),h(t.getHistory());return}if(v==="/attach"){Be(true),(async()=>Do(await gn(e)))();return}if(v==="/compact"){if(re.length===0){g({type:"error",content:"Nothing to compact."});return}a("thinking"),u("");let _=re.map(f=>f.type==="text"&&f.content.startsWith("> ")?`User: ${f.content.slice(2)}`:f.type==="done"?`Assistant: ${f.content.replace(/^DONE:\s*/i,"").trim()}`:f.type==="tool_call"&&f.toolCall?` [${f.toolCall.tool}]`:null).filter(Boolean).join(`
184
+ `),C=[{role:"system",content:"You are a helpful assistant. Summarize the following conversation concisely in bullet points, preserving key decisions and results."},{role:"user",content:_}],F="";try{await Z.stream(C,t.get().llm,f=>{F+=f,u(F);});}catch{}u(""),a("idle"),s([]),St([]),g({type:"done",content:`[Compacted]
185
+ ${F}`});return}if(v.startsWith("/session")){let _=v.slice(8).trim(),[C,...F]=_.split(/\s+/),f=F.join(" ").trim()||C;if(!C||C==="list"){let b=t.listSessions();g({type:"command",commandTitle:"sessions",content:b.length?b.map(k=>` \u2022 ${k}`).join(`
186
+ `):" No sessions saved yet. Use /session save <name>"});}else if(C==="save"){if(!f||f==="save"){g({type:"error",content:"Usage: /session save <name>"});return}t.saveSession(f,re),g({type:"done",content:`Session "${f}" saved (${re.length} messages)`});}else if(C==="load"){if(!f||f==="load"){g({type:"error",content:"Usage: /session load <name>"});return}let b=t.loadSession(f);if(!b){g({type:"error",content:`Session "${f}" not found.`});return}s(b),g({type:"done",content:`Session "${f}" loaded (${b.length} messages)`});}else if(C==="delete"){if(!f||f==="delete"){g({type:"error",content:"Usage: /session delete <name>"});return}t.deleteSession(f),g({type:"done",content:`Session "${f}" deleted`});}else g({type:"error",content:"Usage: /session [list|save <name>|load <name>|delete <name>]"});t.addHistory(v),h(t.getHistory());return}if(v==="/connect"){x(""),Ee(true);return}if(v==="/model"){x(""),we(true),Ce(true),Me([]),(async()=>{let _=t.get(),F=_.llm.provider==="ollama"?await Z.getOllamaProvider().listModels(_.llm.baseURL):await Z.getLMStudioProvider().listModels(_.llm.baseURL);Me(F),Ce(false);})();return}if(v==="/plugin"||v.startsWith("/plugin ")){let _=v.slice(7).trim(),[C,...F]=_.split(/\s+/),f=F.join(" ").trim(),b=he.getInstance();if(!C||C==="list"){let k=b.getAll(),z=b.getErrors(),O=[];if(k.length===0&&z.length===0)O.push(" No plugins installed."),O.push(` Plugin dir: ${b.getPluginDir()}`),O.push(""),O.push(" /plugin install <path> Install a plugin");else {for(let ee of k){let nt=(ee.commands??[]).map(je=>je.cmd.trim()).join(", "),te=(ee.tools??[]).map(je=>je.name).join(", ");O.push(` \u2022 ${ee.name} v${ee.version}${ee.description?" "+ee.description:""}`),nt&&O.push(` commands : ${nt}`),te&&O.push(` tools : ${te}`);}for(let ee of z)O.push(` \u2717 ${ee.file}: ${ee.error}`);}g({type:"command",commandTitle:"plugins",content:O.join(`
187
+ `)});}else if(C==="install"){if(!f){g({type:"error",content:"Usage: /plugin install <path>"}),t.addHistory(v),h(t.getHistory());return}a("thinking");let k=await b.install(f);a("idle"),k.ok?(ot(b.getCommands().map(z=>({cmd:z.cmd,description:z.description}))),g({type:"done",content:`Plugin "${k.name}" installed successfully`})):g({type:"error",content:`Install failed: ${k.error}`});}else if(C==="remove"){if(!f){g({type:"error",content:"Usage: /plugin remove <name>"}),t.addHistory(v),h(t.getHistory());return}a("thinking");let k=await b.remove(f);a("idle"),k.ok?(ot(b.getCommands().map(z=>({cmd:z.cmd,description:z.description}))),g({type:"done",content:`Plugin "${f}" removed`})):g({type:"error",content:k.error||"Remove failed"});}else C==="reload"?(b.reload(),ot(b.getCommands().map(k=>({cmd:k.cmd,description:k.description}))),g({type:"done",content:`Plugins reloaded (${b.getAll().length} loaded)`})):g({type:"error",content:"Usage: /plugin [list | install <path> | remove <name> | reload]"});t.addHistory(v),h(t.getHistory());return}if(v.startsWith("/")){let _=he.getInstance().getCommands(),C=v.trim(),F=_.find(f=>{let b=f.cmd.trimEnd();return C===b||C.startsWith(b+" ")});if(F){let f=F.cmd.trimEnd(),b=C.slice(f.length).trim();a("thinking");try{let k=await F.handler(b,{cwd:e});a("idle"),k.type==="error"?g({type:"error",content:k.content}):k.type==="command"?g({type:"command",commandTitle:k.title,content:k.content}):g({type:"done",content:k.content});}catch(k){a("idle"),g({type:"error",content:`Plugin error: ${String(k)}`});}t.addHistory(v),h(t.getHistory());return}}switch(v.trim().toLowerCase()){case "exit":case "quit":o();return;case "clear":s([]);return;case "help":case "/help":g({type:"command",commandTitle:"help",content:["**Attachments**"," /attach Attach file or image (@-picker)"," @path/to/file Include file in message (type in input)","","**Session**"," /session List saved sessions"," /session save <name> Save conversation"," /session load <name> Load conversation"," /session delete <name> Delete session"," /compact Summarize & compress conversation","","**Connection**"," /connect Connect to server (popup)"," /model Select model (popup)","","**Configuration**"," /config Show current configuration"," /config provider ollama Use Ollama (localhost:11434)"," /config provider lmstudio Use LM Studio (localhost:1234)"," /config model <name> Switch model"," /config url <url> Set base URL"," /config temperature <val> Set temperature (0.0\u20131.0)","","**System**"," /lsp Run diagnostics (tsc/cargo/go vet/pyflakes/eslint)"," /models List available models"," /doctor Check connection & status"," /clear Clear screen"," /exit Quit","","**Keyboard shortcuts**"," ctrl+c Abort running agent / quit"," ctrl+l Clear chat history"," ctrl+k Clear input line"," \u2191 \u2193 Navigate history"," tab Autocomplete / toggle BUILD\u2194PLAN mode"," PageUp / PageDown Scroll chat","","**Shell**"," $ <cmd> or ! <cmd> e.g.: $ npm test","","**Plugins**"," /plugin List installed plugins"," /plugin install <path> Install plugin from directory or .js file"," /plugin remove <name> Uninstall a plugin"," /plugin reload Reload all plugins"].join(`
188
+ `)});break;case "doctor":{let _=t.get(),C=_.llm.provider==="ollama",F=C?await Z.getOllamaProvider().checkHealth(_.llm.baseURL):await Z.getLMStudioProvider().checkHealth(_.llm.baseURL),f=C?"Ollama":"LM Studio",b=C?"ollama serve":"LM Studio \u2192 start Local Server";g({type:"command",commandTitle:"doctor",content:[` Node.js : \u2713 ${process.version}`,` Platform : \u2713 ${process.platform}`,` ${f.padEnd(9)}: ${F?"\u2713 Reachable":`\u2717 Not reachable \u2014 ${b}`}`,` Provider : ${_.llm.provider}`,` Model : ${_.llm.model}`,` URL : ${_.llm.baseURL||"(default)"}`,` Config : ${t.getConfigPath()}`].join(`
189
+ `)});break}case "models":{let _=t.get(),C=_.llm.provider==="ollama",F=C?await Z.getOllamaProvider().listModels(_.llm.baseURL):await Z.getLMStudioProvider().listModels(_.llm.baseURL);g({type:"command",commandTitle:"models",content:F.length?F.map(b=>` \u2022 ${b}`).join(`
190
+ `):C?" No Ollama models found. Pull one with: ollama pull deepseek-coder":" No LM Studio models found. Open LM Studio and load a model."});break}default:{if(v.startsWith("$")||v.startsWith("!")){vt.current?.write(v.slice(1).trim()+`
191
+ `);break}if(L&&de.current){de.current.inject(v),g({type:"text",content:`> [btw] ${v}`});break}let _=v.trim().replace(/^["']|["']$/g,"");if(/^[A-Za-z]:[\\\/].{2,}/.test(_)||/^\/[^\s]{2,}/.test(_)){let N=await yt(_,e);if(N){tt(Te=>[...Te,N]);return}}let F=/@([^\s]+)/g,f=[],b=v,k;for(;(k=F.exec(v))!==null;)f.push(yt(k[1],e)),b=b.replace(k[0],`[${k[1]}]`);let O=(await Promise.all(f)).filter(N=>N!==null),ee=[...Ae,...O];a("thinking"),u(""),p(0);let nt=ee.length?` [${ee.map(N=>N.name).join(", ")}]`:"";g({type:"text",content:`> ${b}${nt}`}),tt([]);let te=new ft;de.current=te;let je=0;te.on("thinking",()=>{a("thinking"),u("");}),te.on("token",N=>{a("running"),u(Te=>Te+N),je+=N.length,p(je);}),te.on("tool_call",({toolCall:N})=>{u(""),g({type:"tool_call",content:N.tool,toolCall:N});}),te.on("tool_result",({toolCall:N,result:Te})=>{g({type:"tool_result",content:"",toolCall:N,toolResult:Te});}),te.on("confirm_required",({toolCall:N,reason:Te,diffPreview:At})=>{Q({toolCall:N,reason:Te,diffPreview:At});}),te.on("injection",({message:N})=>{}),te.on("error",N=>{a("error"),g({type:"error",content:N});}),te.on("done",({response:N,aborted:Te})=>{u(""),a("idle"),Q(null),de.current=null,Te?g({type:"error",content:"Stopped."}):N&&(g({type:"done",content:N}),St(At=>[...At,{role:"user",content:b},{role:"assistant",content:N}].slice(-20)));});let{convHistory:Wo}=Ct.current;te.run(b,e,ee,$e,Wo).catch(N=>{a("error"),g({type:"error",content:String(N)}),de.current=null;});break}}t.addHistory(v),h(t.getHistory());}},[g,e,o]);useInput((S,A)=>{if(xe||ue||Oe){A.ctrl&&S==="c"&&(Ee(false),we(false),Be(false));return}if(!qe){if(A.pageUp){oe(L=>L+2);return}if(A.pageDown){oe(L=>Math.max(0,L-2));return}}if(!qe&&l==="idle"){if(rt){if(A.upArrow){se(L=>Math.max(0,L-1));return}if(A.downArrow){se(L=>Math.min(Ye.length-1,L+1));return}if(A.tab){let L=Ye[ce];L&&(x(L.cmd.endsWith(" ")?L.cmd:L.cmd.trim()),se(0));return}if(A.escape){x(""),se(0),B(-1);return}return}if(A.tab&&!Ie){Fo(L=>L==="build"?"plan":"build");return}if(A.tab&&Ie){x(D+Ie);return}if(A.upArrow){let L=Math.min(E+1,T.length-1);B(L),T[L]&&x(T[L]);return}if(A.downArrow){let L=Math.max(E-1,-1);B(L),x(L===-1?"":T[L]||"");return}if(A.escape){x(""),B(-1);return}}if(A.ctrl&&S==="c"){de.current?(de.current.abort(),de.current=null,a("idle"),u(""),g({type:"error",content:"Aborted."})):o();return}if(A.ctrl&&S==="l"){s([]);return}if(A.ctrl&&S==="k"){x(""),B(-1);return}y&&(S==="y"||S==="Y"?(de.current?.confirm(true),Q(null)):(S==="n"||S==="N"||A.escape)&&(de.current?.confirm(false),Q(null)));});let ye=t.get();ye.llm.provider==="lmstudio"?"LM Studio":"Ollama";return i.createElement(Box,{flexDirection:"column",height:Yt},qe?i.createElement(i.Fragment,null,i.createElement(Box,{flexGrow:1,alignItems:"center",justifyContent:"center"},i.createElement(to,{config:ye,history:T,onSubmit:Bt})),i.createElement(kt,{config:ye,cwd:e,agentStatus:l,tokenCount:d,mode:ie})):i.createElement(i.Fragment,null,i.createElement(Box,{flexGrow:1,flexShrink:1}),(()=>{let S=rt?Ye.length+3:0,A=c||Ne?c.includes("<think>")?5:2:0,L=Ge.length>0?1:0,Ae=y?.diffPreview?y.diffPreview.contextBefore.length+y.diffPreview.oldLines.length+y.diffPreview.newLines.length+y.diffPreview.contextAfter.length+4:0,$e=y?1+Ae:0,re=4+L+1+S+A+$e+1+2,v=Math.max(2,Yt-re),_=Math.max(20,zt-8),C=yn(n),F=Math.min(G,Math.max(0,C.length-1)),{visible:f,hiddenAbove:b,hiddenBelow:k}=bn(C,v,_,F);return wt.current=b,i.createElement(i.Fragment,null,b>0?i.createElement(Box,{paddingX:1,marginBottom:0},i.createElement(Text,{backgroundColor:"#92400E",color:"#FEF3C7"}," \u2191 PageUp "),i.createElement(Text,{color:"#F59E0B",bold:true}," ",b," older messages hidden above")):i.createElement(Text,null," "),f.map((z,O)=>z.type==="user"?i.createElement(Sn,{key:O,content:z.content,timestamp:z.timestamp}):i.createElement(wn,{key:O,messages:z.messages,model:ye.llm.model})),k>0&&i.createElement(Box,{paddingX:1},i.createElement(Text,{backgroundColor:"#1E3A5F",color:"#BFDBFE"}," \u2193 PageDown "),i.createElement(Text,{color:"#60A5FA",bold:true}," ",k," newer messages below")))})(),(c||Ne&&!c)&&(()=>{let{thinking:S,response:A,stillThinking:L}=Cn(c),Ae=A.replace(/```json[\s\S]*?```/g,"").replace(/\{[\s\S]*?"tool"\s*:/g,""),$e=S.trimEnd().split(`
192
+ `).filter(re=>re.trim()).slice(-3);return i.createElement(Box,{marginBottom:0,flexDirection:"column"},S&&i.createElement(Box,{flexDirection:"column"},i.createElement(Box,null,i.createElement(Text,{color:"#3B82F6"}," \u2502 "),i.createElement(Text,{color:"#6366F1",bold:true},"Reasoning"),L&&i.createElement(it,{label:""})),$e.map((re,v)=>i.createElement(Box,{key:v},i.createElement(Text,{color:"#3B82F6"}," \u2502 "),i.createElement(Text,{color:"#4B5563",italic:true},re.slice(0,zt-10))))),i.createElement(Box,null,i.createElement(Text,{color:"#3B82F6"}," \u2502 "),i.createElement(Box,{flexGrow:1},c?Ae?i.createElement(Box,null,i.createElement(Text,{color:"#D1D5DB",wrap:"wrap"},Ae),i.createElement(Text,{color:"#3B82F6"},"\u2588")):L?i.createElement(Box,null,i.createElement(Text,{color:"#6366F1"},"Thinking "),i.createElement(it,{label:""})):null:i.createElement(Box,null,i.createElement(Text,{color:"#6366F1"},"Thinking "),i.createElement(it,{label:""})))))})(),y&&i.createElement(Box,{flexDirection:"column",marginX:1,marginBottom:1,borderStyle:"single",borderColor:"#F59E0B"},y.diffPreview&&i.createElement(Pt,{filePath:y.diffPreview.filePath,oldLines:y.diffPreview.oldLines,newLines:y.diffPreview.newLines,startLine:y.diffPreview.startLine,contextBefore:y.diffPreview.contextBefore,contextAfter:y.diffPreview.contextAfter}),i.createElement(Box,{paddingX:2,paddingY:0},i.createElement(Text,{color:"#F59E0B"},"Allow "),i.createElement(Text,{color:"#D1D5DB"},y.reason),i.createElement(Text,{color:"#4B5563"}," "),i.createElement(Text,{color:"#22C55E"},"[y] yes"),i.createElement(Text,{color:"#4B5563"}," / "),i.createElement(Text,{color:"#EF4444"},"[n] no"))),xe&&i.createElement(lo,{onConnect:(S,A)=>{t.setLLM({provider:S,baseURL:A}),Ee(false),g({type:"done",content:`Connected \xB7 ${S} ${A}`});},onCancel:()=>Ee(false)}),ue&&i.createElement(co,{models:Tt,loading:bt,currentModel:ye.llm.model,onSelect:S=>{t.setLLM({model:S}),we(false),g({type:"done",content:`Model \u2192 ${S}`});},onCancel:()=>we(false)}),Oe&&i.createElement(mo,{files:et,onSelect:async S=>{Be(false);let A=await yt(S,e);A&&tt(L=>[...L,A]);},onCancel:()=>Be(false)}),rt&&i.createElement(Box,{flexDirection:"column",borderStyle:"round",borderColor:"#2D4A7A",marginX:1},Ye.map((S,A)=>{let L=A===ce;return i.createElement(Box,{key:S.cmd,paddingX:1},i.createElement(Text,{color:L?"#3B82F6":"#374151"},L?"\u25B6 ":" "),i.createElement(Text,{color:L?"#60A5FA":"#6B7280",bold:true},S.cmd.trimEnd()),i.createElement(Text,{color:L?"#4B5563":"#374151"}," ",S.description))})),i.createElement(Box,{flexDirection:"column",borderStyle:"single",borderColor:ie==="plan"?"#14532D":"#1E3A5F",marginX:1},Ge.length>0&&i.createElement(Box,{paddingX:1,flexDirection:"row"},Ge.map((S,A)=>i.createElement(Box,{key:A,marginRight:1},i.createElement(Text,{color:S.type==="image"?"#A78BFA":"#60A5FA"},"@",S.name)))),i.createElement(Box,{paddingX:1},i.createElement(Text,{color:Ne?"#F59E0B":ie==="plan"?"#22C55E":"#3B82F6",bold:true},"> "),i.createElement(Mt,{value:D,onChange:Uo,onSubmit:Bt,placeholder:Ne?"inject message to agent...":ie==="plan"?"describe what to plan...":"/ for commands \xB7 @ to attach files",focus:!y&&!xe&&!ue&&!Oe}),Ie&&!Ne&&i.createElement(Text,{color:"#1F2937"},Ie)),i.createElement(Box,{paddingX:1,justifyContent:"space-between"},i.createElement(Box,null,Ne?i.createElement(i.Fragment,null,i.createElement(Text,{color:"#F59E0B"},"ctrl+c "),i.createElement(Text,{color:"#6B7280"},"abort "),i.createElement(Text,{color:"#4B5563"},"\u21B5 "),i.createElement(Text,{color:"#6B7280"},"inject message")):i.createElement(i.Fragment,null,i.createElement(Text,{color:"#4B5563"},"\u21B5 "),i.createElement(Text,{color:"#6B7280"},"send "),i.createElement(Text,{color:"#4B5563"},"tab "),i.createElement(Text,{color:"#6B7280"},Ie?"complete":"switch mode"," "),i.createElement(Text,{color:"#4B5563"},"@ "),i.createElement(Text,{color:"#6B7280"},"attach"),wt.current>0&&i.createElement(i.Fragment,null,i.createElement(Text,{color:"#4B5563"}," \u2502 "),i.createElement(Text,{color:"#F59E0B"},"\u2191 PgUp "),i.createElement(Text,{color:"#D97706"},wt.current," hidden")))),i.createElement(Box,null,i.createElement(Text,{backgroundColor:ie==="plan"?"#166534":"#1D4ED8",color:ie==="plan"?"#86EFAC":"#BFDBFE"}," ",ie==="plan"?"PLAN":"BUILD"," "),i.createElement(Text,{color:"#374151"}," "),i.createElement(Text,{color:"#9CA3AF"},ye.llm.model.length>24?ye.llm.model.slice(0,24)+"\u2026":ye.llm.model)))),i.createElement(kt,{config:ye,cwd:e,agentStatus:l,tokenCount:d,mode:ie})))};var Ze=process.argv.slice(2),kn=process.cwd();(Ze.includes("--help")||Ze.includes("-h"))&&(process.stdout.write(`
193
+ ${V.bold.blue("\u26A1 LocalCode")} ${V.gray("v0.1.0")} ${V.gray("\u2014 Futuristic AI Developer Terminal")}
194
+
195
+ ${V.bold("Usage:")}
196
+ ${V.blue("localcode")} Start interactive TUI
197
+ ${V.blue("localcode")} <task> Run AI task directly
198
+ ${V.blue("localcode")} --provider <p> Override LLM provider
199
+ ${V.blue("localcode")} --model <m> Override model
200
+ ${V.blue("localcode")} --help Show this help
201
+
202
+ ${V.bold("Examples:")}
203
+ ${V.gray("localcode")}
204
+ ${V.gray("localcode fix auth bug")}
205
+ ${V.gray("localcode --provider ollama --model llama3 fix typescript errors")}
206
+ ${V.gray("localcode --provider openai --model gpt-4o create REST API")}
207
+
208
+ ${V.bold("Providers:")} ollama \xB7 openai \xB7 claude \xB7 openrouter \xB7 lmstudio
209
+
210
+ ${V.bold("Config:")} ~/.localcode/config.json
211
+ `),process.exit(0));(Ze.includes("--version")||Ze.includes("-v"))&&(process.stdout.write(`0.1.0
212
+ `),process.exit(0));var Ke=[...Ze];function _o(r){let e=Ke.indexOf(r);if(e===-1)return;let o=Ke[e+1];return Ke.splice(e,2),o}var Ht=_o("--provider"),Xt=_o("--model");(Ht||Xt)&&_e.getInstance().setLLM({...Ht&&{provider:Ht},...Xt&&{model:Xt}});var Pn=Ke.length>0?Ke.join(" "):void 0,Eo=process.stdout.isTTY;function _n(){Eo&&process.stdout.write("\x1B[?1049h\x1B[2J\x1B[3J\x1B[H\x1B[?1000h\x1B[?1006h");}function Re(){Eo&&process.stdout.write("\x1B[?1006l\x1B[?1000l\x1B[?1049l");}var Gt=class extends Transform{isTTY;constructor(){super(),this.isTTY=process.stdin.isTTY;}setRawMode(e){return process.stdin.setRawMode?.(e),this}ref(){return process.stdin.ref?.(),this}unref(){return process.stdin.unref?.(),this}_transform(e,o,t){let s=e.toString("binary").replace(/\x1b\[<(\d+);\d+;\d+[Mm]/g,(l,a)=>{let c=parseInt(a,10);return c===64?"\x1B[5~":c===65?"\x1B[6~":""});s.length>0&&this.push(Buffer.from(s,"binary")),t();}},Mo=new Gt;process.stdin.pipe(Mo);process.on("exit",Re);process.on("SIGINT",()=>{Re(),process.exit(0);});process.on("SIGTERM",()=>{Re(),process.exit(0);});process.on("uncaughtException",()=>{Re(),process.exit(1);});_n();var{waitUntilExit:En}=render(i.createElement(Po,{initialCommand:Pn,cwd:kn}),{stdin:Mo,exitOnCtrlC:false,patchConsole:true});En().then(()=>{Re(),process.exit(0);});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "localcode-agent",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Futuristic AI Developer Terminal & Autonomous Coding Agent",
5
5
  "license": "MIT",
6
6
  "type": "module",