@iamharshil/cortex 5.0.0-beta.1 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/tui.js +19 -0
- package/dist/bin/index.js +37 -726
- package/dist/index.js +25 -25
- package/dist/tui/index.js +431 -0
- package/package.json +10 -3
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as
|
|
2
|
+
import{Command as se}from"commander";import d from"chalk";import m from"chalk";import{readFile as te}from"fs/promises";import{join as z}from"path";import{homedir as oe}from"os";var k=class{name="ollama";baseUrl;defaultModel;timeout;constructor(e){this.baseUrl=e.baseUrl||"http://localhost:11434",this.defaultModel=e.defaultModel||"llama3.2",this.timeout=e.timeout||12e4}async chat(e,t,o){let r={model:o||this.defaultModel,messages:this.formatMessages(e),stream:!1};t&&t.length>0&&(r.tools=t.map(n=>({type:"function",function:{name:n.name,description:n.description,parameters:n.input_schema}})));try{let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout)});if(!n.ok){let c=await n.text();throw new Error(`Ollama API error: ${n.status} - ${c}`)}let a=await n.json();return{content:a.message?.content||"",tool_calls:a.message?.tool_calls?.map(c=>({id:c.id,type:"function",function:{name:c.function.name,arguments:c.function.arguments}})),stop_reason:a.done?"stop":void 0}}catch(n){throw n instanceof Error&&n.name==="TimeoutError"?new Error(`Ollama request timed out after ${this.timeout}ms`):n}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`);return e.ok?(await e.json()).models?.map(o=>o.name)||[]:[]}catch{return[]}}getTokenizer(){return e=>Math.ceil(e.length/4)}formatMessages(e){return e.map(t=>({role:t.role==="tool"?"user":t.role,content:t.content}))}},$=class{name="lmstudio";baseUrl;defaultModel;timeout;constructor(e){this.baseUrl=e.baseUrl||"http://localhost:1234/v1",this.defaultModel=e.defaultModel||"llama-3.1-8b",this.timeout=e.timeout||12e4}async chat(e,t,o){let r={model:o||this.defaultModel,messages:this.formatMessages(e),stream:!1};t&&t.length>0&&(r.tools=t.map(n=>({type:"function",function:{name:n.name,description:n.description,parameters:n.input_schema}})));try{let n=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout)});if(!n.ok){let l=await n.text();throw new Error(`LM Studio API error: ${n.status} - ${l}`)}let c=(await n.json()).choices?.[0];return{content:c?.message?.content||"",tool_calls:c?.message?.tool_calls?.map(l=>({id:l.id,type:"function",function:{name:l.function.name,arguments:l.function.arguments}}))}}catch(n){throw n instanceof Error&&n.name==="TimeoutError"?new Error(`LM Studio request timed out after ${this.timeout}ms`):n}}async listModels(){try{let e=await fetch(`${this.baseUrl.replace("/v1","")}/api/v0/models`);return e.ok?(await e.json()).data?.map(o=>o.id)||[]:[]}catch{return[]}}getTokenizer(){return e=>Math.ceil(e.length/4)}formatMessages(e){return e.map(t=>({role:t.role==="tool"?"user":t.role,content:t.content}))}},j=class{name="openrouter";apiKey;baseUrl;defaultModel;timeout;constructor(e){this.apiKey=e.apiKey,this.baseUrl=e.baseUrl||"https://openrouter.ai/api/v1",this.defaultModel=e.defaultModel||"anthropic/claude-3.5-sonnet",this.timeout=e.timeout||12e4}async chat(e,t,o){let r={model:o||this.defaultModel,messages:this.formatMessages(e)};t&&t.length>0&&(r.tools=t.map(n=>({type:"function",function:{name:n.name,description:n.description,parameters:n.input_schema}})));try{let n=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"HTTP-Referer":"https://cortex.dev","X-Title":"Cortex"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout)});if(!n.ok){let l=await n.text();throw new Error(`OpenRouter API error: ${n.status} - ${l}`)}let c=(await n.json()).choices?.[0];return{content:c?.message?.content||"",tool_calls:c?.message?.tool_calls?.map(l=>({id:l.id,type:"function",function:{name:l.function.name,arguments:l.function.arguments}})),stop_reason:c?.finish_reason}}catch(n){throw n instanceof Error&&n.name==="TimeoutError"?new Error(`OpenRouter request timed out after ${this.timeout}ms`):n}}async listModels(){try{let e=await fetch(`${this.baseUrl}/models`,{headers:{Authorization:`Bearer ${this.apiKey}`}});return e.ok?(await e.json()).data?.map(o=>o.id)||[]:[]}catch{return[]}}getTokenizer(){return e=>Math.ceil(e.length/4)}formatMessages(e){return e.map(t=>t.tool_calls?{role:"assistant",content:t.content||"",tool_calls:t.tool_calls.map(o=>({id:o.id,type:o.type,function:{name:o.function.name,arguments:o.function.arguments}}))}:t.tool_call_id?{role:"tool",content:t.content,tool_call_id:t.tool_call_id}:{role:t.role==="tool"?"user":t.role,content:t.content})}};function v(i){switch(i.type){case"ollama":return new k(i);case"lmstudio":return new $(i);case"openrouter":return new j(i);default:throw new Error(`Unknown provider type: ${i.type}`)}}import{join as O}from"path";import{homedir as W}from"os";import{access as A}from"fs/promises";var L={maxTokens:18e4,systemPromptTokens:3e3,toolDefTokens:5e3,warningThreshold:.7,autoCompactThreshold:.95},x=class{messages=[];config;tokenCount=0;memoryFiles=[];constructor(e={}){this.config={...L,...e}}getSystemPrompt(){return`You are Cortex, an autonomous AI coding agent. You have access to tools to read, write, and edit files, execute shell commands, and search through the codebase.
|
|
3
3
|
|
|
4
4
|
## Your Capabilities
|
|
5
5
|
- Read, write, and edit files in the codebase
|
|
@@ -20,21 +20,21 @@ You are working in the current directory. Use absolute paths for file operations
|
|
|
20
20
|
|
|
21
21
|
## Tools
|
|
22
22
|
You have access to the following tools:
|
|
23
|
-
${
|
|
23
|
+
${B.map(e=>`- ${e.name}: ${e.description}`).join(`
|
|
24
24
|
`)}
|
|
25
25
|
`}addMessage(e){this.messages.push(e),this.updateTokenCount()}getMessages(){return[...this.messages]}getMessagesForAPI(){return[{role:"system",content:this.getSystemPrompt()},...this.messages]}async compact(e){let t=this.summarizeConversation(e),o=this.messages.filter(r=>r.role==="user").pop(),s=this.messages.filter(r=>r.role==="assistant").pop();this.messages=[],o&&this.messages.push({role:"user",content:`[Previous conversation summary]: ${t}
|
|
26
26
|
|
|
27
27
|
[Continuing from previous session]
|
|
28
28
|
|
|
29
|
-
${o.content}`}),s&&this.messages.push({role:"assistant",content:s.content}),this.updateTokenCount()}summarizeConversation(e){let t=e?500:300,o=this.messages.filter(a=>a.tool_calls).map(a=>a.tool_calls?.map(c=>c.function.name).join(", ")).join("; "),s=this.messages.filter(a=>a.role==="tool"&&a.content?.includes("File edited")).length,r=this.messages.filter(a=>a.role==="tool"&&a.content?.includes("File written")).length,n=`Session summary: ${s} files edited, ${r} files created`;return o&&(n+=`. Tools used: ${o}`),n.slice(0,t)}getTokenUsage(){let e=this.config.systemPromptTokens,t=this.config.toolDefTokens,o=this.estimateTokens(this.messagesToString()),s=this.memoryFiles.length*500,r=e+t+o+s,n=this.config.maxTokens-r;return{system:e,tools:t,messages:o,memory:s,available:n,total:this.config.maxTokens}}shouldCompact(){let e=this.getTokenUsage();return(this.config.maxTokens-e.available)/this.config.maxTokens>this.config.autoCompactThreshold}shouldWarn(){let e=this.getTokenUsage();return(this.config.maxTokens-e.available)/this.config.maxTokens>this.config.warningThreshold}async loadProjectMemory(e){let t=O(e,"CORTEX.md");try{await A(t),this.memoryFiles.push(t)}catch{}}async loadUserMemory(){let e=
|
|
29
|
+
${o.content}`}),s&&this.messages.push({role:"assistant",content:s.content}),this.updateTokenCount()}summarizeConversation(e){let t=e?500:300,o=this.messages.filter(a=>a.tool_calls).map(a=>a.tool_calls?.map(c=>c.function.name).join(", ")).join("; "),s=this.messages.filter(a=>a.role==="tool"&&a.content?.includes("File edited")).length,r=this.messages.filter(a=>a.role==="tool"&&a.content?.includes("File written")).length,n=`Session summary: ${s} files edited, ${r} files created`;return o&&(n+=`. Tools used: ${o}`),n.slice(0,t)}getTokenUsage(){let e=this.config.systemPromptTokens,t=this.config.toolDefTokens,o=this.estimateTokens(this.messagesToString()),s=this.memoryFiles.length*500,r=e+t+o+s,n=this.config.maxTokens-r;return{system:e,tools:t,messages:o,memory:s,available:n,total:this.config.maxTokens}}shouldCompact(){let e=this.getTokenUsage();return(this.config.maxTokens-e.available)/this.config.maxTokens>this.config.autoCompactThreshold}shouldWarn(){let e=this.getTokenUsage();return(this.config.maxTokens-e.available)/this.config.maxTokens>this.config.warningThreshold}async loadProjectMemory(e){let t=O(e,"CORTEX.md");try{await A(t),this.memoryFiles.push(t)}catch{}}async loadUserMemory(){let e=W(),t=O(e,".cortex","memory.md");try{await A(t),this.memoryFiles.push(t)}catch{}}clear(){this.messages=[],this.tokenCount=0}updateTokenCount(){let e=this.messagesToString();this.tokenCount=this.estimateTokens(e)}messagesToString(){return this.messages.map(e=>{let t=`${e.role}: ${e.content}`;return e.tool_calls&&(t+=`
|
|
30
30
|
`+JSON.stringify(e.tool_calls)),t}).join(`
|
|
31
|
-
`)}estimateTokens(e){return Math.ceil(e.length/4)}},
|
|
31
|
+
`)}estimateTokens(e){return Math.ceil(e.length/4)}},B=[{name:"Read",description:"Read the contents of a file from the filesystem."},{name:"Write",description:"Create a new file or overwrite an existing file."},{name:"Edit",description:"Make a precise edit to an existing file."},{name:"Bash",description:"Execute a shell command in the terminal."},{name:"Glob",description:"Find files matching a pattern."},{name:"Grep",description:"Search for text within files."},{name:"TodoWrite",description:"Create and manage a todo list."}];import{readFile as U,writeFile as M,mkdir as K,access as H}from"fs/promises";import{join as u}from"path";import{homedir as X}from"os";var C=class{projectMemory="";userMemory="";sessions=[];configDir;projectDir="";constructor(){this.configDir=u(X(),".cortex")}async initialize(e){this.projectDir=e,await this.ensureConfigDir(),await this.loadProjectMemory(e),await this.loadUserMemory(),await this.loadSessionHistory()}async ensureConfigDir(){try{await K(this.configDir,{recursive:!0})}catch{}}async loadProjectMemory(e){let t=u(e,"CORTEX.md");try{this.projectMemory=await U(t,"utf-8")}catch{this.projectMemory=""}}async loadUserMemory(){let e=u(this.configDir,"memory.md");try{this.userMemory=await U(e,"utf-8")}catch{this.userMemory=""}}async loadSessionHistory(){let e=u(this.configDir,"sessions.json");try{let t=await U(e,"utf-8");this.sessions=JSON.parse(t)}catch{this.sessions=[]}}async saveSession(e){this.sessions.push(e),this.sessions.length>50&&(this.sessions=this.sessions.slice(-50));let t=u(this.configDir,"sessions.json");await M(t,JSON.stringify(this.sessions,null,2))}async updateProjectMemory(e){if(!this.projectDir)return;let t=u(this.projectDir,"CORTEX.md");await M(t,e,"utf-8"),this.projectMemory=e}async updateUserMemory(e){let t=u(this.configDir,"memory.md");await M(t,e,"utf-8"),this.userMemory=e}getProjectMemory(){return this.projectMemory}getUserMemory(){return this.userMemory}getMemoryForContext(){let e=[];if(this.projectMemory&&e.push(`## Project Memory (${this.projectDir})
|
|
32
32
|
${this.projectMemory}`),this.userMemory&&e.push(`## User Memory
|
|
33
33
|
${this.userMemory}`),this.sessions.length>0){let t=this.sessions.slice(-5);e.push(`## Recent Sessions
|
|
34
34
|
${t.map(o=>`- ${new Date(o.endTime).toLocaleDateString()}: ${o.summary}`).join(`
|
|
35
35
|
`)}`)}return e.join(`
|
|
36
36
|
|
|
37
|
-
`)}getSessions(){return this.sessions}async createProjectMemoryFile(){if(!this.projectDir)return;let e=
|
|
37
|
+
`)}getSessions(){return this.sessions}async createProjectMemoryFile(){if(!this.projectDir)return;let e=u(this.projectDir,"CORTEX.md");try{await H(e)}catch{let t=`# Cortex Project Memory
|
|
38
38
|
|
|
39
39
|
## Project Overview
|
|
40
40
|
<!-- Fill in your project description -->
|
|
@@ -47,30 +47,30 @@ ${t.map(o=>`- ${new Date(o.endTime).toLocaleDateString()}: ${o.summary}`).join(`
|
|
|
47
47
|
|
|
48
48
|
## Architecture Notes
|
|
49
49
|
<!-- Document important architectural decisions -->
|
|
50
|
-
`;await M(e,t),this.projectMemory=t}}};import{execa as
|
|
50
|
+
`;await M(e,t),this.projectMemory=t}}};import{execa as Y}from"execa";import{readFile as R,writeFile as D}from"fs/promises";import{resolve as F,dirname as V}from"path";import I from"fast-glob";var E=[{name:"Read",description:"Read the contents of a file from the filesystem. Use this when you need to see what's in a file. Provide the absolute_path to the file. Use offset and limit to read specific portions of large files.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read"},offset:{type:"number",description:"Line number to start reading from (1-indexed)",default:1},limit:{type:"number",description:"Maximum number of lines to read",default:1e3}},required:["file_path"]}},{name:"Write",description:"Create a new file or overwrite an existing file with new content. Use this to create new files or make significant changes that warrant full replacement rather than targeted edits.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write"},content:{type:"string",description:"Complete file content to write"}},required:["file_path","content"]}},{name:"Edit",description:"Make a precise edit to an existing file using a search and replace pattern. Use this for targeted modifications. The old_string must match exactly including whitespace and indentation.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit"},old_string:{type:"string",description:"The exact text to find and replace (must match exactly including whitespace)"},new_string:{type:"string",description:"The replacement text"}},required:["file_path","old_string","new_string"]}},{name:"Bash",description:"Execute a shell command in the terminal. Use this to run commands, scripts, git operations, or any other system operations. The working_directory defaults to the current directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"The command to execute"},description:{type:"string",description:"What this command does (for context)",default:""}},required:["command"]}},{name:"Glob",description:"Find files matching a pattern using glob syntax. Useful for discovering files in a project without reading their contents.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g., "**/*.ts", "src/**/*.js")'},path:{type:"string",description:"Directory to search in (defaults to current directory)",default:"."}},required:["pattern"]}},{name:"Grep",description:"Search for text within files. Returns matching lines with file paths.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for"},path:{type:"string",description:"Directory or file to search in",default:"."},include:{type:"string",description:'File pattern to include (e.g., "*.ts", "*.js")'}},required:["pattern"]}},{name:"TodoWrite",description:"Create and manage a todo list for tracking multi-step tasks. Use this to organize complex tasks into manageable steps.",input_schema:{type:"object",properties:{todos:{type:"array",description:"Array of todo items with content, status, and priority",items:{type:"object",properties:{content:{type:"string",description:"Description of the task"},status:{type:"string",enum:["pending","in_progress","completed","cancelled"],default:"pending"},priority:{type:"string",enum:["high","medium","low"],default:"medium"}},required:["content","status","priority"]}}},required:["todos"]}}];async function q(i,e,t){let o=`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;try{switch(i){case"Read":{let s=e.file_path,r=e.offset||1,n=e.limit||1e3,c=(await R(s,"utf-8")).split(`
|
|
51
51
|
`),l=c.slice(r-1,r-1+n);return{tool_call_id:o,output:l.join(`
|
|
52
52
|
`)+(c.length>r-1+n?`
|
|
53
53
|
|
|
54
|
-
... ${c.length-(r-1+n)} more lines`:"")}}case"Write":{let s=e.file_path,r=e.content,n=
|
|
54
|
+
... ${c.length-(r-1+n)} more lines`:"")}}case"Write":{let s=e.file_path,r=e.content,n=V(s);return await Q(n,{recursive:!0}),await D(s,r,"utf-8"),{tool_call_id:o,output:`File written: ${s}`}}case"Edit":{let s=e.file_path,r=e.old_string,n=e.new_string,a=await R(s,"utf-8");if(!a.includes(r))return{tool_call_id:o,output:"Error: Could not find the specified text to replace. The old_string must match exactly.",is_error:!0};let c=a.replace(r,n);return await D(s,c,"utf-8"),{tool_call_id:o,output:`File edited: ${s}`}}case"Bash":{let s=e.command,r=e.description||"",{stdout:n,stderr:a,exitCode:c}=await Y(s,{shell:!0,cwd:t,timeout:12e4}),l=a?`${n}
|
|
55
55
|
${a}`:n;if(c!==0&&!n)return{tool_call_id:o,output:`Command failed with exit code ${c}: ${s}
|
|
56
|
-
${a}`,is_error:!0};let
|
|
56
|
+
${a}`,is_error:!0};let p=l.length>15e3?l.slice(0,15e3)+`
|
|
57
57
|
|
|
58
|
-
... output truncated (${l.length} chars)`:l;return{tool_call_id:o,output:
|
|
59
|
-
`):"No files found"}}case"Grep":{let s=e.pattern,r=e.path||".",n=e.include,a=F(t,r),c=await
|
|
60
|
-
`);for(let
|
|
58
|
+
... output truncated (${l.length} chars)`:l;return{tool_call_id:o,output:p||`Command executed successfully (exit code: ${c})`}}case"Glob":{let s=e.pattern,r=e.path||".",n=F(t,r),a=await I(s,{cwd:n,absolute:!0,onlyFiles:!0});return{tool_call_id:o,output:a.length>0?a.join(`
|
|
59
|
+
`):"No files found"}}case"Grep":{let s=e.pattern,r=e.path||".",n=e.include,a=F(t,r),c=await I(n||"**/*",{cwd:a,onlyFiles:!0}),l=[];for(let w of c.slice(0,100))try{let S=(await R(w,"utf-8")).split(`
|
|
60
|
+
`);for(let y=0;y<S.length;y++)new RegExp(s,"i").test(S[y])&&l.push(`${w}:${y+1}: ${S[y]}`)}catch{}let p=l.length>100?l.slice(0,100).concat([`... ${l.length-100} more matches`]):l;return{tool_call_id:o,output:p.length>0?p.join(`
|
|
61
61
|
`):"No matches found"}}case"TodoWrite":{let s=e.todos;return{tool_call_id:o,output:`Todo list updated with ${s.length} items:
|
|
62
62
|
${s.map((r,n)=>`${n+1}. [${r.status}] ${r.content}`).join(`
|
|
63
|
-
`)}`}}default:return{tool_call_id:o,output:`Unknown tool: ${i}`,is_error:!0}}}catch(s){return{tool_call_id:o,output:`Error executing ${i}: ${s instanceof Error?s.message:String(s)}`,is_error:!0}}}async function
|
|
63
|
+
`)}`}}default:return{tool_call_id:o,output:`Unknown tool: ${i}`,is_error:!0}}}catch(s){return{tool_call_id:o,output:`Error executing ${i}: ${s instanceof Error?s.message:String(s)}`,is_error:!0}}}async function Q(i,e){let{mkdirSync:t}=await import("fs");t(i,e)}import{execa as Z}from"execa";import{EventEmitter as ee}from"events";var P=class extends ee{servers=new Map;processes=new Map;tools=new Map;requestId=0;pendingRequests=new Map;initialized=!1;async addServer(e){this.servers.set(e.name,e),e.type==="stdio"?await this.connectStdioServer(e):e.type==="http"&&e.url&&await this.connectHttpServer(e)}async removeServer(e){let t=this.servers.get(e);if(t){if(t.type==="stdio"){let o=this.processes.get(e);o&&(o.kill(),this.processes.delete(e))}this.servers.delete(e),this.tools.delete(e)}}async listTools(e){let t={};if(e){let o=this.tools.get(e);if(o)for(let s of o)t[`${e}/${s.name}`]=s}else for(let[o,s]of this.tools)for(let r of s)t[`${o}/${r.name}`]=r;return t}async callTool(e,t,o){let s=this.servers.get(e);if(!s)throw new Error(`Unknown MCP server: ${e}`);return s.type==="http"&&s.url?this.callHttpTool(s.url,t,o):this.callStdioTool(e,t,o)}async connectStdioServer(e){let t=++this.requestId;try{let o=Z(e.command,e.args||[],{env:{...process.env,...e.env},stdio:["pipe","pipe","pipe"]});this.processes.set(e.name,o),o.stdout?.on("data",s=>{this.handleStdioMessage(e.name,s.toString())}),o.stderr?.on("data",s=>{console.error(`[MCP ${e.name}]`,s.toString())}),await this.sendStdioRequest(e.name,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"cortex",version:"5.0.0"}}),this.tools.set(e.name,[]),this.initialized=!0}catch(o){console.error(`Failed to connect to MCP server ${e.name}:`,o)}}async connectHttpServer(e){if(e.url)try{let t=await fetch(`${e.url}/initialize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"cortex",version:"5.0.0"}})});if(t.ok){let o=await t.json();this.tools.set(e.name,o.tools||[])}}catch(t){console.error(`Failed to connect to MCP server ${e.name}:`,t)}}async sendStdioRequest(e,t,o){let s=++this.requestId,r=this.processes.get(e);if(!r||!r.stdin)throw new Error(`MCP server ${e} not connected`);return new Promise((n,a)=>{this.pendingRequests.set(s,{resolve:n,reject:a}),r.stdin?.write(JSON.stringify({jsonrpc:"2.0",id:s,method:t,params:o})+`
|
|
64
64
|
`),setTimeout(()=>{this.pendingRequests.has(s)&&(this.pendingRequests.delete(s),a(new Error("MCP request timeout")))},3e4)})}handleStdioMessage(e,t){try{let o=t.split(`
|
|
65
|
-
`).filter(Boolean);for(let s of o){let r=JSON.parse(s);if(r.id&&this.pendingRequests.has(r.id)){let n=this.pendingRequests.get(r.id);this.pendingRequests.delete(r.id),r.error?n.reject(new Error(r.error.message||"MCP error")):n.resolve(r.result)}if(r.method==="tools/list"){let n=r.params?.tools||[];this.tools.set(e,n),this.emit("toolsUpdated",{server:e,tools:n})}r.method==="notifications/tools_changed"&&this.refreshTools(e)}}catch{}}async callStdioTool(e,t,o){let s=await this.sendStdioRequest(e,"tools/call",{name:t,arguments:o});return JSON.stringify(s)}async callHttpTool(e,t,o){let s=await fetch(`${e}/tools/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,arguments:o})});if(!s.ok)throw new Error(`MCP tool call failed: ${s.status}`);let r=await s.json();return JSON.stringify(r.content?.[0]?.text||"")}async refreshTools(e){let t=this.servers.get(e);if(t)if(t.type==="http"&&t.url)await this.connectHttpServer(t);else try{let s=(await this.sendStdioRequest(e,"tools/list",{}))?.tools||[];this.tools.set(e,s)}catch{}}getToolsForContext(){let e=[];for(let[t,o]of this.tools)for(let s of o)e.push({name:`${t}/${s.name}`,description:s.description,input_schema:s.inputSchema});return e}disconnect(){for(let[e,t]of this.processes)t.kill();this.processes.clear(),this.servers.clear(),this.tools.clear(),this.initialized=!1}};var T=class{provider;context;memory;mcp;config;tools=[...
|
|
65
|
+
`).filter(Boolean);for(let s of o){let r=JSON.parse(s);if(r.id&&this.pendingRequests.has(r.id)){let n=this.pendingRequests.get(r.id);this.pendingRequests.delete(r.id),r.error?n.reject(new Error(r.error.message||"MCP error")):n.resolve(r.result)}if(r.method==="tools/list"){let n=r.params?.tools||[];this.tools.set(e,n),this.emit("toolsUpdated",{server:e,tools:n})}r.method==="notifications/tools_changed"&&this.refreshTools(e)}}catch{}}async callStdioTool(e,t,o){let s=await this.sendStdioRequest(e,"tools/call",{name:t,arguments:o});return JSON.stringify(s)}async callHttpTool(e,t,o){let s=await fetch(`${e}/tools/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,arguments:o})});if(!s.ok)throw new Error(`MCP tool call failed: ${s.status}`);let r=await s.json();return JSON.stringify(r.content?.[0]?.text||"")}async refreshTools(e){let t=this.servers.get(e);if(t)if(t.type==="http"&&t.url)await this.connectHttpServer(t);else try{let s=(await this.sendStdioRequest(e,"tools/list",{}))?.tools||[];this.tools.set(e,s)}catch{}}getToolsForContext(){let e=[];for(let[t,o]of this.tools)for(let s of o)e.push({name:`${t}/${s.name}`,description:s.description,input_schema:s.inputSchema});return e}disconnect(){for(let[e,t]of this.processes)t.kill();this.processes.clear(),this.servers.clear(),this.tools.clear(),this.initialized=!1}};var T=class{provider;context;memory;mcp;config;tools=[...E];cwd;planMode=!1;currentPlan=[];constructor(e,t){this.config=e,this.cwd=t;let o={type:e.provider,baseUrl:e.providerUrl,apiKey:e.apiKey,defaultModel:e.model};this.provider=v(o),this.context=new x,this.memory=new C,this.mcp=new P,this.planMode=e.planMode||!1}async initialize(){console.log(m.blue("\u{1F9E0} Initializing Cortex...")),await this.memory.initialize(this.cwd),await this.context.loadProjectMemory(this.cwd),await this.context.loadUserMemory(),await this.loadMCPConfig(),console.log(m.green("\u2705 Cortex ready!"))}async loadMCPConfig(){let e=[z(this.cwd,".cortex","mcp.json"),z(oe(),".cortex","mcp.json")];for(let t of e)try{let o=await te(t,"utf-8"),s=JSON.parse(o);if(s.servers)for(let[r,n]of Object.entries(s.servers))await this.mcp.addServer({name:r,command:n.command,args:n.args,env:n.env,type:n.type||"stdio",url:n.url})}catch{}if(this.mcp.listTools()){let t=this.mcp.getToolsForContext();this.tools=[...E,...t]}}async run(e){console.log(m.cyan(`
|
|
66
66
|
\u{1F916} Thinking...
|
|
67
|
-
`)),this.planMode?await this.runWithPlanMode(e):await this.runDirect(e)}async runDirect(e){let t=0,o=this.config.maxIterations||50,s=!1;for(this.context.addMessage({role:"user",content:e});!s&&t<o;){t++,this.context.shouldWarn()&&console.log(
|
|
68
|
-
\u{1F527} ${c}: ${JSON.stringify(l)}`));let
|
|
67
|
+
`)),this.planMode?await this.runWithPlanMode(e):await this.runDirect(e)}async runDirect(e){let t=0,o=this.config.maxIterations||50,s=!1;for(this.context.addMessage({role:"user",content:e});!s&&t<o;){t++,this.context.shouldWarn()&&console.log(m.yellow(`\u26A0\uFE0F Context usage high (${Math.round((1-this.context.getTokenUsage().available/this.context.getTokenUsage().total)*100)}%)`));try{let r=await this.provider.chat(this.context.getMessagesForAPI(),this.tools,this.config.model);if(console.log(m.white(r.content)),r.tool_calls&&r.tool_calls.length>0){let n={role:"assistant",content:r.content,tool_calls:r.tool_calls};this.context.addMessage(n);for(let a of r.tool_calls){let c=a.function.name,l=JSON.parse(a.function.arguments);console.log(m.dim(`
|
|
68
|
+
\u{1F527} ${c}: ${JSON.stringify(l)}`));let p=await q(c,l,this.cwd),w={role:"tool",content:p.output,tool_call_id:a.id,name:c};this.context.addMessage(w),p.is_error&&console.log(m.red(`\u274C ${p.output}`))}}else s=!0;(r.stop_reason==="stop"||r.stop_reason==="end_turn")&&(s=!0)}catch(r){console.error(m.red(`Error: ${r instanceof Error?r.message:String(r)}`));break}this.context.shouldCompact()&&(console.log(m.yellow("\u{1F4E6} Compacting context...")),await this.context.compact())}t>=o&&console.log(m.yellow(`\u26A0\uFE0F Reached max iterations (${o})`))}async runWithPlanMode(e){console.log(m.blue("\u{1F4DD} Running in Plan Mode...")),this.context.addMessage({role:"user",content:`[PLANNING MODE] ${e}
|
|
69
69
|
|
|
70
|
-
Please analyze the task and create a detailed plan before executing anything. List each step with the files that will be modified.`});let t=await this.provider.chat(this.context.getMessagesForAPI(),void 0,this.config.model);console.log(
|
|
71
|
-
\u{1F4CB} Proposed Plan:`)),console.log(
|
|
70
|
+
Please analyze the task and create a detailed plan before executing anything. List each step with the files that will be modified.`});let t=await this.provider.chat(this.context.getMessagesForAPI(),void 0,this.config.model);console.log(m.cyan(`
|
|
71
|
+
\u{1F4CB} Proposed Plan:`)),console.log(m.white(t.content)),console.log(m.green(`
|
|
72
72
|
\u2705 Proceeding with execution...
|
|
73
|
-
`)),this.context.clear(),this.context.addMessage({role:"user",content:e}),await this.runDirect(e)}getContextInfo(){let e=this.context.getTokenUsage();return{tokens:`${e.total-e.available} / ${e.total}`,messages:this.context.getMessages().length}}async cleanup(){this.mcp.disconnect()}};import{readFile as
|
|
73
|
+
`)),this.context.clear(),this.context.addMessage({role:"user",content:e}),await this.runDirect(e)}getContextInfo(){let e=this.context.getTokenUsage();return{tokens:`${e.total-e.available} / ${e.total}`,messages:this.context.getMessages().length}}async cleanup(){this.mcp.disconnect()}};import{readFile as G,writeFile as b,access as N,mkdir as ne}from"fs/promises";import{join as g}from"path";import{homedir as re}from"os";var h=new se;h.name("cortex").description("The ultimate local AI coding agent - context-aware, memory-powered, MCP-enabled").version("5.0.0-beta.1").option("-p, --provider <name>","Provider to use: ollama, lmstudio, openrouter").option("-m, --model <name>","Model to use").option("-u, --url <url>","Provider URL").option("--plan-mode","Show plan before executing changes").option("--tui","Start in TUI mode (default when no command provided)").option("--no-tui","Disable TUI mode");async function _(){let i=[g(process.cwd(),".cortex","config.json"),g(re(),".cortex","config.json")];for(let e of i)try{let t=await G(e,"utf-8");return JSON.parse(t)}catch{}return{}}async function ie(){console.log(d.blue("Initializing Cortex project..."));let i=g(process.cwd(),".cortex"),e=g(i,"config.json"),t=g(i,"mcp.json"),o=g(process.cwd(),"CORTEX.md");try{await ne(i,{recursive:!0})}catch{}try{await N(e),console.log(d.yellow("Cortex already initialized in this project"));return}catch{}await b(e,JSON.stringify({provider:"ollama",model:"llama3.2"},null,2)),console.log(d.green("\u2705 Created .cortex/config.json"));try{await N(o)}catch{await b(o,`# Cortex Project Memory
|
|
74
74
|
|
|
75
75
|
## Project Overview
|
|
76
76
|
<!-- Fill in your project description -->
|
|
@@ -83,10 +83,10 @@ Please analyze the task and create a detailed plan before executing anything. Li
|
|
|
83
83
|
|
|
84
84
|
## Architecture Notes
|
|
85
85
|
<!-- Document important architectural decisions -->
|
|
86
|
-
`),console.log(
|
|
87
|
-
\u{1F389} Cortex initialized! Run "cortex" to start coding.`))}async function
|
|
88
|
-
\u{1F4CA} Session: ${l.messages} messages, ${l.tokens} tokens`))}catch(l){console.error(
|
|
89
|
-
\u274C Error: ${l instanceof Error?l.message:String(l)}`)),process.exit(1)}finally{await c.cleanup()}}async function
|
|
90
|
-
`));let i=await
|
|
91
|
-
\u{1F4E6} Available models:`));for(let s of o.slice(0,10))console.log(` - ${s}`);o.length>10&&console.log(
|
|
92
|
-
`));let e=
|
|
86
|
+
`),console.log(d.green("\u2705 Created CORTEX.md"))}await b(t,JSON.stringify({servers:{}},null,2)),console.log(d.green("\u2705 Created .cortex/mcp.json")),console.log(d.green(`
|
|
87
|
+
\u{1F389} Cortex initialized! Run "cortex" to start coding.`))}async function ae(i,e){let t=await _(),o=e.provider||t.provider||"ollama",s=e.model||t.model,r=e.url||t.url,n=e.planMode||t.planMode,a={provider:o,model:s,providerUrl:r,planMode:n},c=new T(a,process.cwd());try{await c.initialize(),await c.run(i);let l=c.getContextInfo();console.log(d.dim(`
|
|
88
|
+
\u{1F4CA} Session: ${l.messages} messages, ${l.tokens} tokens`))}catch(l){console.error(d.red(`
|
|
89
|
+
\u274C Error: ${l instanceof Error?l.message:String(l)}`)),process.exit(1)}finally{await c.cleanup()}}async function ce(){console.log(d.blue(`\u{1F50D} Checking provider status...
|
|
90
|
+
`));let i=await _(),e=i.provider||"ollama";try{let t=v({type:e,baseUrl:i.url});console.log(d.green(`\u2705 Provider: ${t.name}`));let o=await t.listModels();if(o.length>0){console.log(d.cyan(`
|
|
91
|
+
\u{1F4E6} Available models:`));for(let s of o.slice(0,10))console.log(` - ${s}`);o.length>10&&console.log(d.dim(` ... and ${o.length-10} more`))}else console.log(d.yellow("\u26A0\uFE0F No models found. Make sure your provider is running."))}catch(t){console.error(d.red(`\u274C Provider error: ${t instanceof Error?t.message:String(t)}`))}}async function le(i){console.log(d.blue(`\u2699\uFE0F Setting up Cortex...
|
|
92
|
+
`));let e=g(process.cwd(),".cortex","config.json"),t={};try{let s=await G(e,"utf-8");t=JSON.parse(s)}catch{}let o={provider:i.provider||t.provider||"ollama",model:i.model||t.model||"llama3.2",url:t.url||"http://localhost:11434"};await b(e,JSON.stringify(o,null,2)),console.log(d.green("\u2705 Configuration saved!")),console.log(d.dim(` Provider: ${o.provider}`)),console.log(d.dim(` Model: ${o.model}`))}async function de(i){let e=await _(),t=i.provider||e.provider||"ollama";try{let s=await v({type:t,baseUrl:e.url}).listModels();if(s.length===0){console.log(d.yellow("No models available"));return}console.log(d.cyan(`Available models on ${t}:`));for(let r of s)console.log(` ${r}`)}catch(o){console.error(d.red(`Error: ${o instanceof Error?o.message:String(o)}`))}}h.command("init").description("Initialize Cortex in the current project").action(ie);h.command("run [prompt...]").description("Run a coding task").option("-p, --provider <name>","Provider to use").option("-m, --model <name>","Model to use").option("-u, --url <url>","Provider URL").option("--plan-mode","Show plan before executing").action(async(i,e)=>{(!i||i.length===0)&&(console.log(d.yellow('Please provide a prompt. Usage: cortex run "your task"')),process.exit(1)),await ae(i.join(" "),e)});h.command("status").description("Check provider and model status").action(ce);h.command("setup").description("Configure Cortex settings").option("-p, --provider <name>","Provider name").option("-m, --model <name>","Default model").option("-f, --force","Overwrite existing config").action(le);h.command("models").description("List available models").option("-p, --provider <name>","Provider to query").action(de);h.command("chat").description("Start interactive chat session").option("-p, --provider <name>","Provider to use").option("-m, --model <name>","Model to use").action(async i=>{console.log(d.yellow("Interactive chat coming soon!"))});function f(i=0){console.log(),console.log(d.dim(i===0?"\u{1F44B} Goodbye!":"\u274C Cancelled.")),process.exit(i)}process.on("SIGINT",()=>f(0));process.on("SIGTERM",()=>f(0));process.on("uncaughtException",i=>{i.message?.includes("ExitPromptError")||i.message?.includes("User force closed")||i.message?.includes("prompt")?f(0):(console.error(d.red("Error:"),i.message),process.exit(1))});process.on("unhandledRejection",i=>{let e=String(i);(e.includes("ExitPromptError")||e.includes("User force closed")||e.includes("prompt"))&&f(0)});var J=process.argv.slice(2);async function me(){if(J.length===0||J.includes("--tui")){let i=await _(),e=i.provider||"ollama",t=i.model,o=g(__dirname,"..","bin","tui.js"),s=["--provider",e];t&&s.push("--model",t);let{spawn:r}=await import("child_process");r("node",[o,...s],{cwd:process.cwd(),stdio:"inherit",shell:!1}).on("close",a=>{f(a||0)})}else h.parse()}me();
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/tui/index.tsx
|
|
4
|
+
import React3 from "react";
|
|
5
|
+
import { render } from "ink";
|
|
6
|
+
|
|
7
|
+
// src/tui/App.tsx
|
|
8
|
+
import { useState as useState2 } from "react";
|
|
9
|
+
import { Box as Box5 } from "ink";
|
|
10
|
+
|
|
11
|
+
// src/tui/theme.ts
|
|
12
|
+
var colors = {
|
|
13
|
+
primary: "#00D9FF",
|
|
14
|
+
secondary: "#FF79C6",
|
|
15
|
+
accent: "#50FA7B",
|
|
16
|
+
error: "#FF5555",
|
|
17
|
+
warning: "#FFB86C",
|
|
18
|
+
success: "#50FA7B",
|
|
19
|
+
dim: "#6272A4",
|
|
20
|
+
bg: "#282A36",
|
|
21
|
+
bgDim: "#44475A",
|
|
22
|
+
fg: "#F8F8F2",
|
|
23
|
+
fgDim: "#BDBDBD"
|
|
24
|
+
};
|
|
25
|
+
var theme = {
|
|
26
|
+
colors,
|
|
27
|
+
border: {
|
|
28
|
+
color: colors.dim,
|
|
29
|
+
accent: colors.primary
|
|
30
|
+
},
|
|
31
|
+
spacing: {
|
|
32
|
+
xs: 1,
|
|
33
|
+
sm: 2,
|
|
34
|
+
md: 4,
|
|
35
|
+
lg: 8
|
|
36
|
+
},
|
|
37
|
+
font: {
|
|
38
|
+
mono: "monospace"
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// src/tui/components/Chat.tsx
|
|
43
|
+
import { Box, Text } from "ink";
|
|
44
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
45
|
+
var Chat = ({
|
|
46
|
+
messages,
|
|
47
|
+
isStreaming,
|
|
48
|
+
currentToolCall
|
|
49
|
+
}) => {
|
|
50
|
+
const renderMessage = (msg, idx) => {
|
|
51
|
+
const roleColors = {
|
|
52
|
+
user: theme.colors.primary,
|
|
53
|
+
assistant: theme.colors.secondary,
|
|
54
|
+
system: theme.colors.warning,
|
|
55
|
+
tool: theme.colors.accent
|
|
56
|
+
};
|
|
57
|
+
const roleLabels = {
|
|
58
|
+
user: "You",
|
|
59
|
+
assistant: "Cortex",
|
|
60
|
+
system: "System",
|
|
61
|
+
tool: msg.name || "Tool"
|
|
62
|
+
};
|
|
63
|
+
return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginY: 1, children: [
|
|
64
|
+
/* @__PURE__ */ jsx(Text, { bold: true, color: roleColors[msg.role], children: roleLabels[msg.role] }),
|
|
65
|
+
/* @__PURE__ */ jsx(Text, { children: msg.content }),
|
|
66
|
+
msg.tool_calls && msg.tool_calls.length > 0 && /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginTop: 1, children: msg.tool_calls.map((tc) => /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingLeft: 2, children: [
|
|
67
|
+
/* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
|
|
68
|
+
"\u2192 ",
|
|
69
|
+
tc.name,
|
|
70
|
+
"(",
|
|
71
|
+
JSON.stringify(tc.arguments),
|
|
72
|
+
")"
|
|
73
|
+
] }),
|
|
74
|
+
tc.status === "completed" && tc.result && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
|
|
75
|
+
"Result: ",
|
|
76
|
+
tc.result.slice(0, 200)
|
|
77
|
+
] })
|
|
78
|
+
] }, tc.id)) })
|
|
79
|
+
] }, msg.id);
|
|
80
|
+
};
|
|
81
|
+
return /* @__PURE__ */ jsx(Box, { flexDirection: "column", overflow: "hidden", children: messages.length === 0 ? /* @__PURE__ */ jsxs(
|
|
82
|
+
Box,
|
|
83
|
+
{
|
|
84
|
+
flexDirection: "column",
|
|
85
|
+
justifyContent: "center",
|
|
86
|
+
alignItems: "center",
|
|
87
|
+
flex: 1,
|
|
88
|
+
children: [
|
|
89
|
+
/* @__PURE__ */ jsx(Text, { bold: true, color: theme.colors.primary, children: "Cortex AI" }),
|
|
90
|
+
/* @__PURE__ */ jsx(Text, { dimColor: true, children: "Type your message below to start coding" }),
|
|
91
|
+
isStreaming && /* @__PURE__ */ jsx(Text, { color: theme.colors.accent, italic: true, children: "Thinking..." })
|
|
92
|
+
]
|
|
93
|
+
}
|
|
94
|
+
) : /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
|
|
95
|
+
messages.map((msg, idx) => renderMessage(msg, idx)),
|
|
96
|
+
isStreaming && /* @__PURE__ */ jsx(Text, { color: theme.colors.accent, italic: true, children: "\u258A" }),
|
|
97
|
+
currentToolCall && /* @__PURE__ */ jsx(
|
|
98
|
+
Box,
|
|
99
|
+
{
|
|
100
|
+
marginY: 1,
|
|
101
|
+
paddingX: 2,
|
|
102
|
+
borderStyle: "round",
|
|
103
|
+
borderColor: theme.colors.warning,
|
|
104
|
+
children: /* @__PURE__ */ jsxs(Text, { color: theme.colors.warning, children: [
|
|
105
|
+
"\u26A1 Running: ",
|
|
106
|
+
currentToolCall.name
|
|
107
|
+
] })
|
|
108
|
+
}
|
|
109
|
+
)
|
|
110
|
+
] }) });
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// src/tui/components/Input.tsx
|
|
114
|
+
import { useState } from "react";
|
|
115
|
+
import { Box as Box2, Text as Text2, useInput } from "ink";
|
|
116
|
+
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
117
|
+
var Input = ({
|
|
118
|
+
value,
|
|
119
|
+
onChange,
|
|
120
|
+
onSubmit,
|
|
121
|
+
disabled
|
|
122
|
+
}) => {
|
|
123
|
+
const [history, setHistory] = useState([]);
|
|
124
|
+
const [historyIndex, setHistoryIndex] = useState(-1);
|
|
125
|
+
useInput((input, key) => {
|
|
126
|
+
if (disabled) return;
|
|
127
|
+
if (key.return) {
|
|
128
|
+
if (value.trim()) {
|
|
129
|
+
setHistory((prev) => [value, ...prev.slice(0, 49)]);
|
|
130
|
+
setHistoryIndex(-1);
|
|
131
|
+
onSubmit(value);
|
|
132
|
+
}
|
|
133
|
+
} else if (key.upArrow) {
|
|
134
|
+
if (historyIndex < history.length - 1) {
|
|
135
|
+
const newIndex = historyIndex + 1;
|
|
136
|
+
setHistoryIndex(newIndex);
|
|
137
|
+
onChange(history[newIndex]);
|
|
138
|
+
}
|
|
139
|
+
} else if (key.downArrow) {
|
|
140
|
+
if (historyIndex > 0) {
|
|
141
|
+
const newIndex = historyIndex - 1;
|
|
142
|
+
setHistoryIndex(newIndex);
|
|
143
|
+
onChange(history[newIndex]);
|
|
144
|
+
} else if (historyIndex === 0) {
|
|
145
|
+
setHistoryIndex(-1);
|
|
146
|
+
onChange("");
|
|
147
|
+
}
|
|
148
|
+
} else if (key.delete || key.backspace) {
|
|
149
|
+
onChange(value.slice(0, -1));
|
|
150
|
+
} else if (input) {
|
|
151
|
+
onChange(value + input);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
return /* @__PURE__ */ jsxs2(
|
|
155
|
+
Box2,
|
|
156
|
+
{
|
|
157
|
+
flexDirection: "row",
|
|
158
|
+
alignItems: "center",
|
|
159
|
+
paddingX: 2,
|
|
160
|
+
paddingY: 1,
|
|
161
|
+
borderStyle: "single",
|
|
162
|
+
borderColor: theme.colors.dim,
|
|
163
|
+
children: [
|
|
164
|
+
/* @__PURE__ */ jsx2(Text2, { bold: true, color: theme.colors.primary, children: "\u276F" }),
|
|
165
|
+
/* @__PURE__ */ jsx2(Box2, { flex: 1, marginLeft: 1, children: /* @__PURE__ */ jsx2(Text2, { color: disabled ? theme.colors.dim : theme.colors.fg, children: disabled ? "Processing..." : value || "Type a message..." }) }),
|
|
166
|
+
/* @__PURE__ */ jsx2(Text2, { dimColor: true, children: " Enter | \u2191\u2193 | Ctrl+C " })
|
|
167
|
+
]
|
|
168
|
+
}
|
|
169
|
+
);
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// src/tui/components/StatusBar.tsx
|
|
173
|
+
import { Box as Box3, Text as Text3 } from "ink";
|
|
174
|
+
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
|
|
175
|
+
var StatusBar = ({
|
|
176
|
+
view,
|
|
177
|
+
onViewChange,
|
|
178
|
+
provider: provider2,
|
|
179
|
+
model: model2,
|
|
180
|
+
messages
|
|
181
|
+
}) => {
|
|
182
|
+
return /* @__PURE__ */ jsxs3(
|
|
183
|
+
Box3,
|
|
184
|
+
{
|
|
185
|
+
flexDirection: "row",
|
|
186
|
+
justifyContent: "space-between",
|
|
187
|
+
paddingX: 2,
|
|
188
|
+
paddingY: 1,
|
|
189
|
+
borderStyle: "single",
|
|
190
|
+
borderColor: theme.colors.dim,
|
|
191
|
+
children: [
|
|
192
|
+
/* @__PURE__ */ jsxs3(Box3, { flexDirection: "row", children: [
|
|
193
|
+
/* @__PURE__ */ jsx3(
|
|
194
|
+
Text3,
|
|
195
|
+
{
|
|
196
|
+
bold: true,
|
|
197
|
+
color: view === "chat" ? theme.colors.primary : theme.colors.dim,
|
|
198
|
+
onPress: () => onViewChange("chat"),
|
|
199
|
+
children: "[Chat]"
|
|
200
|
+
}
|
|
201
|
+
),
|
|
202
|
+
/* @__PURE__ */ jsx3(Text3, { color: theme.colors.dim, children: " | " }),
|
|
203
|
+
/* @__PURE__ */ jsx3(
|
|
204
|
+
Text3,
|
|
205
|
+
{
|
|
206
|
+
bold: true,
|
|
207
|
+
color: view === "sessions" ? theme.colors.primary : theme.colors.dim,
|
|
208
|
+
onPress: () => onViewChange("sessions"),
|
|
209
|
+
children: "[Sessions]"
|
|
210
|
+
}
|
|
211
|
+
),
|
|
212
|
+
/* @__PURE__ */ jsx3(Text3, { color: theme.colors.dim, children: " | " }),
|
|
213
|
+
/* @__PURE__ */ jsx3(
|
|
214
|
+
Text3,
|
|
215
|
+
{
|
|
216
|
+
bold: true,
|
|
217
|
+
color: view === "settings" ? theme.colors.primary : theme.colors.dim,
|
|
218
|
+
onPress: () => onViewChange("settings"),
|
|
219
|
+
children: "[Settings]"
|
|
220
|
+
}
|
|
221
|
+
)
|
|
222
|
+
] }),
|
|
223
|
+
/* @__PURE__ */ jsxs3(Box3, { flexDirection: "row", children: [
|
|
224
|
+
/* @__PURE__ */ jsxs3(Text3, { dimColor: true, children: [
|
|
225
|
+
provider2,
|
|
226
|
+
"/",
|
|
227
|
+
model2
|
|
228
|
+
] }),
|
|
229
|
+
/* @__PURE__ */ jsx3(Text3, { color: theme.colors.dim, children: " | " }),
|
|
230
|
+
/* @__PURE__ */ jsxs3(Text3, { dimColor: true, children: [
|
|
231
|
+
"Messages: ",
|
|
232
|
+
messages
|
|
233
|
+
] })
|
|
234
|
+
] })
|
|
235
|
+
]
|
|
236
|
+
}
|
|
237
|
+
);
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// src/tui/components/Sidebar.tsx
|
|
241
|
+
import { Box as Box4, Text as Text4 } from "ink";
|
|
242
|
+
import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
|
|
243
|
+
var Sidebar = ({
|
|
244
|
+
sessions,
|
|
245
|
+
activeSessionId,
|
|
246
|
+
onSelectSession
|
|
247
|
+
}) => {
|
|
248
|
+
const formatDate = (timestamp) => {
|
|
249
|
+
const date = new Date(timestamp);
|
|
250
|
+
return date.toLocaleDateString() + " " + date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
|
251
|
+
};
|
|
252
|
+
return /* @__PURE__ */ jsxs4(
|
|
253
|
+
Box4,
|
|
254
|
+
{
|
|
255
|
+
width: 30,
|
|
256
|
+
flexDirection: "column",
|
|
257
|
+
borderStyle: "single",
|
|
258
|
+
borderColor: theme.colors.dim,
|
|
259
|
+
marginRight: 1,
|
|
260
|
+
children: [
|
|
261
|
+
/* @__PURE__ */ jsx4(
|
|
262
|
+
Box4,
|
|
263
|
+
{
|
|
264
|
+
paddingX: 2,
|
|
265
|
+
paddingY: 1,
|
|
266
|
+
borderStyle: "bold",
|
|
267
|
+
borderColor: theme.colors.primary,
|
|
268
|
+
children: /* @__PURE__ */ jsx4(Text4, { bold: true, color: theme.colors.primary, children: "Sessions" })
|
|
269
|
+
}
|
|
270
|
+
),
|
|
271
|
+
/* @__PURE__ */ jsx4(Box4, { flexDirection: "column", flex: 1, children: sessions.length === 0 ? /* @__PURE__ */ jsx4(Box4, { justifyContent: "center", alignItems: "center", flex: 1, children: /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: "No sessions yet" }) }) : sessions.map((session) => /* @__PURE__ */ jsxs4(
|
|
272
|
+
Box4,
|
|
273
|
+
{
|
|
274
|
+
flexDirection: "column",
|
|
275
|
+
paddingX: 2,
|
|
276
|
+
paddingY: 1,
|
|
277
|
+
borderStyle: "none",
|
|
278
|
+
onPress: () => onSelectSession(session.id),
|
|
279
|
+
children: [
|
|
280
|
+
/* @__PURE__ */ jsx4(
|
|
281
|
+
Text4,
|
|
282
|
+
{
|
|
283
|
+
bold: true,
|
|
284
|
+
color: session.id === activeSessionId ? theme.colors.primary : theme.colors.fg,
|
|
285
|
+
children: session.name
|
|
286
|
+
}
|
|
287
|
+
),
|
|
288
|
+
/* @__PURE__ */ jsx4(Text4, { dimColor: true, font: "monospace", children: formatDate(session.updatedAt) })
|
|
289
|
+
]
|
|
290
|
+
},
|
|
291
|
+
session.id
|
|
292
|
+
)) })
|
|
293
|
+
]
|
|
294
|
+
}
|
|
295
|
+
);
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// src/tui/App.tsx
|
|
299
|
+
import { jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
|
|
300
|
+
var App = ({ cwd: cwd2, provider: provider2, model: model2 }) => {
|
|
301
|
+
const [messages, setMessages] = useState2([]);
|
|
302
|
+
const [input, setInput] = useState2("");
|
|
303
|
+
const [isStreaming, setIsStreaming] = useState2(false);
|
|
304
|
+
const [currentToolCall, setCurrentToolCall] = useState2(null);
|
|
305
|
+
const [sessions, setSessions] = useState2([]);
|
|
306
|
+
const [activeView, setActiveView] = useState2("chat");
|
|
307
|
+
const [sessionId, setSessionId] = useState2(null);
|
|
308
|
+
const handleSubmit = async (value) => {
|
|
309
|
+
if (!value.trim() || isStreaming) return;
|
|
310
|
+
const userMessage = {
|
|
311
|
+
id: Date.now().toString(),
|
|
312
|
+
role: "user",
|
|
313
|
+
content: value,
|
|
314
|
+
timestamp: Date.now()
|
|
315
|
+
};
|
|
316
|
+
setMessages((prev) => [...prev, userMessage]);
|
|
317
|
+
setInput("");
|
|
318
|
+
setIsStreaming(true);
|
|
319
|
+
setTimeout(() => {
|
|
320
|
+
const assistantMessage = {
|
|
321
|
+
id: (Date.now() + 1).toString(),
|
|
322
|
+
role: "assistant",
|
|
323
|
+
content: "Thinking...",
|
|
324
|
+
timestamp: Date.now()
|
|
325
|
+
};
|
|
326
|
+
setMessages((prev) => [...prev, assistantMessage]);
|
|
327
|
+
setIsStreaming(false);
|
|
328
|
+
}, 500);
|
|
329
|
+
};
|
|
330
|
+
const handleToolCall = (toolCall) => {
|
|
331
|
+
setCurrentToolCall(toolCall);
|
|
332
|
+
};
|
|
333
|
+
const handleToolComplete = (toolCallId, result) => {
|
|
334
|
+
setCurrentToolCall(null);
|
|
335
|
+
setMessages(
|
|
336
|
+
(prev) => prev.map(
|
|
337
|
+
(msg) => msg.tool_calls?.map(
|
|
338
|
+
(tc) => tc.id === toolCallId ? { ...tc, status: "completed", result } : tc
|
|
339
|
+
)
|
|
340
|
+
)
|
|
341
|
+
);
|
|
342
|
+
};
|
|
343
|
+
return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", height: 100, children: [
|
|
344
|
+
/* @__PURE__ */ jsx5(Box5, { flexDirection: "column", flex: 1, overflow: "hidden", children: /* @__PURE__ */ jsxs5(Box5, { flexDirection: "row", flex: 1, children: [
|
|
345
|
+
activeView === "sessions" && /* @__PURE__ */ jsx5(
|
|
346
|
+
Sidebar,
|
|
347
|
+
{
|
|
348
|
+
sessions,
|
|
349
|
+
activeSessionId: sessionId,
|
|
350
|
+
onSelectSession: (id) => setSessionId(id)
|
|
351
|
+
}
|
|
352
|
+
),
|
|
353
|
+
/* @__PURE__ */ jsxs5(
|
|
354
|
+
Box5,
|
|
355
|
+
{
|
|
356
|
+
flexDirection: "column",
|
|
357
|
+
flex: 1,
|
|
358
|
+
borderStyle: "round",
|
|
359
|
+
borderColor: theme.colors.dim,
|
|
360
|
+
children: [
|
|
361
|
+
/* @__PURE__ */ jsx5(
|
|
362
|
+
Box5,
|
|
363
|
+
{
|
|
364
|
+
paddingX: 1,
|
|
365
|
+
borderStyle: "bold",
|
|
366
|
+
borderColor: theme.colors.primary,
|
|
367
|
+
flex: 1,
|
|
368
|
+
overflow: "hidden",
|
|
369
|
+
children: /* @__PURE__ */ jsx5(
|
|
370
|
+
Chat,
|
|
371
|
+
{
|
|
372
|
+
messages,
|
|
373
|
+
isStreaming,
|
|
374
|
+
currentToolCall
|
|
375
|
+
}
|
|
376
|
+
)
|
|
377
|
+
}
|
|
378
|
+
),
|
|
379
|
+
/* @__PURE__ */ jsx5(
|
|
380
|
+
Input,
|
|
381
|
+
{
|
|
382
|
+
value: input,
|
|
383
|
+
onChange: setInput,
|
|
384
|
+
onSubmit: handleSubmit,
|
|
385
|
+
disabled: isStreaming
|
|
386
|
+
}
|
|
387
|
+
)
|
|
388
|
+
]
|
|
389
|
+
}
|
|
390
|
+
)
|
|
391
|
+
] }) }),
|
|
392
|
+
/* @__PURE__ */ jsx5(
|
|
393
|
+
StatusBar,
|
|
394
|
+
{
|
|
395
|
+
view: activeView,
|
|
396
|
+
onViewChange: setActiveView,
|
|
397
|
+
provider: provider2,
|
|
398
|
+
model: model2 || "default",
|
|
399
|
+
messages: messages.length
|
|
400
|
+
}
|
|
401
|
+
)
|
|
402
|
+
] });
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
// src/tui/index.tsx
|
|
406
|
+
var args = process.argv.slice(2);
|
|
407
|
+
var cwd = process.cwd();
|
|
408
|
+
var isTui = args.length === 0 || args.includes("--tui") || args.some((a) => !a.startsWith("--"));
|
|
409
|
+
var provider = "ollama";
|
|
410
|
+
var model = "llama3.2";
|
|
411
|
+
for (let i = 0; i < args.length; i++) {
|
|
412
|
+
if (args[i] === "--provider" && args[i + 1]) {
|
|
413
|
+
provider = args[i + 1];
|
|
414
|
+
i++;
|
|
415
|
+
} else if (args[i] === "--model" && args[i + 1]) {
|
|
416
|
+
model = args[i + 1];
|
|
417
|
+
i++;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (isTui) {
|
|
421
|
+
const { waitUntilExit } = render(
|
|
422
|
+
React3.createElement(App, { cwd, provider, model })
|
|
423
|
+
);
|
|
424
|
+
waitUntilExit().then(() => {
|
|
425
|
+
console.log("\nGoodbye!");
|
|
426
|
+
process.exit(0);
|
|
427
|
+
});
|
|
428
|
+
} else {
|
|
429
|
+
console.log("Use 'cortex' without arguments to start TUI mode");
|
|
430
|
+
process.exit(1);
|
|
431
|
+
}
|