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.
- package/dist/localcode.js +71 -71
- 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
|
|
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
|
|
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=
|
|
129
|
-
`).filter(
|
|
130
|
-
`);u=
|
|
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
|
|
133
|
-
`).map((l,
|
|
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
|
|
136
|
-
`).length} lines)`}}async function
|
|
137
|
-
`).length,
|
|
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=
|
|
140
|
-
`),diffStartLine:
|
|
141
|
-
`)||"(empty directory)"}}async function
|
|
142
|
-
`)||"No files found."}}async function
|
|
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:[
|
|
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
|
|
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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/[ \t]{2,}/g," ").replace(/\n{3,}/g,`
|
|
147
147
|
|
|
148
|
-
`).trim()}}async function
|
|
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
|
-
${
|
|
151
|
-
`),error:l>0?`${l} error(s)`:void 0}}var Fe=Pe.join(
|
|
152
|
-
${
|
|
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
|
-
`),
|
|
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: ${
|
|
156
|
+
Task: ${d}
|
|
157
157
|
|
|
158
|
-
Working directory: ${
|
|
158
|
+
Working directory: ${a}`:`Task: ${d}
|
|
159
159
|
|
|
160
|
-
Working directory: ${
|
|
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
|
-
`+
|
|
164
|
-
{"tool": "${
|
|
165
|
-
`):"",
|
|
166
|
-
`).length,
|
|
167
|
-
`),
|
|
168
|
-
`),
|
|
169
|
-
`),startLine:
|
|
170
|
-
${
|
|
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
|
|
175
|
-
`).reduce((o,t)=>o+Math.max(1,Math.ceil((t.length||1)/Math.max(1,e))),0)}function
|
|
176
|
-
`).length+(t.commandTitle?1:0)+2;else if(t.type==="text")o+=
|
|
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,
|
|
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(
|
|
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
|
|
181
|
-
URL \u2192 ${
|
|
182
|
-
`)});}t.addHistory(
|
|
183
|
-
`)});}t.addHistory(
|
|
184
|
-
`),
|
|
185
|
-
${
|
|
186
|
-
`):" No sessions saved yet. Use /session save <name>"});}else if(
|
|
187
|
-
`)});}else if(
|
|
188
|
-
`)});break;case "doctor":{let _=t.get(),
|
|
189
|
-
`)});break}case "models":{let _=t.get(),
|
|
190
|
-
`):
|
|
191
|
-
`);break}if(
|
|
192
|
-
`).filter(
|
|
193
|
-
${
|
|
194
|
-
|
|
195
|
-
${
|
|
196
|
-
${
|
|
197
|
-
${
|
|
198
|
-
${
|
|
199
|
-
${
|
|
200
|
-
${
|
|
201
|
-
|
|
202
|
-
${
|
|
203
|
-
${
|
|
204
|
-
${
|
|
205
|
-
${
|
|
206
|
-
${
|
|
207
|
-
|
|
208
|
-
${
|
|
209
|
-
|
|
210
|
-
${
|
|
211
|
-
`),process.exit(0));(
|
|
212
|
-
`),process.exit(0));var
|
|
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);});
|