command-code 0.0.4-alpha.3 → 0.0.4-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +2 -2
  2. package/package.json +3 -3
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{Command as e}from"commander";import*as t from"fs/promises";import n,{mkdir as r,writeFile as o}from"fs/promises";import*as s from"path";import i,{relative as a,dirname as c,join as l,isAbsolute as u,resolve as d}from"path";import*as m from"os";import p,{tmpdir as h}from"os";import{execSync as g,spawn as f}from"child_process";import{z as y}from"zod";import w from"crypto";import b from"readline/promises";import{Static as E,Box as x,Text as C,useInput as v,render as S,useApp as k,useStdout as T}from"ink";import P,{useState as A,useEffect as I,useRef as D,useCallback as $,useMemo as F}from"react";import R from"@anthropic-ai/sdk";import*as M from"fs";import j,{readFileSync as O,promises as U,constants as _,existsSync as N,readdirSync as L,statSync as B}from"fs";import{minimatch as z}from"minimatch";import{glob as W}from"glob";import q from"@sindresorhus/slugify";import{MessageStream as G}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import J from"@crosscopy/clipboard";import V from"ink-gradient";import H,{mainSymbols as Y}from"figures";import{setOptions as Q,parse as K}from"marked";import Z from"marked-terminal";import*as X from"diff";import ee from"ink-text-input";import te from"sharp";import{EventEmitter as ne}from"events";import re from"ink-select-input";import{fileURLToPath as oe,URL as se}from"url";import{promisify as ie}from"util";import*as ae from"http";import*as ce from"https";import le from"registry-url";import ue from"registry-auth-token";import de from"dedent";import me from"chalk";import pe from"log-symbols";var he=Object.defineProperty,__name=(e,t)=>he(e,"name",{value:t,configurable:!0}),ge=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ℹ️ ${e}`)}success(e){console.log(`[${this.prefix}] ✅ ${e}`)}error(e){console.error(`[${this.prefix}] ❌ ${e}`)}warn(e){console.warn(`[${this.prefix}] ⚠️ ${e}`)}debug(e){process.env.DEBUG&&console.log(`[${this.prefix}] 🐛 ${e}`)}};function formatDate(e=new Date){return e.toISOString().split("T")[0]}function parseJSON(e){try{return JSON.parse(e)}catch{return null}}__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON");var fe="/alpha/generate",ye={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",DATA:"/alpha/share/data",APPEND:"/alpha/share/append",CONNECT:"/alpha/share/connect"},we=new ge("Config"),be=s.join(m.homedir(),".command-code-config.json");async function loadConfig(){try{return parseJSON(await t.readFile(be,"utf-8"))||{}}catch{return{}}}async function saveConfig(e){await t.writeFile(be,JSON.stringify(e,null,2))}__name(loadConfig,"loadConfig"),__name(saveConfig,"saveConfig");var Ee,xe,Ce=new e("config").description("Manage CLI configuration").addCommand(new e("get").description("Get a configuration value").argument("<key>","Configuration key").action(async e=>{const t=(await loadConfig())[e];void 0!==t?we.info(`${e}: ${JSON.stringify(t)}`):we.warn(`Key "${e}" not found in configuration`)})).addCommand(new e("set").description("Set a configuration value").argument("<key>","Configuration key").argument("<value>","Configuration value").action(async(e,t)=>{const n=await loadConfig();let r=t;"true"===t?r=!0:"false"===t?r=!1:isNaN(Number(t))||(r=Number(t)),n[e]=r,await saveConfig(n),we.success(`Set ${e} = ${JSON.stringify(r)}`)})).addCommand(new e("list").description("List all configuration values").action(async()=>{const e=await loadConfig();0===Object.keys(e).length?we.info("No configuration values set"):(we.info("Current configuration:"),Object.entries(e).forEach(([e,t])=>{console.log(` ${e}: ${JSON.stringify(t)}`)}))})).addCommand(new e("reset").description("Reset all configuration").action(async()=>{await saveConfig({}),we.success("Configuration reset successfully")})),ve=new ge("Info"),Se=new e("info").description("Display system information").option("-v, --verbose","Show verbose output").action(e=>{if(ve.info("System Information:"),console.log("-------------------"),console.log(`📅 Date: ${formatDate()}`),console.log(`💻 Platform: ${m.platform()}`),console.log(`🏗️ Architecture: ${m.arch()}`),console.log(`🧮 CPUs: ${m.cpus().length}`),console.log(`💾 Memory: ${Math.round(m.totalmem()/1024/1024/1024)} GB`),console.log(`📁 Home Directory: ${m.homedir()}`),e.verbose){console.log("\nDetailed CPU Information:"),m.cpus().forEach((e,t)=>{console.log(` CPU ${t}: ${e.model} @ ${e.speed} MHz`)}),console.log("\nNetwork Interfaces:");const e=m.networkInterfaces();Object.keys(e).forEach(t=>{const n=e[t];n&&n.forEach(e=>{"IPv4"!==e.family||e.internal||console.log(` ${t}: ${e.address}`)})})}ve.success("Information displayed successfully!")});async function loginAction(){try{console.log("🔐 Starting Anthropic OAuth login…\n");const{url:e,verifier:t,state:n}=xe.createAuthorizationUrl();console.log("Go to:",e),console.log("");try{"darwin"===process.platform?g(`open "${e}"`,{stdio:"ignore"}):"win32"===process.platform?g(`start "${e}"`,{stdio:"ignore"}):g(`xdg-open "${e}"`,{stdio:"ignore"}),console.log("✅ Browser opened automatically")}catch{console.log("ℹ️ Please copy and paste the URL above into your browser")}console.log("");const r=b.createInterface({input:process.stdin,output:process.stdout}),o=await r.question("After authorizing, paste the authorization code here: ");r.close(),o.trim()||(console.log("❌ No authorization code provided"),process.exit(1));const s=o.split("#")[0].trim();console.log("\n🔄 Exchanging code for tokens…"),await xe.exchangeCodeForTokens(s,t,n),console.log("✅ Login successful!"),console.log("OAuth tokens saved to ~/.command-code/auth.json")}catch(e){console.error("❌ Login failed:",e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function logoutAction(){try{if(console.log("🔄 Removing authentication…"),!await Ee.get("anthropic"))return void console.log("ℹ️ Not currently authenticated");await Ee.remove("anthropic"),console.log("✅ Logged out successfully")}catch(e){console.error("❌ Logout failed:",e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function statusAction(){try{const e=await Ee.get("anthropic");if(!e)return console.log("⚠️ Not authenticated"),void console.log("Run 'cmd auth login' to authenticate with Anthropic");if(console.log("✅ Authenticated with Anthropic"),console.log("Type:","oauth"===e.type?"OAuth (Claude Pro/Max)":"API Key"),"oauth"===e.type){const t=e.expires<Date.now(),n=new Date(e.expires).toLocaleString();t?console.log("🔄 Token expired:",n,"(will auto-refresh on next use)"):console.log("✅ Token expires:",n)}}catch(e){console.error("❌ Status check failed:",e instanceof Error?e.message:"Unknown error"),process.exit(1)}}(e=>{e.OAuth=y.object({type:y.literal("oauth"),refresh:y.string(),access:y.string(),expires:y.number()}),e.ApiKey=y.object({type:y.literal("api"),key:y.string()}),e.Info=y.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const t=__name(()=>i.join(p.homedir(),".command-code"),"getAuthDir"),r=__name(()=>i.join(t(),"auth.json"),"getAuthFile");async function get(e){try{const t=await n.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,o){const s=t(),i=r();await n.mkdir(s,{recursive:!0});let a={};try{const e=await n.readFile(i,"utf-8");a=JSON.parse(e)}catch{}a[e]=o,await n.writeFile(i,JSON.stringify(a,null,2)),await n.chmod(i,384)}async function remove(e){const t=r();try{const r=await n.readFile(t,"utf-8"),o=JSON.parse(r);delete o[e],0===Object.keys(o).length?await n.unlink(t):(await n.writeFile(t,JSON.stringify(o,null,2)),await n.chmod(t,384))}catch{}}async function list(){try{const e=await n.readFile(r(),"utf-8");return JSON.parse(e)}catch{return{}}}e.get=get,__name(get,"get"),e.set=set,__name(set,"set"),e.remove=remove,__name(remove,"remove"),e.list=list,__name(list,"list")})(Ee||(Ee={})),(e=>{const t="9d1c250a-e61b-44d9-88ed-5944d1962f5e",n="https://console.anthropic.com/v1/oauth/token",r="https://console.anthropic.com/oauth/code/callback";function generateCodeVerifier(){return w.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return w.createHash("sha256").update(e).digest("base64url")}function generateState(){return w.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),o=generateState();return{url:`https://claude.ai/oauth/authorize?${new URLSearchParams({code:"true",client_id:t,response_type:"code",redirect_uri:r,scope:"org:create_api_key user:profile user:inference",code_challenge:n,code_challenge_method:"S256",state:o}).toString()}`,verifier:e,state:o}}async function exchangeCodeForTokens(e,o,s){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:s})});if(!i.ok){const e=await i.text();throw new Error(`Token exchange failed: ${e}`)}const a=await i.json();await Ee.set("anthropic",{type:"oauth",refresh:a.refresh_token,access:a.access_token,expires:Date.now()+1e3*a.expires_in})}async function refreshAccessToken(){const e=await Ee.get("anthropic");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return e.access;try{const r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t,refresh_token:e.refresh})});if(!r.ok)return void await Ee.remove("anthropic");const o=await r.json();return await Ee.set("anthropic",{type:"oauth",refresh:o.refresh_token,access:o.access_token,expires:Date.now()+1e3*o.expires_in}),o.access_token}catch(e){return void await Ee.remove("anthropic")}}}async function getValidAccessToken(){const e=await Ee.get("anthropic");if(e)return"api"===e.type?e.key:"oauth"===e.type?await refreshAccessToken():void 0}__name(generateCodeVerifier,"generateCodeVerifier"),__name(generateCodeChallenge,"generateCodeChallenge"),__name(generateState,"generateState"),e.createAuthorizationUrl=createAuthorizationUrl,__name(createAuthorizationUrl,"createAuthorizationUrl"),e.exchangeCodeForTokens=exchangeCodeForTokens,__name(exchangeCodeForTokens,"exchangeCodeForTokens"),e.refreshAccessToken=refreshAccessToken,__name(refreshAccessToken,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken,__name(getValidAccessToken,"getValidAccessToken")})(xe||(xe={})),__name(loginAction,"loginAction"),__name(logoutAction,"logoutAction"),__name(statusAction,"statusAction");var ke=new e("auth").description("Manage authentication with Anthropic");ke.command("login").description("Login with Claude Pro/Max subscription via OAuth").action(loginAction),ke.command("logout").description("Remove stored authentication").action(logoutAction),ke.command("status").description("Show authentication status").action(statusAction);var Te=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{const s=f("/bin/bash",["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"]});let i="",a="",c=null;n>0&&(c=setTimeout(()=>{s.kill("SIGTERM"),t({stdout:i,stderr:a+(a?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),s.stdout?.on("data",e=>{i+=e.toString()}),s.stderr?.on("data",e=>{a+=e.toString()}),s.on("close",n=>{c&&clearTimeout(c),t({stdout:i.trim(),stderr:a.trim(),exitCode:n??0,command:e})}),s.on("error",n=>{c&&clearTimeout(c),t({stdout:i,stderr:a+`\n[Error: ${n.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),Pe=__name(e=>{let t="";return e.stdout&&(t+=e.stdout),e.stderr&&(t&&(t+="\n"),t+=e.stderr),0===e.exitCode||e.stderr||(t&&(t+="\n"),t+=`[Process exited with code ${e.exitCode}]`),t||"(No output)"},"formatBashOutput"),Ae=y.object({id:y.string(),timestamp:y.number(),type:y.literal("image"),source:y.object({type:y.enum(["base64","url"]),media_type:y.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:y.string()})}),Ie=y.object({id:y.string(),timestamp:y.number(),input:y.string(),output:y.string().optional(),metadata:y.record(y.string(),y.any()).optional(),images:y.array(Ae).optional().default([])}),De=Ie.extend({role:y.literal("user")}),$e=Ie.extend({role:y.literal("assistant")}),Fe=Ie.extend({role:y.literal("tool"),name:y.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),Re=Ie.extend({role:y.literal("bash"),command:y.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),Me=Ie.extend({role:y.literal("system")}),je=y.discriminatedUnion("role",[De,$e,Fe,Re,Me]),Oe=__name((e,t)=>je.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),Ue=__name(e=>je.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),_e=__name((e,t,n)=>je.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Ne=__name(e=>je.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),Le=__name(e=>je.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Be=__name((e,t)=>{const n={...e,output:t};return je.parse(n)},"updateEntryWithOutput"),ze=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),We=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),qe=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),Ge=["Thinking…","Yapping…","Yawning…","Brewing…","Contemplating…","Conjuring…","Pondering…","Mixing…","Stirring…","Channeling…","Sculpting…","Crystallizing…","Spinning…","Tuning…","Sparking…","Revving…","Cruising…","Exploring…","Blazing…","Climbing…","Diving…","Surfing…","Riding…","Dancing…","Juggling…","Performing…","Casting…","Cooking…","Baking…","Seasoning…","Garnishing…","Vibing…","Chilling…","Grooving…","Jamming…","Swaying…","Bouncing…","Flowing…","Gliding…","Floating…","Drifting…","Wandering…","Meandering…","Strolling…","Skipping…","Hopping…","Leaping…","Soaring…","Glowing…","Shimmering…","Twinkling…","Flickering…","Pulsing…","Humming…","Buzzing…","Whirring…","Purring…","Chirping…","Whistling…","Giggling…","Snickering…","Chuckling…","Grinning…","Smirking…","Winking…","Nodding…","Stretching…","Flexing…","Wiggling…","Swirling…","Twirling…","Spiraling…","Weaving…","Bobbing…","Rocking…","Swinging…","Swooshing…","Zipping…","Zooming…","Whizzing…","Zapping…","Popping…","Snapping…","Crackling…","Sizzling…","Bubbling…","Fizzing…"],Je=__name(()=>Ge[Math.floor(Math.random()*Ge.length)],"getRandomLLMStatus"),Ve=__name(e=>{switch(e){case"read_file":return"Read";case"edit_file":return"Edit";case"write_file":return"Write";case"read_directory":return"List";case"read_multiple_files":return"Read Multiple";case"grep":return"Search";case"shell_command":return"Shell";case"todo_write":return"Todos";case"think":return"Thinking…";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),He=__name((e,t)=>{try{switch(e){case"read_file":case"write_file":return t.absolutePath||t.file_path||t.path||"file";case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path||"file";case"read_directory":return t.path||"directory";case"grep":return`"${t.pattern}" in ${t.path||"files"}`;case"shell_command":return t.command&&t.args&&t.args.length>0?`${t.command} ${t.args.join(" ")}`:t.command||"";case"todo_write":return`${t.todos?t.todos.length:0} items`;case"think":return t.content||"planning";case"read_multiple_files":const e=t.include||[];return Array.isArray(e)?e.join(", "):"multiple files";default:return JSON.stringify(t||{})}}catch{return"parameters"}},"getToolInputContent"),Ye=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput"),Qe=__name(()=>{const[e,t]=A({isExecuting:!1,currentCommand:null});return{executeBash:$(async(e,n)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Te(e,{timeout:3e4,cwd:process.cwd()}),r=Pe(t);n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const o=n[t];if("bash"===o.role&&"command"in o&&o.command===e){n[t]=Be(o,r);break}}return n})}catch(t){const r=t instanceof Error?t.message:"Unknown error occurred";n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const o=n[t];if("bash"===o.role&&"command"in o&&o.command===e){n[t]=Be(o,`Error: ${r}`);break}}return n})}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution"),Ke=new ge("AnthropicClient"),Ze=class{static{__name(this,"AnthropicClient")}static instance=null;constructor(){}static async initialize(){if(this.instance)return this.instance;const e=await xe.getValidAccessToken();if(e)try{return this.instance=new R({authToken:e,defaultHeaders:{"anthropic-beta":"oauth-2025-04-20"}}),process.env.DEBUG&&Ke.debug("Anthropic client initialized with OAuth"),this.instance}catch(e){throw Ke.error("Failed to initialize Anthropic client with OAuth"),e}const t=process.env.ANTHROPIC_API_KEY;if(!t)throw Ke.error("No authentication found"),Ke.info("Please either:"),Ke.info(' 1. Run "cmd auth login" to authenticate with Claude Pro/Max'),Ke.info(" 2. Or set ANTHROPIC_API_KEY environment variable"),new Error('No authentication found. Use "cmd auth login" or set ANTHROPIC_API_KEY');try{return this.instance=new R({apiKey:t}),process.env.DEBUG&&Ke.debug("Anthropic client initialized with API key"),this.instance}catch(e){throw Ke.error("Failed to initialize Anthropic client with API key"),e}}static async getClient(){return this.instance?this.instance:await this.initialize()}static async isConfigured(){return!(!await xe.getValidAccessToken()&&!process.env.ANTHROPIC_API_KEY)}static reset(){this.instance=null,Ke.debug("Anthropic client reset")}};function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var Xe=y.object({absolutePath:y.string().describe("The absolute path to the file to read"),offset:y.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:y.number().optional().describe("Optional number of lines to read")});y.object({content:y.union([y.string(),y.instanceof(Buffer)]),contentType:y.enum(["text","binary"]),fileType:y.string(),size:y.number(),linesRead:y.number().optional()});var et=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};async function readFileContent(e){const{absolutePath:n,offset:r,limit:o}=e;if(!s.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new et("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const i=s.normalize(n);try{await t.access(i,M.constants.F_OK|M.constants.R_OK)}catch{throw new et(`File not found or not readable: ${i}`,"FILE_ACCESS_ERROR")}if(!(await t.stat(i)).isFile())throw new et("Path does not point to a file","NOT_A_FILE");const a=getFileType(i),c=isBinaryFile(a);if(void 0!==r&&void 0===o||void 0===r&&void 0!==o)throw new et("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new et("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new et("Limit must be > 0","INVALID_LIMIT");try{if(c){const e=await t.readFile(i);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==r&&void 0!==o){const e=await readTextFileLines(i,r,o);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await t.readFile(i,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof et)throw e;throw new et(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var tt={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".pdf":"application/pdf",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf"};function getFileType(e){const t=s.extname(e).toLowerCase();return{".txt":"text",".md":"markdown",".csv":"csv",".log":"log",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".env":"env",".js":"javascript",".ts":"typescript",".jsx":"jsx",".tsx":"tsx",".py":"python",".java":"java",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c-header",".hpp":"cpp-header",".cs":"csharp",".go":"go",".rb":"ruby",".php":"php",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".clj":"clojure",".elm":"elm",".erl":"erlang",".ex":"elixir",".exs":"elixir",".hs":"haskell",".lua":"lua",".pl":"perl",".r":"r",".dart":"dart",".f":"fortran",".f90":"fortran",".groovy":"groovy",".jl":"julia",".m":"matlab",".sh":"shell",".bash":"bash",".zsh":"zsh",".ps1":"powershell",".sql":"sql",".vue":"vue",".svelte":"svelte",".astro":"astro",".component.ts":"angular",".module.ts":"angular",".service.ts":"angular",".razor":"razor",".cshtml":"razor",".erb":"ruby-template",".mustache":"mustache",".handlebars":"handlebars",".hbs":"handlebars",".ejs":"ejs",".pug":"pug",".liquid":"liquid",".twig":"twig",...tt}[t]||"unknown"}function isBinaryFile(e){return Object.values(tt).includes(e)}async function readTextFileLines(e,n,r){const o=(await t.readFile(e,"utf8")).split(/\r?\n/),s=n,i=Math.min(s+r,o.length),a=o.slice(s,i);return{content:a.join("\n"),linesRead:a.length}}async function processFileReferences(e){const t=[];let n=e;const r=[...e.matchAll(/@([^\s@]+)/g)];for(const e of r){const r=e[0],o=e[1];try{const e=s.isAbsolute(o)?o:s.resolve(process.cwd(),o),i=await readFileContent({absolutePath:e});if("binary"===i.contentType)continue;const a=String(i.content),c=s.relative(process.cwd(),e);t.push({token:r,resolvedPath:e,content:a});const l=`{${c}: ${a}}`;n=n.replace(r,l)}catch(e){continue}}return{displayContent:e,processedContent:n,fileReferences:t}}function reconstructContent(e,t){let n=e;for(const e of t){const t=`{${s.relative(process.cwd(),e.resolvedPath)}: ${e.content}}`;n=n.replace(e.token,t)}return n}function formatOutput(e){const t=[];if(void 0!==e.linesRead)t.push(`Read ${e.linesRead} lines`);else if("binary"===e.contentType)t.push(`Binary file: ${e.size} bytes`);else{const n=e.content?String(e.content).split("\n").length:0;t.push(`Read ${n} lines`)}return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),__name(formatOutput,"formatOutput");var nt={name:"read_file",description:"Reads the contents of a file from the local filesystem, handling both text and binary files appropriately. \nThis tool automatically detects the file type based on extension and processes it accordingly - text files are returned as readable strings while binary files return metadata about the file type and size. \nFor large text files, you can optionally read specific line ranges using the offset and limit parameters to avoid loading the entire file into memory. \nThe tool validates that the provided path is absolute and that the file exists and is readable before attempting to read it. \nIt should be used when you need to examine file contents, verify file existence, or extract specific portions of text files for analysis or processing.",input_schema:{type:"object",properties:{absolutePath:{type:"string",description:'The absolute path to the file to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). Relative paths like "./file.txt" or "../file.txt" are not accepted. The file must exist and be readable by the current process.'},offset:{type:"number",description:"The line number to start reading from (0-based index, where 0 is the first line). This parameter must be used together with the limit parameter for reading specific line ranges. Cannot be negative. Use this when you need to read a specific section of a large file without loading the entire content."},limit:{type:"number",description:"The maximum number of lines to read starting from the offset. Must be a positive integer and used together with the offset parameter. This helps manage memory usage when dealing with large files by reading only the necessary portion."}},required:["absolutePath"]},execute:__name(async e=>{try{const t=Xe.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`❌ Error: ${e.message}`:"❌ Error: Unknown error occurred while reading file"}},"execute")},rt=y.object({filePath:y.string().describe("The absolute path to the file to edit"),oldValue:y.string().describe("The text to replace"),newValue:y.string().describe("The new text to insert"),replacementCount:y.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:y.boolean().optional().describe("Whether to replace all occurrences (default: false)")});function createFileEditError(e,t){const n=new Error(e);return n.name="FileEditError",n.code=t,n}async function editFile(e){const{filePath:t,oldValue:n,newValue:r,replaceAll:o=!1,replacementCount:i=1}=e;if(!t)throw createFileEditError("filePath is required","INVALID_PATH");if(!s.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!n)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==r)throw createFileEditError("newValue is required","INVALID_INPUT");if(!o&&i<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await U.access(t,_.F_OK|_.R_OK|_.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${t}`,"FILE_ACCESS_ERROR")}let a;try{const e=await readFileContent({absolutePath:t});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");a=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const c=(a.match(new RegExp(escapeRegExp(n),"g"))||[]).length;if(0===c)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let l,u;if(o)l=c;else if(l=i,l>c)throw createFileEditError(`Expected ${l} replacements, but only found ${c} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||l===c)u=a.split(n).join(r),d=c;else{u=a;for(let e=0;e<l;e++){const e=u.indexOf(n);-1!==e&&(u=u.substring(0,e)+r+u.substring(e+n.length),d++)}}if(0===d)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await U.writeFile(t,u,"utf-8"),console.log(`Successfully made ${d} replacement${1!==d?"s":""} in ${t}\n`),{path:t,replacementsCount:d,oldContent:a,newContent:u}}catch(e){throw createFileEditError(`Failed to write file: ${e instanceof Error?e.message:"Unknown error"}`,"WRITE_ERROR")}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function formatOutput2(e){const t=1!==e.replacementsCount?"s":"",n=`Edited ${e.path} (${e.replacementsCount} replacement${t})`;return e.newContent.length<500?`${n}\n\n${e.newContent}`:n}y.object({path:y.string(),replacementsCount:y.number(),oldContent:y.string(),newContent:y.string()}),y.object({name:y.string(),message:y.string(),code:y.string().optional()}),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),__name(formatOutput2,"formatOutput");var ot={name:"edit_file",description:"Performs precise text replacements in files by finding and replacing exact string matches, similar to a str_replace operation.\nThis tool is designed for making targeted edits to text files, allowing you to replace specific occurrences of text with new content while preserving the rest of the file unchanged.\nIt validates that the file exists, is accessible, and is a text file (not binary) before attempting any modifications, ensuring data integrity.\nThe tool can replace a single occurrence, a specific number of occurrences, or all occurrences of the target text based on your requirements.\nIt should be used when you need to fix typos, update variable names, modify configuration values, or make any other precise text changes in code or text files.\nThe tool will report the exact number of replacements made and will fail safely if the target text is not found or if multiple matches exist when expecting a unique match.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path to the file to edit. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The file must exist and have write permissions. Binary files cannot be edited with this tool."},oldValue:{type:"string",description:"The exact text string to search for in the file. This must match exactly including whitespace, indentation, and line breaks. The match is case-sensitive. If multiple matches exist and replaceAll is false, only the first occurrence from the beginning of the file will be replaced."},newValue:{type:"string",description:"The replacement text that will be inserted in place of each matched occurrence of oldValue. Can be an empty string to effectively delete the matched text. Preserves any surrounding whitespace and formatting."},replaceAll:{type:"boolean",description:"When true, replaces all occurrences of oldValue in the file. When false (default), replaces only the number of occurrences specified by replacementCount. Use true when you need to update all instances, such as renaming a variable throughout a file."},replacementCount:{type:"number",description:"The number of occurrences to replace when replaceAll is false. Default is 1. Must be a positive integer. If set higher than the actual number of occurrences, the tool will report an error. Use this for controlled, partial replacements."}},required:["filePath","oldValue","newValue"]},execute:__name(async e=>{try{const t=rt.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`❌ Error: ${e.message}`:"❌ Error: Unknown error occurred while editing file"}},"execute")},st=y.object({path:y.string().describe("The absolute path to the directory to read"),exclude:y.array(y.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:y.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});y.object({files:y.array(y.string()),directories:y.array(y.string())});var it=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}};async function readDirectory(e){const{path:n,exclude:r=[],respectGitIgnore:o=!1}=e;if(!s.isAbsolute(n))throw new it("Path must be absolute, not relative","INVALID_PATH");try{if(!(await t.stat(n)).isDirectory())throw new it("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof it)throw e;throw new it(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await t.readdir(n);let i=[];o&&(i=await loadGitIgnorePatterns(n));const a=[...r,...i],c=[],l=[];for(const r of e){if(shouldIgnoreEntry(r,a))continue;const e=s.join(n,r);try{const n=await t.stat(e);n.isDirectory()?l.push(r):n.isFile()&&c.push(r)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:c.sort(),directories:l.sort()}}catch(e){if(e instanceof it)throw e;throw new it(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(e){const n=[];try{if(!await isInGitRepository(e))return n;let r=s.resolve(e);const o=await findGitRoot(e);for(;r&&isWithinGitRoot(r,o);){const e=s.join(r,".gitignore");try{const r=(await t.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...r)}catch(e){}const o=s.dirname(r);if(o===r)break;r=o}}catch(e){}return n}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(e){let n=s.resolve(e);for(;;){try{const e=s.join(n,".git");if((await t.stat(e)).isDirectory())return n}catch{}const e=s.dirname(n);if(e===n)throw new Error("Not in a git repository");n=e}}function isWithinGitRoot(e,t){const n=s.resolve(e),r=s.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(z(e,n))return!0;return!1}function formatOutput3(e){const t=e.directories.length+e.files.length,n=[];return n.push(`Found ${t} items (${e.directories.length} dirs, ${e.files.length} files)`),e.directories.length>0&&(n.push("Directories:"),e.directories.forEach(e=>n.push(` ${e}/`))),e.files.length>0&&(n.push("Files:"),e.files.forEach(e=>n.push(` ${e}`))),0===t&&n.push("(empty directory)"),n.join("\n")}__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),__name(formatOutput3,"formatOutput");var at={name:"read_directory",description:"Lists the contents of a directory, providing separate arrays of files and subdirectories found at the specified path.\nThis tool is essential for exploring project structure, discovering available files, and understanding directory organization before performing operations on specific files.\nIt automatically respects .gitignore patterns by default when operating within git repositories, ensuring you don't see files that are intentionally excluded from version control.\nThe tool supports custom exclusion patterns using glob syntax, allowing you to filter out specific files or directories based on your needs, such as build artifacts or temporary files.\nResults are always sorted alphabetically for consistent output, making it easier to locate specific items in large directories.\nIt should be used when you need to explore a directory's contents, verify file existence, or understand project structure before performing file operations.",input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the directory to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The directory must exist and be accessible. Returns an error if the path points to a file instead of a directory."},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude from results. Uses minimatch syntax for pattern matching. Examples: ["*.log", "temp*", "**/*.tmp"] would exclude all log files, anything starting with "temp", and all .tmp files in any subdirectory. Patterns are applied in addition to any .gitignore rules.'}},required:["path"]},execute:__name(async e=>{try{const t=st.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`❌ Error: ${e.message}`:"❌ Error: Unknown error occurred while reading directory"}},"execute")},ct=y.object({filePath:y.string().describe("The absolute path where the file should be written"),content:y.string().describe("The content to write to the file")});async function writeFile2({filePath:e,content:t}){if(!u(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=c(e);N(n)||await r(n,{recursive:!0}),await o(e,t,"utf-8");const s=Buffer.byteLength(t,"utf-8");return console.log(`Successfully wrote ${s} bytes to: ${e}\n`),{path:e,bytesWritten:s}}catch(t){const n=t instanceof Error?t.message:"Unknown error occurred";throw new Error(`Failed to write file '${e}': ${n}`)}}function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}y.object({success:y.boolean(),message:y.string(),path:y.string().optional()}),__name(writeFile2,"writeFile"),__name(formatOutput4,"formatOutput");var lt={name:"write_file",description:"Creates or overwrites a file with the specified content at the given absolute path, automatically creating any necessary parent directories.\nThis tool handles the complete file writing process, including directory creation, making it ideal for generating new files, saving processed output, or creating configuration files.\nIf the file already exists, it will be completely overwritten with the new content - the previous contents will be lost, so use with caution on existing files.\nThe tool automatically creates any missing parent directories in the path, eliminating the need to manually ensure directory structure exists before writing.\nIt should be used when you need to create new files, save generated content, write configuration files, or output processed data to the filesystem.\nAll content is written as UTF-8 encoded text, making it suitable for source code, configuration files, documentation, and other text-based formats.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path where the file should be written. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). If parent directories do not exist, they will be created automatically. Existing files at this path will be overwritten without warning."},content:{type:"string",description:"The text content to write to the file. Can be any UTF-8 string including multi-line text, JSON, XML, source code, or any other text format. Empty strings are valid and will create an empty file. Line endings are preserved as provided."}},required:["filePath","content"]},execute:__name(async e=>{try{const t=ct.parse(e),n=await writeFile2(t);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")},ut=y.object({include:y.array(y.string()).describe("Array of glob patterns to include files"),exclude:y.array(y.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:y.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:y.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:y.string().optional().describe("Base directory for relative paths. Default: current working directory")}),dt=y.object({filePath:y.string(),content:y.string(),fileType:y.string(),size:y.number()});y.object({content:y.string(),filesRead:y.array(y.string()),errors:y.array(y.object({file:y.string(),error:y.string()})),fileDetails:y.array(dt)});var mt=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},pt=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const o=new Set;for(const s of e)try{(await W(s,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>o.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${s}": ${e}`)}return Array.from(o).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:t,exclude:n=[],gitIgnore:r=!0,defaultExclude:o=!0,targetDirectory:s=process.cwd()}=e;if(!t||0===t.length)throw new mt("At least one include pattern must be provided","NO_PATTERNS");const a=i.resolve(s),c={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(...pt);const s=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:a});for(const e of s)try{const t=i.resolve(a,e),n=await readFileContent({absolutePath:t}),r=processFileResult({content:n,filePath:e});c.fileDetails.push(r),c.content+=`\n// File: ${e} (${n.fileType})\n`,c.content+=r.content,c.content+="\n",c.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);c.errors.push({file:e,error:n}),c.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return c}catch(e){if(e instanceof mt)throw e;throw new mt(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getReadSummary(e){return{totalFiles:e.fileDetails.length,successfulReads:e.filesRead.length,failedReads:e.errors.length,totalSize:e.fileDetails.reduce((e,t)=>e+t.size,0),fileTypesCounts:e.fileDetails.reduce((e,t)=>(e[t.fileType]=(e[t.fileType]||0)+1,e),{}),contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];return n.push(`Read ${t.successfulReads}/${t.totalFiles} files (${t.totalSize} bytes)`),e.errors.length>0&&(n.push("\nErrors:"),e.errors.forEach(e=>n.push(` - ${e.file}: ${e.error}`))),n.push("\n--- File Contents ---"),n.push(e.content),n.join("\n")}__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles"),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var ht={name:"read_multiple_files",description:"Reads multiple files simultaneously based on glob patterns, returning their contents concatenated with clear file headers for easy identification.\nThis tool is designed for bulk file operations, such as analyzing all source files in a project, reviewing multiple configuration files, or processing sets of related documents.\nIt automatically excludes common non-source directories like node_modules and build folders by default, and respects .gitignore patterns to avoid processing files that shouldn't be analyzed.\nThe tool handles both text and binary files appropriately - text files have their content included while binary files are noted with their type and size information.\nEach file's content is clearly separated with a header showing the file path and type, making it easy to distinguish between different files in the concatenated output.\nIt should be used when you need to analyze multiple files at once, search across multiple files for patterns, or gather content from various sources for processing or review.\nThe tool provides detailed feedback including which files were successfully read, any errors encountered, and statistics about the operation.",input_schema:{type:"object",properties:{include:{type:"array",items:{type:"string"},description:'Array of glob patterns to match files for reading. Uses standard glob syntax with support for wildcards (* for single level, ** for recursive). Examples: ["**/*.ts"] matches all TypeScript files, ["src/**/*.js", "lib/**/*.js"] matches JavaScript files in src and lib directories. At least one pattern must be provided.'},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude files from reading. Applied after include patterns. Examples: ["**/*.test.ts", "**/*.spec.js"] excludes test files, ["**/generated/**"] excludes generated directories. These patterns are additive with default exclusions and .gitignore rules.'},defaultExclude:{type:"boolean",description:"Whether to apply default exclusions for common non-source directories and files. Default is true. When enabled, automatically excludes: node_modules, dist, build, .git, coverage, tmp, temp, .DS_Store, *.log, *.tmp, *.cache, and other common build artifacts. Set to false to read all matching files regardless of common conventions."},gitIgnore:{type:"boolean",description:"Whether to respect .gitignore files when matching patterns. Default is true. When enabled, any files or directories listed in .gitignore files will be excluded from results. Useful for avoiding generated files, secrets, or other intentionally untracked files. Set to false to include all files matching your patterns."},targetDirectory:{type:"string",description:"The base directory from which to resolve glob patterns. Default is the current working directory. Must be an absolute path. All include and exclude patterns will be resolved relative to this directory. Use this to scope your file search to a specific part of the filesystem."}},required:["include"]},execute:__name(async e=>{try{const t=ut.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`❌ Error: ${e.message}`:"❌ Error: Unknown error occurred while reading multiple files"}},"execute")},gt=y.object({pattern:y.string().min(1,"Pattern is required"),include:y.array(y.string()).optional(),directory:y.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=f(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",i="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{i+=e.toString()}),o.on("close",e=>{0===e?n(s):1!==e||i?r(new Error(i||`Command failed with exit code ${e}`)):n("")}),o.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,o]=t;return{file:n,line:parseInt(r,10),column:1,content:o.trim(),match:o.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",o=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)o.splice(-1,0,"--glob",e);o.splice(-1,0,"--glob","!node_modules/**"),o.splice(-1,0,"--glob","!.git/**"),o.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:o,command:"rg"})}catch(s){if(!(s instanceof Error&&s.message.includes("ENOENT")))throw s;if(r="grep",o=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)o.splice(-1,0,"--include",e);o.splice(-1,0,"--exclude-dir=node_modules"),o.splice(-1,0,"--exclude-dir=.git"),o.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:o,command:"grep"})}if(!e.trim())return[];const s=e.trim().split("\n"),i=[];for(const e of s){const t=parseGrepLine(e);t&&i.push(t)}return i}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),__name(formatGrepResults,"formatGrepResults");var ft={name:"grep",description:"Searches for text patterns across files in a directory using regular expressions, providing powerful pattern matching capabilities for code analysis, debugging, and content discovery.\nThis tool performs recursive searches through directory structures, examining file contents to find all occurrences of the specified pattern, making it ideal for locating specific code implementations, finding TODO comments, searching for function usage, or identifying configuration values.\nThe search uses Perl-compatible regular expressions (PCRE), supporting advanced patterns including lookaheads, lookbehinds, character classes, and quantifiers, with results showing file paths and line numbers for each match.\nFile filtering can be applied using glob patterns to search only specific file types, improving performance and relevance by focusing on the files that matter for your search.\nIt should be used when you need to find where something is defined or used in a codebase, locate specific text patterns across multiple files, verify the presence of certain code patterns, or analyze code structure and dependencies.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'The regular expression pattern to search for in file contents. Supports full PCRE syntax including special characters (\\d, \\w, \\s), quantifiers (*, +, ?, {n,m}), anchors (^, $), and groups. Special regex characters like ., *, [, ], (, ), {, }, |, \\, ^, $ must be escaped with backslash when matching literally. Examples: "TODO.*urgent" finds TODO comments marked urgent, "function\\s+\\w+\\(" finds function definitions, "import.*from.*react" finds React imports.'},include:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to filter which files to search. Only files matching at least one pattern will be searched. Supports standard glob syntax: * matches any characters except /, ** matches any characters including /, ? matches single character, [abc] matches character set. Examples: ["*.ts", "*.tsx"] searches TypeScript files, ["src/**/*.js"] searches JavaScript files in src directory, ["*.{js,jsx,ts,tsx}"] searches all JavaScript/TypeScript files. If omitted, searches all files except those in .gitignore.'},directory:{type:"string",description:'Optional directory to search in, specified as a relative path from the current working directory. Cannot be an absolute path. Examples: "src" searches in src folder, "packages/core" searches in packages/core, "." or omitted searches current directory. The directory must exist and be readable. Defaults to the current working directory if not specified.'}},required:["pattern"]},execute:__name(async e=>{try{const t=gt.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`❌ Error: ${e.message}`:"❌ Error: Unknown error occurred while searching files"}},"execute")},yt=y.object({command:y.string().min(1,"Command cannot be empty"),args:y.array(y.string()).optional(),directory:y.string().optional(),timeout:y.number().optional()}),wt=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,i){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=i}};async function executeShellCommand(e){const{command:t,args:r=[],directory:o,timeout:i=3e4}=e,a=Date.now();if(!t.trim())throw new wt("Command cannot be empty","EMPTY_COMMAND");let c;if(o){if(s.isAbsolute(o))throw new wt("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");c=s.resolve(process.cwd(),o)}else c=process.cwd();try{if(!(await n.stat(c)).isDirectory())throw new wt(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof wt)throw e;throw new wt(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:c,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((n,o)=>{let s="",c="",l=!1;const u=setTimeout(()=>{if(!l){d.kill("SIGTERM");const e=Date.now()-a;o(new wt(`Command timed out after ${i}ms`,"TIMEOUT",null,"SIGTERM",s,c,e))}},i),d=f(t,r,e);d.stdout?.on("data",e=>{s+=e.toString()}),d.stderr?.on("data",e=>{c+=e.toString()}),d.on("close",(e,t)=>{l=!0,clearTimeout(u);const r=Date.now()-a;0===e?n({stdout:s.trim(),stderr:c.trim(),exitCode:e,signal:t,duration:r}):o(new wt(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,s.trim(),c.trim(),r))}),d.on("error",e=>{l=!0,clearTimeout(u);const t=Date.now()-a;o(new wt(`Failed to start command: ${e.message}`,"START_FAILED",null,null,s.trim(),c.trim(),t))})})}catch(e){if(e instanceof wt)throw e;throw new wt(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}function formatShellCommandResult(e){const t=[];return 0===e.exitCode||null===e.exitCode||t.push(`Exit code: ${e.exitCode}`),e.signal&&t.push(`Signal: ${e.signal}`),e.stdout&&t.push(e.stdout),e.stderr&&t.push(e.stderr),t.join("\n")}__name(executeShellCommand,"executeShellCommand"),__name(formatShellCommandResult,"formatShellCommandResult");var bt={name:"shell_command",description:"Executes shell commands in a controlled environment with comprehensive output capture, timeout protection, and working directory management, enabling system operations, build processes, and tool integrations.\nThis tool spawns commands as child processes with full control over execution environment, capturing both standard output and error streams while monitoring exit codes and signals, making it ideal for running build scripts, executing CLI tools, performing system operations, or integrating with external programs.\nCommands run with shell interpretation enabled for cross-platform compatibility, supporting pipes, redirections, and shell built-ins, with automatic timeout termination to prevent hanging processes from blocking execution.\nThe tool provides detailed execution results including stdout, stderr, exit codes, and execution duration, helping diagnose issues and verify successful completion of operations.\nIt should be used when you need to run build or test commands, execute system utilities, interact with CLI tools, perform file operations that require shell commands, or integrate with external programs and scripts.\nImportant: Commands execute with the permissions of the current process. Be cautious with commands that modify the filesystem or system state. Always validate and sanitize any user-provided input before including it in commands.",input_schema:{type:"object",properties:{command:{type:"string",description:'The shell command to execute. Can be any valid shell command available in the system PATH or built-in shell commands. Common commands include: "npm" for Node.js packages, "git" for version control, "ls"/"dir" for listing files, "echo" for output, "cat"/"type" for file contents. The command string is passed to the system shell (sh on Unix, cmd.exe on Windows). Special characters should be properly escaped. Cannot be empty.'},args:{type:"array",items:{type:"string"},description:'Optional array of arguments to pass to the command. Each argument is passed as a separate string and is automatically escaped for shell safety. Use this instead of including arguments in the command string for better security and cross-platform compatibility. Examples: ["install", "--save-dev", "typescript"] for npm, ["status", "--short"] for git, ["-la", "/usr"] for ls. Arguments containing spaces or special characters are automatically quoted.'},directory:{type:"string",description:'Optional working directory where the command should be executed, specified as a relative path from the current working directory. Must be a relative path (absolute paths are not allowed for security). The directory must exist and be accessible. Examples: "src" runs in src folder, "packages/core" runs in packages/core, "../sibling" runs in sibling directory. If omitted, uses the current working directory. Useful for running commands that depend on specific file locations or configurations.'},timeout:{type:"number",description:"Optional maximum time in milliseconds to wait for the command to complete before forcibly terminating it. Must be between 100 and 300000 (5 minutes). Defaults to 30000ms (30 seconds). The command process is killed with SIGTERM if it exceeds this duration. Useful for preventing long-running or hanging processes. Set higher for operations known to take time (builds, installs), lower for quick operations. Examples: 5000 for quick commands, 60000 for npm install, 120000 for large builds."}},required:["command"]},execute:__name(async e=>{try{const t=yt.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`❌ Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`❌ Error: ${e.message}`}return"❌ Error: Unknown error occurred while executing command"}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}__name(think,"think");var Et={name:"think",description:'Use this tool to think step by step about complex problems. Use first-person language: "I need to understand..." or "Let me figure out..." rather than "The user wants...". Show your reasoning process.',input_schema:{type:"object",properties:{thought:{type:"string",description:"Your step-by-step reasoning and thought process"}},required:["thought"]},execute:think};async function todoWrite(e){return JSON.stringify(e.todos)}__name(todoWrite,"todoWrite");var xt=[nt,ot,at,lt,ht,ft,bt,Et,{name:"todo_write",description:"Create and manage a structured task list. Use this to track progress, organize complex tasks, and show thoroughness to the user. Create todos when tasks require multiple steps, are non-trivial, or when explicitly requested.",input_schema:{type:"object",properties:{todos:{type:"array",description:"The updated todo list",items:{type:"object",properties:{content:{type:"string",minLength:1,description:"The todo item content"},status:{type:"string",enum:["pending","in_progress","completed"],description:"The status of the todo item"},id:{type:"string",description:"Unique identifier for the todo item"}},required:["content","status","id"]}}},required:["todos"]},execute:todoWrite}],Ct=new Map(xt.map(e=>[e.name,e]));async function executeTool(e,t){const n=Ct.get(e);if(!n)throw new Error(`Tool "${e}" not found. Available tools: ${Array.from(Ct.keys()).join(", ")}`);try{return await n.execute(t)}catch(e){return e instanceof Error?`Error: ${e.message}`:"Error: Unknown error occurred"}}function getToolSchemas(){return xt.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(1.1*t));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)"text"===n.type?t+=estimateTextTokens(n.text):"image"===n.type&&"source"in n&&"base64"===n.source.type&&(t+=estimateImageTokens(n.source.data));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/3.5;const n=.1*e.split(/\s+/).length;return Math.ceil(t-n)}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>25e3}function getOversizedOutputError(e,t){return`Error: Output too large (${e.toLocaleString()} tokens, max ${25e3.toLocaleString()}). Try using grep or ripgrep with more specific patterns to filter results.`}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?getOversizedOutputError(estimateTokens(e)):e}function calculateUsageFromResponse(e){return(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.output_tokens||0)}__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse");var vt=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return i.join(p.homedir(),".command-code","projects")}static getCurrentProjectDirName(){return q(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=i.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=i.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=g("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await n.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),!1}}async isProjectInitialized(){try{return(await n.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{const r=JSON.stringify(e);if(r===this.lastSavedMessagesHash)return;await this.initializeProject();const o=[];for(const n of e){const e=crypto.randomUUID(),r={id:e,timestamp:n.meta.timestamp,sessionId:this.sessionId,parentId:this.lastMessageId,role:n.message.role,content:n.message.content,gitBranch:this.gitBranch,metadata:{...n.meta,...t?.metadata||{}}};o.push(JSON.stringify(r)),this.lastMessageId=e}await n.writeFile(this.sessionFilePath,o.join("\n")+"\n"),this.lastSavedMessagesHash=r}catch(e){console.error("Failed to save messages to session:",e)}}async loadMessages(e){const t=e||this.sessionId,r=i.join(this.projectPath,`${t}.jsonl`);try{const e=(await n.readFile(r,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);"user"!==e.role&&"assistant"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}})}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading messages:",e),[]}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),o=crypto.randomUUID();if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n&&t.push({id:o,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const r of e.content)if("text"===r.type)n+=r.text;else if("tool_use"===r.type){const e=He(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}n&&t.push({id:o,timestamp:r,role:"assistant",input:n,images:[]})}}return t}async loadSession(e){const t=e||this.sessionId,r=i.join(this.projectPath,`${t}.jsonl`);try{const e=(await n.readFile(r,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);t.push(e)}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading session:",e),[]}}convertToFeedEntries(e){return e.map(e=>{const t={id:e.id,timestamp:new Date(e.timestamp).getTime(),role:e.role,metadata:e.metadata};return"object"==typeof e.content&&null!==e.content&&"input"in e.content?{...t,input:e.content.input,output:e.content.output,...e.content.name?{name:e.content.name}:{},...e.content.command?{command:e.content.command}:{}}:{...t,input:"string"==typeof e.content?e.content:JSON.stringify(e.content)}})}convertToAnthropicMessages(e){return e.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>{let t;if(t="string"==typeof e.content?e.content:e.content&&"object"==typeof e.content?e.content.input||JSON.stringify(e.content):"","user"===e.role&&e.metadata?.fileReferences)try{t=reconstructContent(t,e.metadata.fileReferences)}catch(e){console.error("Failed to reconstruct file content from session:",e)}return{role:e.role,content:t}})}static async isProjectInitialized(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),r=i.join(e,t);try{return(await n.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),r=i.join(e,t);try{return await n.mkdir(r,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=i.join(_SessionManager.getProjectsBasePath(),e);try{try{await n.access(t)}catch{return[]}const e=(await n.readdir(t)).filter(e=>e.endsWith(".jsonl")),r=[];for(const o of e){const e=o.replace(".jsonl",""),s=i.join(t,o);try{const o=await n.stat(s),i=(await n.readFile(s,"utf-8")).trim().split("\n").filter(e=>e.trim());if(i.length>0){let n="",s="";const a=JSON.parse(i[0]);a.gitBranch&&(s=a.gitBranch);for(const e of i){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)n=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){n=e.text;break}}else t.content?.input&&(n=t.content.input);if(n)break}}r.push({id:e,createdAt:o.birthtime.toISOString(),lastModified:o.mtime.toISOString(),firstMessage:n||"No messages",messageCount:i.length,projectPath:t,gitBranch:s||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return r.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const t=i.join(this.projectPath,`${this.sessionId}.share.json`);try{await n.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=i.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await n.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=i.join(this.projectPath,`${this.sessionId}.share.json`);try{await n.unlink(e)}catch(e){}}};function getApiBaseUrl({prod:e}={}){return(void 0!==e?e:"development"!==process.env.ENVIRONMENT)?"https://api.claicode.com":"http://localhost:9090"}__name(getApiBaseUrl,"getApiBaseUrl");var St=class _APIError extends Error{static{__name(this,"APIError")}status;headers;error;code;param;type;request_id;constructor(e,t,n,r){super(_APIError.makeMessage(e,t,n)),this.status=e,this.headers=r,this.request_id=r?.["lb-request-id"];const o=t;this.error=o,this.code=o?.code,this.status=o?.status}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e)return new kt({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Tt(e,o,n,r);case 401:return new Pt(e,o,n,r);case 403:return new At(e,o,n,r);case 404:return new It(e,o,n,r);case 409:return new Dt(e,o,n,r);case 422:return new $t(e,o,n,r);case 429:return new Ft(e,o,n,r);default:return e>=500?new Rt(e,o,n,r):new _APIError(e,o,n,r)}}},kt=class extends St{static{__name(this,"APIConnectionError")}status=void 0;constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Tt=class extends St{static{__name(this,"BadRequestError")}status=400},Pt=class extends St{static{__name(this,"AuthenticationError")}status=401},At=class extends St{static{__name(this,"PermissionDeniedError")}status=403},It=class extends St{static{__name(this,"NotFoundError")}status=404},Dt=class extends St{static{__name(this,"ConflictError")}status=409},$t=class extends St{static{__name(this,"UnprocessableEntityError")}status=422},Ft=class extends St{static{__name(this,"RateLimitError")}status=429},Rt=class extends St{static{__name(this,"InternalServerError")}},Mt=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=this.buildHeaders({headers:e.headers});let o;try{o=await this.makeRequest({url:n,options:e,headers:r})}catch(e){throw new kt({cause:e instanceof Error?e:void 0})}return o.ok||await this.handleErrorResponse({response:o}),e.stream?o.body:o.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}buildHeaders({headers:e}){return{"Content-Type":"application/json",...this.config.apiKey?{Authorization:`Bearer ${this.config.apiKey}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const s=await fetch(e,{method:t.method,headers:n,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return o&&clearTimeout(o),s}catch(e){throw o&&clearTimeout(o),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};throw e.headers.forEach((e,t)=>{n[t]=e}),St.generate(e.status,t,e.statusText,n)}async post(e){return this.send({...e,method:"POST"})}async get(e){return this.send({...e,method:"GET"})}async put(e){return this.send({...e,method:"PUT"})}async delete(e){return this.send({...e,method:"DELETE"})}},jt=y.object({timestamp:y.string(),model:y.string().optional(),duration:y.number().optional(),usage:y.object({inputTokens:y.number(),outputTokens:y.number(),totalTokens:y.number(),cacheReadTokens:y.number().optional(),cacheWriteTokens:y.number().optional(),estimatedCost:y.number().optional()}).optional(),source:y.string().optional(),context:y.object({sessionId:y.string().optional(),threadId:y.string().optional(),userId:y.string().optional()}).optional()});y.object({message:y.any(),meta:jt}),y.object({sessionId:y.string(),messages:y.array(y.any()).optional()}),y.object({secret:y.string(),url:y.string()}),y.object({sessionId:y.string(),secret:y.string()}),y.object({sessionId:y.string(),secret:y.string(),key:y.string(),content:y.any()}),y.object({sessionId:y.string(),secret:y.string(),message:y.any()}),y.object({shortId:y.string()}),y.object({info:y.any().optional(),messages:y.array(y.any())});var Ot=class _PathSanitizer{static{__name(this,"PathSanitizer")}projectRoot;homeDir;options;constructor(e={}){this.projectRoot=e.projectRoot||process.cwd(),this.homeDir=this.getHomeDirectory(),this.options={projectRoot:this.projectRoot,useHomeShorthand:e.useHomeShorthand??!0,customReplacements:e.customReplacements||[]}}sanitizeMessage(e){if(!e)return e;const t=JSON.parse(JSON.stringify(e)),n=t.message||t;return"string"==typeof n.content?n.content=this.sanitizeText(n.content):Array.isArray(n.content)?n.content=n.content.map(e=>"text"===e.type&&"string"==typeof e.text?{...e,text:this.sanitizeText(e.text)}:"tool_use"===e.type&&e.input?{...e,input:this.sanitizeToolInput(e.input)}:e):n.content&&"object"==typeof n.content&&(n.content.input&&(n.content.input=this.sanitizeText(n.content.input)),n.content.output&&(n.content.output=this.sanitizeText(n.content.output))),t.message&&(t.message=n),t.metadata&&(t.metadata=this.sanitizeObject(t.metadata)),t}sanitizeToolInput(e){if(!e||"object"!=typeof e)return e;const t={...e},n=["absolutePath","filePath","path","file_path"];for(const e of n)t[e]&&"string"==typeof t[e]&&(t[e]=this.sanitizePath(t[e]));return t.directory&&"string"==typeof t.directory&&(t.directory=this.sanitizePath(t.directory)),t.content&&"string"==typeof t.content&&(t.content=this.sanitizeText(t.content)),t}sanitizeText(e){if(!e||"string"!=typeof e)return e;let t=e;for(const{pattern:e,replacement:n}of this.options.customReplacements)t=t.replace(e,n);return t=this.replaceAbsolutePaths(t),t}sanitizePath(e){if(!e||"string"!=typeof e)return e;if(!i.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=i.relative(this.projectRoot,e);if(!t.startsWith("../../../"))return t.startsWith("../")?t:`./${t}`}catch(e){}if(this.options.useHomeShorthand&&e.startsWith(this.homeDir))return e.replace(this.homeDir,"~");const t=i.basename(e);return i.dirname(e),this.isUserPath(e)?`<user-home>/${i.relative(this.homeDir,e)}`:`<system-path>/${t}`}replaceAbsolutePaths(e){return e.match(/\/(?:Users|home)\/[^\/\s]+(?:\/[^\s]*)?/g),(e=e.replace(/\/(?:Users|home)\/[^\/\s]+(?:\/[^\s]*)?/g,e=>this.sanitizePath(e))).match(/[A-Za-z]:\\(?:Users\\[^\\]+(?:\\[^\\]*)*|[^\s]*)/g),(e=e.replace(/[A-Za-z]:\\(?:Users\\[^\\]+(?:\\[^\\]*)*|[^\s]*)/g,e=>this.sanitizePath(e))).match(/(?:^|\s)([A-Za-z]:\\[^\s]*|\/[^\s]*)/g),e.replace(/(?:^|\s)([A-Za-z]:\\[^\s]*|\/[^\s]*)/g,(e,t)=>e.substring(0,e.length-t.length)+this.sanitizePath(t))}sanitizeObject(e){if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.sanitizeObject(e));const t={};for(const[n,r]of Object.entries(e))t[n]="string"==typeof r?this.sanitizeText(r):"object"==typeof r?this.sanitizeObject(r):r;return t}isWindowsAbsolutePath(e){return/^[A-Za-z]:\\/.test(e)}isUserPath(e){return e.includes("/Users/")||e.includes("/home/")||e.includes("\\Users\\")}getHomeDirectory(){return process.env.HOME||process.env.USERPROFILE||""}static forProject(e){return new _PathSanitizer({projectRoot:e,useHomeShorthand:!0})}static sanitizeMessage(e,t){return _PathSanitizer.forProject(t).sanitizeMessage(e)}static sanitizeMessages(e,t){const n=_PathSanitizer.forProject(t);return e.map(e=>n.sanitizeMessage(e))}};function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${p.platform()}-${p.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return j.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!e.name.startsWith(".")).filter(e=>!t.has(e.name)).map(e=>e.name).sort()}catch{return[]}}function isGitRepository(){try{return g("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return g("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=g("git branch -r",{encoding:"utf8",cwd:getCurrentWorkingDirectory()});return e.includes("origin/main")?"main":e.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=g("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),n=t.filter(e=>e.startsWith(" M")).length,r=t.filter(e=>e.startsWith("A ")).length,o=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,i=[];return n>0&&i.push(`M ${n}`),r>0&&i.push(`A ${r}`),o>0&&i.push(`D ${o}`),s>0&&i.push(`?? ${s}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=g("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getRootDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[]}}__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext");var Ut=new ge("ContextEngine"),_t=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();constructor(e,t){const n=getApiBaseUrl();this.request=new Mt({baseUrl:n}),this.callbacks=e,this.sessionManager=new vt(t)}async getClient(){return this.anthropic||(this.anthropic=await Ze.getClient()),this.anthropic}async interrupt(e=!1){if(this.abortController){this.abortController.abort(),this.abortController=null,Ut.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)&&t.message.content.some(e=>"tool_use"===e.type)&&(this.messages.pop(),Ut.debug("Removed assistant message with pending tool calls to prevent API errors")),e){this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[{type:"text",text:"Interrupted by user"}]}));const e=Oe("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>Ut.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t){let n=e,r=[];try{const t=await processFileReferences(e);n=t.processedContent,r=t.fileReferences}catch(e){console.error("File reference processing failed:",e)}const o=Oe(e);t&&t.length>0&&(o.metadata={...o.metadata,images:t}),r&&r.length>0&&(o.metadata={...o.metadata,fileReferences:r}),this.callbacks.onFeedUpdate(o);const s=[];t&&t.length>0&&t.forEach(e=>{s.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),n.trim()&&s.push({type:"text",text:n});const i={role:"user",content:s};return this.addMessageAndSync(this.createMessageWithMeta(i)),this.sessionManager.saveMessages(this.messages,o).catch(e=>Ut.error(`Failed to save messages to session: ${e}`)),await this.processMessages()}async processMessages(){let e="";this.abortController=new AbortController;let t=!1;for(;;)try{if(this.abortController?.signal.aborted)throw new Error("Interrupted by user");if(!t){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message),t=!0}const n=getToolSchemas(),r=await xe.getValidAccessToken(),o={tools:n,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:"anthropic:claude-sonnet-4-20250514"},s={config:getEnvironmentContext(),params:o};Ut.debug(`🔍 API Call: ${o.model}, ${this.messages.length} messages, ${n.length} tools, streaming: true`);const i=await this.request.post({body:s,stream:!0,endpoint:fe,signal:this.abortController?.signal,headers:{"x-oauth-token":`Bearer ${r}`}}),a=G.fromReadableStream(i);a.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let c,l=null;a.on("error",e=>{l="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});try{c=await a.finalMessage()}catch(e){if(l)throw l;if("AbortError"===e.name||e.message?.includes("aborted")||this.abortController?.signal.aborted)throw new Error("Interrupted by user");throw e}if(l)throw l;if("usage"in c){const e=c.usage;if(e?.input_tokens){const t=calculateUsageFromResponse(e);this.contextTokensUsed=t,this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:2e5})}}const u=c.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),d=c.content.filter(e=>"tool_use"===e.type);if(e=u,0===d.length){const e=c.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(e.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:e})),u.trim()){const e=Ue(u);this.callbacks.onFeedUpdate(e),this.sessionManager.saveMessages(this.messages,e).catch(e=>Ut.error(`Failed to save messages: ${e}`))}if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0){const t=[];for(const n of e){t.push({type:"text",text:n});const e=Oe(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>Ut.error(`Failed to save messages: ${e}`));continue}}break}const m=c.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(m.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:m})),u.trim()){const e=Ue(u);this.callbacks.onFeedUpdate(e)}const p=[],h=new Set;let g=!1;for(const e of d){if(this.abortController?.signal.aborted)throw new Error("Interrupted by user");try{if(["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&this.callbacks.onPermissionRequest&&!await this.callbacks.onPermissionRequest(e.name,e.input)){const t=He(e.name,e.input),n="edit_file"===e.name?e.input:void 0,r=_e(e.name,t,n),o=Be(r,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o),g=!0;break}const t=await executeTool(e.name,e.input);if(this.abortController?.signal.aborted)throw new Error("Interrupted by user");const n=checkToolOutputTokensLimit(t,e.name),r=estimateTokens(n);this.currentInteractionTokens+=r,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),p.push({type:"tool_result",tool_use_id:e.id,content:n}),h.add(e.id);const o=He(e.name,e.input),s="edit_file"===e.name?e.input:void 0,i=_e(e.name,o,s),a=Be(i,n);this.callbacks.onFeedUpdate(a)}catch(t){const n=t instanceof Error?t.message:"Unknown error";p.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}),h.add(e.id);const r=He(e.name,e.input),o="edit_file"===e.name?e.input:void 0,s=_e(e.name,r,o),i=Be(s,ze(n));this.callbacks.onFeedUpdate(i)}}if(g){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?h.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const f=[...p];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){f.push({type:"text",text:t});const e=Oe(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:f})),this.sessionManager.saveMessages(this.messages).catch(e=>Ut.error(`Failed to save messages: ${e}`))}catch(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||this.abortController?.signal.aborted)throw Ut.debug("Request interrupted by user"),new Error("Interrupted by user");throw Ut.error(`Failed to get response: ${e}`),e}return this.abortController=null,e}getHistory(){return[...this.messages]}async loadSession(e){const t=await this.sessionManager.loadMessages(e);this.messages=t;const n=this.sessionManager.reconstructFeedFromMessages(t);return Ut.debug(`Loaded session ${e} with ${t.length} messages`),n}getMessages(){return[...this.messages]}getRawMessages(){return this.messages.map(e=>e.message)}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){Ut.error(`Failed to sync message to share: ${e}`)}}))}async syncMessageToShare(e,t){try{const n=Ot.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r=`${getApiBaseUrl()}${ye.APPEND}`,o={sessionId:e.sessionId,secret:e.secret,message:n},s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const e=await s.text();Ut.error(`Share sync failed with status ${s.status}: ${e}`)}}catch(e){throw e}}};function Markdown({children:e,...t}){const n={...t};Q({renderer:new Z(n),breaks:!0,gfm:!0});const r=K(e);return P.createElement(C,null,r.toString().trim())}function AssistantMessage({content:e}){return P.createElement(x,null,P.createElement(C,null,Y.nodejs),P.createElement(x,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},P.createElement(Markdown,null,e)))}function UserMessage({content:e}){const t="Interrupted by user"===e;return P.createElement(x,null,P.createElement(C,{color:t?"red":"dim"},Y.pointer),P.createElement(x,{marginLeft:1},P.createElement(C,{color:t?"red":void 0,dimColor:!t,wrap:"wrap"},e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage"),__name(UserMessage,"UserMessage");var Nt="#6B7280";function truncateToolOutputForDisplay(e){const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),n=t.split("\n");return n.length<=4?t:`${n.slice(0,4).join("\n")}\n… (${n.length-4} more lines)`}function generateDiff(e,t,n){const r=X.diffLines(e,t);let o=0,s=0,i=0;return r.forEach(e=>{e.added?o+=e.count||1:e.removed&&(s+=e.count||1)}),P.createElement(x,{flexDirection:"column"},P.createElement(C,{color:"gray"},"Updated ",P.createElement(C,{color:"white",bold:!0},n)," with ",P.createElement(C,{color:"#22C55E"},o)," addition",1!==o?"s":""," and ",P.createElement(C,{color:"#EF4444"},s)," removal",1!==s?"s":""),P.createElement(x,{flexDirection:"column",marginLeft:2},r.map((e,t)=>{const n=e.value.split("\n").filter(e=>e);return e.added||e.removed?n.map((n,r)=>e.removed?(i++,P.createElement(x,{key:`${t}-${r}-removed`,width:"100%"},P.createElement(C,{color:"gray"},i.toString().padStart(3)," "),P.createElement(x,{backgroundColor:"#712F37"},P.createElement(C,null,"-"),P.createElement(C,null," ",n.replace(/\s/g," "))))):e.added?(i++,P.createElement(x,{key:`${t}-${r}-added`,width:"100%"},P.createElement(C,{color:"gray"},i.toString().padStart(3)," "),P.createElement(x,{backgroundColor:"#325B30"},P.createElement(C,null,"+"),P.createElement(C,null," ",n.replace(/\s/g," "))))):null):(i+=n.length,null)})))}function formatTodosForDisplay(e){const t=Ye(e);return t?P.createElement(x,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?"☒":"☐";let r,o=!1;switch(e.status){case"completed":r="#22C55E",o=!0;break;case"in_progress":r="#E4CCFF";break;default:r="white"}return P.createElement(x,{key:e.id||t,flexDirection:"row"},P.createElement(x,{width:2},P.createElement(C,{color:r},n)),P.createElement(C,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):P.createElement(C,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s}){const i="Thinking…"===e,a="Todos"===e,c="Edit"===e,l=!i&&t,u=!i&&!a;let d,m;if(r)d="yellow",m="→";else if(o)d="red",m=Y.nodejs;else if(i)d=Nt,m="✻";else if(a&&n){const e=Ye(n),t=e?.every(e=>"completed"===e.status);d=t?"#22C55E":"#D4A017",m=Y.nodejs}else d="#22C55E",m=Y.nodejs;return P.createElement(x,null,P.createElement(C,{color:d,italic:i},m),P.createElement(x,{flexDirection:"column",marginLeft:1},P.createElement(x,null,P.createElement(C,{bold:!i,color:i?Nt:void 0,italic:i},`${e} `),l&&P.createElement(C,null,P.createElement(Markdown,null,`(${t})`))),n&&P.createElement(x,{columnGap:1},u&&P.createElement(C,null,"⎿"," "),a?formatTodosForDisplay(n):i?P.createElement(x,{width:"100%",flexDirection:"column"},P.createElement(C,null," "),P.createElement(C,{color:Nt,wrap:"wrap",italic:!0},n)):c&&s?.oldValue&&s?.newValue?generateDiff(s.oldValue,s.newValue,t):P.createElement(x,{width:"100%"},P.createElement(C,{color:o?"red":"",wrap:"wrap"},truncateToolOutputForDisplay(n)))),r&&P.createElement(x,{columnGap:1},P.createElement(C,null,"⎿"," "),P.createElement(C,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,s;return n?(o="yellow",s="→"):r?(o="red",s="✗"):(o="green",s="✓"),P.createElement(x,null,P.createElement(C,{color:o},s),P.createElement(x,{flexDirection:"column",marginLeft:1},P.createElement(x,null,P.createElement(C,{color:"gray"},"$ "),P.createElement(C,{color:o,bold:!0},e)),P.createElement(x,{columnGap:1},P.createElement(C,null,"⎿"," "),P.createElement(C,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}function SystemMessage({content:e}){return P.createElement(x,{flexDirection:"column"},P.createElement(C,{wrap:"wrap"},P.createElement(Markdown,null,e)))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage"),__name(SystemMessage,"SystemMessage");var Lt="\n ██████╗ ██████╗ ███╗ ███╗███╗ ███╗ █████╗ ███╗ ██╗██████╗\n██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔══██╗████╗ ██║██╔══██╗\n██║ ██║ ██║██╔████╔██║██╔████╔██║███████║██╔██╗ ██║██║ ██║\n██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║\n╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝\n ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝\n",Bt=P.memo(({feed:e,showHeader:t=!1,staticKey:n})=>{const r=t?["header",...e]:e;return P.createElement(E,{items:r,key:n},e=>{if("header"===e)return P.createElement(x,{key:"header",marginBottom:1},P.createElement(V,{name:"vice"},P.createElement(C,null,Lt),P.createElement(C,null,"Welcome to Command by Langbase. Agentic coding agent.")));const t=e,n=(()=>{switch(t.role){case"user":return P.createElement(UserMessage,{content:t.input});case"assistant":return P.createElement(AssistantMessage,{content:t.input});case"tool":return P.createElement(ToolMessage,{name:Ve(t.name||""),input:t.input,output:t.output||"",isPending:qe(t),hasError:We(t),metadata:t.metadata});case"bash":return P.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:qe(t),hasError:We(t)});case"system":return P.createElement(SystemMessage,{content:t.input});default:return P.createElement(P.Fragment,null)}})();return P.createElement(x,{key:t.id,marginBottom:1},n)})}),zt=__name(({messages:e})=>0===e.length?null:P.createElement(x,{borderStyle:"round",borderColor:"#D97706",padding:1,marginBottom:1},P.createElement(x,{flexDirection:"column"},P.createElement(x,{marginBottom:1},P.createElement(C,{color:"#D97706",bold:!0},"Queued Messages (",e.length,")")),e.map((t,n)=>P.createElement(x,{key:n,marginBottom:n===e.length-1?0:1},P.createElement(C,{color:"gray"},"•"),P.createElement(x,{marginLeft:1},P.createElement(C,{dimColor:!0},t.length>60?`${t.substring(0,60)}...`:t)))))),"QueuedMessages"),Wt=["dim","dim2","normal","normal2","bright","bright2","brighter","brighter2","brightest","brightest","brighter2","brighter","bright2","bright","normal2","normal","dim2","dim"],qt=__name(e=>{switch(e){case"dim":return"#8A6BA3";case"dim2":return"#9D7AB8";case"normal":return"#B799E6";case"normal2":return"#C9AAEE";case"bright":default:return"#E4CCFF";case"bright2":return"#EBDAFF";case"brighter":return"#F0D9FF";case"brighter2":return"#F5E8FF";case"brightest":return"#FFFFFF"}},"getGlowColor"),Gt=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=A(0),[s,i]=A(0);function formatToken(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}function formatTime(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}return I(()=>{const e=setInterval(()=>{o(e=>(e+1)%Wt.length)},120);return()=>clearInterval(e)},[]),I(()=>{if(s===n)return;const e=n-s,t=Math.max(1,Math.ceil(Math.abs(e)/20)),r=e>0?t:-t,o=setInterval(()=>{i(e=>{const t=e+r;return r>0&&t>=n||r<0&&t<=n?n:t})},100);return()=>clearInterval(o)},[n,s]),__name(formatToken,"formatToken"),__name(formatTime,"formatTime"),P.createElement(x,{columnGap:1},P.createElement(x,{paddingLeft:1,paddingRight:0},P.createElement(C,{color:qt(Wt[r]),bold:!0},"⌘")),P.createElement(x,null,P.createElement(C,{color:"#E4CCFF",wrap:"wrap"},e)),P.createElement(x,{columnGap:1},P.createElement(C,{dimColor:!0},`(${formatTime(t)}`),P.createElement(C,{dimColor:!0},"•"),P.createElement(C,{color:"gray"},"↑"),P.createElement(C,{dimColor:!0},`${formatToken(Math.round(s))}`),P.createElement(C,{dimColor:!0},"•"),P.createElement(x,{columnGap:1},P.createElement(C,{bold:!0,color:"gray"},"esc"),P.createElement(C,{dimColor:!0},"to interrupt)"))))},"Status"),Jt=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=A(process.cwd()),[s,i]=A([]),[u,m]=A(0),[p,h]=A(0),g=n.trim()?15:10,f=$((e,t=process.cwd())=>{if(!e.trim())return[];const n=[],r=e.toLowerCase(),o=__name((e,s=0)=>{if(!(s>8))try{L(e).forEach(i=>{const c=l(e,i);try{const e=B(c),l=a(t,c),u=l.toLowerCase();(i.toLowerCase().includes(r)||u.includes(r))&&n.push({name:l,path:c,isDirectory:e.isDirectory()}),e.isDirectory()&&(["node_modules"].includes(i)||o(c,s+1))}catch(e){}})}catch(e){}},"searchRecursively");return o(t),n.sort((e,t)=>{const n=e.name.toLowerCase(),o=t.name.toLowerCase(),s=n===r,i=o===r;if(s&&!i)return-1;if(!s&&i)return 1;const a=n.split("/").pop()||"",c=o.split("/").pop()||"",l=a.includes(r),u=c.includes(r);if(l&&!u)return-1;if(!l&&u)return 1;const d=e.name.split("/").length,m=t.name.split("/").length;return d!==m?d-m:e.name.localeCompare(t.name)}),n.slice(0,50)},[]),y=$(e=>{try{const t=L(e),n=[];"/"!==e&&n.push({name:"..",path:c(e),isDirectory:!0}),t.forEach(t=>{const r=l(e,t);try{const e=B(r);n.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),n.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),i(n),m(0),h(0)}catch{}},[]);I(()=>{if(n.trim()){const e=f(n);i(e),m(0),h(0)}else y(r)},[r,y,n,f]),v((r,i)=>{if(i.escape)t();else if(i.upArrow)m(e=>{const t=Math.max(0,e-1);return t<p&&h(t),t});else if(i.downArrow)m(e=>{const t=Math.min(s.length-1,e+1);return t>=p+g&&h(t-g+1),t});else if(i.return){const t=s[u];if(!t)return;return void(t.isDirectory&&!n.trim()?o(d(t.path)):e(t.path))}});const w=s.slice(p,p+g);return P.createElement(x,{flexDirection:"column",paddingLeft:2},P.createElement(x,{marginBottom:1,flexDirection:"column"},P.createElement(C,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),P.createElement(C,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • Enter to select/open • Esc to close")),0===w.length?P.createElement(C,{color:"dim"},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):w.map((e,t)=>{const n=p+t,r=e.name;return P.createElement(C,{key:e.path,color:n===u?"white":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList"),Vt=[{command:"/resume",description:"Resume a past conversation"},{command:"/clear",description:"Clear the conversation"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"}],Ht=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=A(0),s=F(()=>{if(!n)return Vt;const e=n.toLowerCase();return Vt.map(t=>{const n=t.command.toLowerCase(),r=t.description.toLowerCase();let o=0;return n.startsWith("/"+e)?o+=100:n.includes(e)&&(o+=50),r.includes(e)&&(o+=25),{...t,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]);return I(()=>{o(0)},[n]),v((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>Math.max(0,e-1));else if(i.downArrow)o(e=>Math.min(s.length-1,e+1));else if(i.return){const t=s[r];return void(t&&e(t.command))}}),0===s.length?P.createElement(x,{flexDirection:"column",paddingLeft:2},P.createElement(C,{color:"dim"},"No commands found")):P.createElement(x,{flexDirection:"column",paddingLeft:2},P.createElement(x,{columnGap:4},P.createElement(x,{flexDirection:"column"},s.map((e,t)=>P.createElement(C,{key:e.command,color:r===t?"white":"dim"},e.command))),P.createElement(x,{flexDirection:"column"},s.map((e,t)=>P.createElement(C,{key:e.command,color:r===t?"white":"dim"},e.description)))))},"CommandMenu"),Yt=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=A([]),[o,s]=A(0),[i,a]=A(!0);I(()=>{c()},[]);const c=__name(async()=>{a(!0);const e=await vt.listSessions();r(e.slice(0,30)),a(!1)},"loadSessions");if(v((r,i)=>{i.escape?t():i.upArrow?s(e=>Math.max(0,e-1)):i.downArrow?s(e=>Math.min(n.length-1,e+1)):i.return&&n.length>0&&o<n.length&&e(n[o].id)}),i)return P.createElement(x,{flexDirection:"column",paddingLeft:2},P.createElement(C,{color:"gray"},"Loading sessions..."));if(0===n.length)return P.createElement(x,{flexDirection:"column",paddingLeft:2},P.createElement(C,{color:"gray"},"No previous sessions found"),P.createElement(C,{color:"dim",dimColor:!0},"Press ESC to go back"));const l=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),u=__name((e,t=45)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return P.createElement(x,{flexDirection:"column",paddingLeft:2},P.createElement(C,{color:"cyan",bold:!0},"Resume Session"),P.createElement(C,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),P.createElement(x,{marginTop:1}),P.createElement(x,{columnGap:2,marginBottom:1},P.createElement(x,{width:5},P.createElement(C,{color:"gray"}," ")),P.createElement(x,{width:13},P.createElement(C,{color:"gray"},"Modified")),P.createElement(x,{width:20},P.createElement(C,{color:"gray"},"Git Branch")),P.createElement(x,{width:11},P.createElement(C,{color:"gray"},"# Messages")),P.createElement(x,null,P.createElement(C,{color:"gray"},"Summary"))),P.createElement(x,{columnGap:2},P.createElement(x,{flexDirection:"column",width:5},n.map((e,t)=>P.createElement(C,{key:`sel-${t}`,color:o===t?"cyan":"gray"},o===t?`${Y.pointer} ${t+1}.`:` ${t+1}.`))),P.createElement(x,{flexDirection:"column",width:13},n.map((e,t)=>P.createElement(C,{key:`mod-${e.id}`,color:o===t?"white":"gray"},l(e.lastModified)))),P.createElement(x,{flexDirection:"column",width:20},n.map((e,t)=>P.createElement(C,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),P.createElement(x,{flexDirection:"column",width:11},n.map((e,t)=>P.createElement(C,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),P.createElement(x,{flexDirection:"column"},n.map((e,t)=>P.createElement(C,{key:`summary-${e.id}`,color:o===t?"white":"gray"},u(e.firstMessage))))))},"SessionsResumeTable"),Qt=__name(({usage:e})=>{if(!e)return null;const t=__name(e=>e>=1e3?`${Math.round(e/1e3)}K`:e.toString(),"formatNumber"),n=Math.min(e.current/e.limit*100,100),r=__name(e=>e>=90?"red":e>=70?"yellow":"gray","getColor");return P.createElement(x,{paddingRight:1},P.createElement(C,{color:r(n),dimColor:!0},n.toFixed(1),"% context used (",t(e.current),"/",t(e.limit),")"))},"ContextUsage");async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=te(n),s=await o.metadata();if(!s.width||!s.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const i=1200;let a,c,{width:l,height:u}=s;(l>i||u>i)&&(l>u?(u=Math.round(u*i/l),l=i):(l=Math.round(l*i/u),u=i)),t.includes("png")&&s.hasAlpha?(a=await o.resize(l,u,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(a=await o.resize(l,u,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const d=a.length;return{compressedBase64:a.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:d,compressionRatio:r/d}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}async function detectClipboardImage(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasImage())return null;let t=null;try{if(t=await e.default.getImageBase64(),!t){const n=e.default.getImageBase64();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}if(!t||0===t.length)return null;if(t.length>32e6)return console.log("Image too large:",t.length,"bytes"),null;try{const e=await compressImageForSharing(t,"image/png");return e?{data:e.compressedBase64,mediaType:e.mediaType}:(console.log("Failed to compress clipboard image"),null)}catch(e){return console.log("Failed to process clipboard image:",e),null}}catch(e){return null}}async function detectClipboardText(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasText())return null;let t=null;try{if(t=await e.default.getText(),!t){const n=e.default.getText();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}return t&&0!==t.length?t:null}catch(e){return null}}function processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};let r=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");return r=r.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),{isPasteStart:t,isPasteEnd:n,cleanedContent:r}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}__name(compressImageForSharing,"compressImageForSharing"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode");var Kt=__name(()=>P.createElement(x,{flexDirection:"column",paddingLeft:2},P.createElement(C,{color:"dim",bold:!0},"Available Shortcuts:"),P.createElement(x,{columnGap:4},P.createElement(x,{flexDirection:"column"},P.createElement(C,{color:"dim"},"! for bash mode"),P.createElement(C,{color:"dim"},"/ for commands"),P.createElement(C,{color:"dim"},"@ for file paths")),P.createElement(x,{flexDirection:"column"},P.createElement(C,{color:"dim"},"double tap esc to clear input"),P.createElement(C,{color:"dim"},"shift + ⏎ for newline"),P.createElement(C,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Zt=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:i,fileSearchQuery:c,setFileSearchQuery:l,onCommand:u,contextUsage:d,shareInfo:m,showShareNotification:p,unshareNotificationMessage:h,updateStatus:g,updateFailedInfo:f})=>{const[y,w]=A(0),[b,E]=A(!1),[S,k]=A(!1),[T,I]=A(!1),[R,M]=A(!1),[j,O]=A(""),[U,_]=A(!1),[N,L]=A(null),[B,z]=A([]),[W,q]=A([]),[G,J]=A(""),V=D(!1),[H,Q]=A(!1),K=$(()=>{n(""),k(!1),M(!1),O(""),_(!1),z([]),q([]),J(""),Q(!1),w(e=>e+1)},[n]),Z=$(e=>{if(0===e.length)return e;let t=e.length;for(;t>0&&/\s/.test(e[t-1]);)t--;for(;t>0&&!/\s/.test(e[t-1]);)t--;return e.slice(0,t)},[]),X=$(()=>{const t=Z(e);n(t),w(e=>e+1)},[e,Z,n]);function handlePastedContent(t){if(t.length>200){const r=`[Text#${B.length+1}]`;z(e=>[...e,t]),n(e+r),w(e=>e+1)}else n(e+t),w(e=>e+1)}v(async(t,r)=>{if(!r.ctrl&&!r.meta&&!r.shift){if(""===t)return void K();if(""===t)return void X()}if(r.meta&&r.delete)return V.current=!0,void X();if(r.meta&&r.backspace)K();else if(r.alt&&r.backspace)X();else{if(r.ctrl&&"w"===t)return V.current=!0,void X();if(r.meta&&"w"===t)return V.current=!0,void K();if(r.meta&&"v"===t||r.ctrl&&"v"===t){if(r.ctrl&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();if(r){const e=`[Image#${W.length+1}]`;q(e=>[...e,r]),n(t+e),w(e=>e+1)}else{const e=await detectClipboardText();e&&handlePastedContent(e)}return void(V.current=!0)}}else{if((r.ctrl||r.meta)&&"u"===t)return V.current=!0,void K();if(r.ctrl&&t)switch(t.toLowerCase()){case"k":case"a":return void K();case"z":return I(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100)}if(r.escape){if(U)return _(!1),n(G),void w(e=>e+1);const e=Date.now(),t=500;return N&&e-N<t?(K(),L(null)):(L(e),setTimeout(()=>L(null),t)),E(!1),void k(!1)}b&&(r.backspace||r.delete)&&0===e.length&&E(!1)}}}),__name(handlePastedContent,"handlePastedContent");const te=$(async t=>{const r=processBracketedPaste(t);if(r.isPasteStart&&!H){if(Q(!0),r.isPasteEnd){Q(!1);const t=await detectClipboardImage();if(t){const r=`[Image#${W.length+1}]`;q(e=>[...e,t]),n(e+r),w(e=>e+1)}else if(r.cleanedContent)handlePastedContent(r.cleanedContent);else{const e=await detectClipboardText();e&&handlePastedContent(e)}return}return}if(H&&!r.isPasteEnd)return;if(H&&r.isPasteEnd){Q(!1);const e=await detectClipboardImage();if(e){const t=`[Image#${W.length+1}]`;q(t=>[...t,e]),n(r.cleanedContent+t),w(e=>e+1)}else{const e=await detectClipboardText();e?handlePastedContent(e):r.cleanedContent&&handlePastedContent(r.cleanedContent)}return}if(r.isPasteEnd&&!r.isPasteStart)return;if(V.current)return void(V.current=!1);const o=1===t.length,a=t.slice(-1);if(o){if("?"===a&&!b)return E(!0),n(""),void w(e=>e+1);if("!"===a&&!S)return E(!1),k(!0),n(""),void w(e=>e+1);"/"!==a||R||(M(!0),O(""))}if(R){const e=t.lastIndexOf("/");if(-1!==e){const n=t.substring(e+1);O(n)}}if("@"!==a||s||(i(!0),l("")),s){const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1);l(n)}}b&&(t!==e||t.length<e.length)&&E(!1),0===t.length&&(k(!1),M(!1),O(""),_(!1),q([]),z([]),l(""),J(""),Q(!1)),n(t)},[b,e,n,s,i,S,H,W]),ne=$(async()=>{if(b)return void E(!1);let n=e.trim(),r=[];const o=W.length>0,s=B.length>0;if(!S&&o){const e=[];W.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!S&&s){let e=n;B.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:S?"bash":"user",images:r}),k(!1),M(!1),O(""),q([]),z([])},[t,b,e,S,W]),re=$(t=>{const r=a(process.cwd(),t);let o;if(s&&""!==c){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r:r}else o=`${e}${r}`;n(o),i(!1),l(""),w(e=>e+1)},[n,i,e,s,c,l]),oe=$(()=>{i(!1),l("")},[i,l]),se=$(t=>{"/resume"===t?(J(e),M(!1),O(""),_(!0),n(""),w(e=>e+1)):(M(!1),O(""),n(""),w(e=>e+1),u&&u(t))},[u,n,e]),ie=$(()=>{M(!1),O(""),n(""),w(e=>e+1)},[n]),ae=$(e=>{_(!1),n(""),J(""),w(e=>e+1),u&&u(`/resume:${e}`)},[u]),ce=$(()=>{_(!1),n(G),w(e=>e+1)},[G]),le=F(()=>!b&&0===e.length&&!S&&!U,[b,e,S,R,U]),ue=__name(()=>b||s||R||U||T?0:le||S?3:4,"getBottomMargin");return P.createElement(x,{width:"100%",flexDirection:"column",marginBottom:ue()},!U&&P.createElement(x,{borderStyle:"round",borderColor:S?"green":"gray",paddingX:1,paddingY:0,width:"100%"},P.createElement(C,{color:S?"green":"dim"},S?"!":Y.pointer),P.createElement(x,{flexGrow:1,paddingLeft:1},P.createElement(ee,{key:y,value:e,placeholder:o,onChange:te,onSubmit:()=>{s||R||U||ne()},showCursor:r}))),b&&P.createElement(Kt,null),T&&P.createElement(x,{paddingTop:1},P.createElement(C,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),s&&P.createElement(Jt,{onSelectFile:re,onClose:oe,searchQuery:c}),R&&P.createElement(Ht,{onSelectCommand:se,onClose:ie,searchQuery:j}),U&&P.createElement(Yt,{onSelectSession:ae,onClose:ce}),le&&P.createElement(x,{flexDirection:"row",justifyContent:"space-between",paddingLeft:2,paddingRight:2},P.createElement(C,{color:"dim"},"? for shortcuts"),P.createElement(x,{flexDirection:"row"},g&&P.createElement(x,{marginRight:2},P.createElement(C,{color:"green",dimColor:!0},`${Y.tick} Command Code updated: v${g.updatedFrom} ${Y.arrowRight} v${g.updatedTo}`)),f&&P.createElement(x,{marginRight:2},P.createElement(C,{color:"yellow",dimColor:!0},Y.info," Update available:"," ",f.currentVersion," ",Y.arrowRight," ",f.latestVersion)),P.createElement(Qt,{usage:d||null}))),S&&P.createElement(x,{paddingLeft:2},P.createElement(C,{color:"green"},"! for bash mode")),p&&m&&P.createElement(x,{paddingLeft:2},P.createElement(C,{color:"#E4CCFF"},"🔗 SHARED: ",m.url," (copied to clipboard)")),h&&P.createElement(x,{paddingLeft:2},P.createElement(C,{color:h.includes("NOT SHARED")?"red":"#E4CCFF"},h)))},"InputBox"),Xt=P.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,outputTokens:m=0,contextUsage:p,shareInfo:h,showShareNotification:g,unshareNotificationMessage:f,updateStatus:y,updateFailedInfo:w})=>{const[b,E]=A(0);return I(()=>{if(!t)return void E(0);const e=setInterval(()=>{E(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),P.createElement(x,{flexDirection:"column"},P.createElement(zt,{messages:e}),(t||n.isExecuting)&&P.createElement(Gt,{tokens:m,timeElapsed:b,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),P.createElement(Zt,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:p,shareInfo:h,showShareNotification:g,unshareNotificationMessage:f,updateStatus:y,updateFailedInfo:w}))}),en=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=k(),[r,o]=A([]),[s,i]=A(0),[a,c]=A(!0),[l,u]=A(0),d=30;I(()=>{m()},[]);const m=__name(async()=>{c(!0);const e=await vt.listSessions();o(e),c(!1)},"loadSessions");if(v((t,o)=>{o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<l&&u(t),t}):o.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=l+d&&u(t-d+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),a)return P.createElement(x,{flexDirection:"column",paddingLeft:2,paddingTop:1},P.createElement(C,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5),i=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:s<7?`${s} day${s>1?"s":""} ago`:1===i?"1 week ago":`${i} weeks ago`},"formatRelativeTime"),h=__name((e,t=50)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return P.createElement(x,{flexDirection:"column"},P.createElement(C,{color:"gray"},"No sessions available"));const g=r.slice(l,l+d),f=l;return P.createElement(x,{flexDirection:"column",paddingLeft:1},r.length>d&&P.createElement(x,{marginBottom:1},P.createElement(C,{color:"dim"},"Showing ",l+1,"-",Math.min(l+d,r.length)," ","of ",r.length," sessions",l>0&&" (↑ for more)",l+d<r.length&&" (↓ for more)")),P.createElement(x,{columnGap:2,marginBottom:1},P.createElement(x,{width:7},P.createElement(C,{color:"gray"}," ")),P.createElement(x,{width:13},P.createElement(C,{color:"gray"},"Modified")),P.createElement(x,{width:11},P.createElement(C,{color:"gray"},"# Messages")),P.createElement(x,{width:20},P.createElement(C,{color:"gray"},"Git Branch")),P.createElement(x,null,P.createElement(C,{color:"gray"},"Summary"))),P.createElement(x,{columnGap:2},P.createElement(x,{flexDirection:"column",width:7},g.map((e,t)=>{const n=f+t;return P.createElement(C,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${Y.pointer} ${n+1}.`:` ${n+1}.`)})),P.createElement(x,{flexDirection:"column",width:13},g.map((e,t)=>{const n=f+t;return P.createElement(C,{key:`mod-${e.id}`,color:s===n?"white":"gray"},p(e.lastModified))})),P.createElement(x,{flexDirection:"column",width:11},g.map((e,t)=>{const n=f+t;return P.createElement(C,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),P.createElement(x,{flexDirection:"column",width:20},g.map((e,t)=>{const n=f+t;return P.createElement(C,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),P.createElement(x,{flexDirection:"column"},g.map((e,t)=>{const n=f+t;return P.createElement(C,{key:`summary-${e.id}`,color:s===n?"white":"gray"},h(e.firstMessage))}))))},"SessionTable"),tn=__name(({onTrust:e,onExit:t})=>{const{exit:n}=k(),[r,o]=A(1),s=process.cwd().replace(process.env.HOME||"","~");return v((s,i)=>{i.upArrow||i.downArrow?o(1===r?2:1):i.return?1===r?e():(t(),n()):"1"===s?e():("2"===s||i.escape||i.ctrl&&"c"===s)&&(t(),n())}),P.createElement(x,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1},P.createElement(C,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),P.createElement(x,{marginTop:1},P.createElement(C,{color:"gray"},s)),P.createElement(x,{marginTop:1,flexDirection:"column"},P.createElement(C,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),P.createElement(x,{marginTop:1},P.createElement(C,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),P.createElement(x,{marginTop:1,flexDirection:"column"},P.createElement(x,null,P.createElement(C,{color:1===r?"cyan":"gray"},1===r?Y.pointer:" "," 1. Yes, proceed")),P.createElement(x,null,P.createElement(C,{color:2===r?"cyan":"gray"},2===r?Y.pointer:" "," 2. No, exit"))))},"TrustPrompt"),nn=class extends ne{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||i.join(e,".command-code","settings.local.json"),this.config=this.getDefaultConfig(),this.loadConfig()}getDefaultConfig(){return{enabled:!0,defaultScope:"session",autoApprove:{create:!1,edit:!1,delete:!1,execute:!1,shellCommands:!1},trustedPaths:[],trustedCommands:[],sessionPermissions:new Map,projectPermissions:new Map,sessionShellPermissions:new Map,projectShellPermissions:new Map}}async loadConfig(){try{const e=await n.readFile(this.configPath,"utf-8"),t=JSON.parse(e);t.permissions&&("acceptEdits"===t.permissions.defaultMode&&(this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0),t.permissions.allow&&t.permissions.allow.forEach(e=>{if(e.startsWith("Bash(")&&e.endsWith(")")){const t=e.slice(5,-1);this.config.trustedCommands.push(t)}}))}catch(e){}}async requestPermission(e){if(!this.config.enabled)return{allowed:!0};const t=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)?{allowed:!0}:this.config.sessionPermissions.has(t)?{allowed:this.config.sessionPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("permission-request",e,n=>{this.handleUserChoice(e,n).then(t)})})}async handleUserChoice(e,t){const n=e.action,r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionPermissions.set(n,!0);break;case"project":await this.createCommandCodeSettings(),this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getFileKey(e){const t=i.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=i.relative(this.projectRoot,e);return this.config.trustedPaths.some(n=>t.startsWith(n)||e.startsWith(n))}async requestShellPermission(e){if(!this.config.enabled)return{allowed:!0};const t=this.getCommandKey(e);return this.config.autoApprove.shellCommands||this.isTrustedCommand(e.command)?{allowed:!0}:this.config.projectShellPermissions.has(t)?{allowed:this.config.projectShellPermissions.get(t)||!1,scope:"project"}:this.config.sessionShellPermissions.has(t)?{allowed:this.config.sessionShellPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("shell-permission-request",e,n=>{this.handleShellUserChoice(e,n).then(t)})})}async handleShellUserChoice(e,t){const n=this.getCommandKey(e),r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionShellPermissions.set(n,!0);break;case"project":await this.addCommandToSettings(e.command),this.config.projectShellPermissions.set(n,!0)}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getCommandKey(e){return`${e.command.split(" ")[0]}:${e.args?e.args.join(" "):""}`.trim()}isTrustedCommand(e){return this.config.trustedCommands.some(t=>{if(t===e)return!0;if(t.endsWith(":*")){const n=t.slice(0,-2);return e===n||e.startsWith(n+" ")}return e.startsWith(t)})}clearSessionPermissions(){this.config.sessionPermissions.clear(),this.config.sessionShellPermissions.clear()}clearProjectPermissions(){this.config.projectPermissions.clear(),this.config.projectShellPermissions.clear()}setAutoApprove(e,t){this.config.autoApprove[e]=t}addTrustedPath(e){this.config.trustedPaths.includes(e)||this.config.trustedPaths.push(e)}removeTrustedPath(e){const t=this.config.trustedPaths.indexOf(e);t>-1&&this.config.trustedPaths.splice(t,1)}addTrustedCommand(e){this.config.trustedCommands.includes(e)||this.config.trustedCommands.push(e)}removeTrustedCommand(e){const t=this.config.trustedCommands.indexOf(e);t>-1&&this.config.trustedCommands.splice(t,1)}setEnabled(e){this.config.enabled=e}getConfig(){return{...this.config}}async createCommandCodeSettings(){const e=i.join(this.projectRoot,".command-code"),t=i.join(e,"settings.local.json");try{await n.mkdir(e,{recursive:!0});let r={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await n.readFile(t,"utf-8"),o=JSON.parse(e);o.permissions&&o.permissions.allow&&(r.permissions.allow=[...new Set([...o.permissions.allow,...r.permissions.allow])]),o.permissions&&o.permissions.deny&&(r.permissions.deny=o.permissions.deny)}catch(e){}await n.writeFile(t,JSON.stringify(r,null,2),"utf-8")}catch(e){console.error("Failed to create .command-code settings:",e)}}async addCommandToSettings(e){const t=i.join(this.projectRoot,".command-code"),r=i.join(t,"settings.local.json"),o=`Bash(${e.split(" ")[0]}:*)`;try{let e;await n.mkdir(t,{recursive:!0});try{const t=await n.readFile(r,"utf-8");e=JSON.parse(t)}catch(t){e={permissions:{allow:[],deny:[],defaultMode:"ask"}}}e.permissions||(e.permissions={allow:[],deny:[],defaultMode:"ask"}),e.permissions.allow||(e.permissions.allow=[]),e.permissions.allow.includes(o)||e.permissions.allow.push(o),await n.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .command-code settings:",e)}}},rn=__name((e={})=>{const[t,n]=A(null),[r,o]=A(null),[s,i]=A(!1);return I(()=>{const t=e.projectRoot||process.cwd(),r=new nn(t);return r.on("permission-request",(t,n)=>{o(t),i(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),i(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:$(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:$(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:$(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),i(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),i(!1)}},[t]),clearSessionPermissions:$(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:$(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:$((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:$(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions"),on=__name(({request:e,onResponse:t})=>{const[n]=A(0),r=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, for this session only",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"Yes, and always allow modifying files in this project",value:"yes-project",description:"Allow and remember for this project",scope:"project"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],o=__name(e=>{const n=r.find(t=>t.value===e.value);n&&t(n)},"handleSelect"),s=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),a=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const t=i.basename(e.filePath),n=i.relative(process.cwd(),e.filePath);return n&&!n.startsWith("../")&&n.length<50?n:t||e.filePath}catch{return e.filePath}},"getDisplayPath"),c=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return P.createElement(x,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},P.createElement(x,{marginBottom:1},P.createElement(C,{bold:!0,color:"yellow"},c())),P.createElement(x,{marginBottom:1},P.createElement(C,{bold:!0},"Do you want to ",s()," ",P.createElement(C,{color:"cyan"},a()),"?")),P.createElement(re,{items:r.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:({isSelected:e})=>P.createElement(C,{color:"cyan"},e?Y.pointer:" "),itemComponent:({label:e,isSelected:t})=>P.createElement(C,{color:t?"cyan":"white"},e.includes("(")?P.createElement(P.Fragment,null,e.split("(")[0],P.createElement(C,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),sn=__name(({request:e,onResponse:t})=>{const[n]=A(0),r=__name(()=>e.command.split(" ")[0],"getCommandName"),o=__name(()=>e.workingDirectory||process.cwd(),"getProjectPath"),s=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, for this session only",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:`Yes, and don't ask again for ${r()} commands in ${o()}`,value:"yes-project",description:"Allow and remember for this project",scope:"project"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],i=__name(e=>{const n=s.find(t=>t.value===e.value);n&&t(n)},"handleSelect"),a=__name(()=>{const t=e.args&&e.args.length>0?`${e.command} ${e.args.join(" ")}`:e.command;return t.length>60?t.substring(0,57)+"...":t},"getCommandDisplay");return P.createElement(x,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},P.createElement(x,{marginBottom:1},P.createElement(C,{bold:!0,color:"yellow"},"Execute Shell Command")),P.createElement(x,{marginBottom:1},P.createElement(C,{bold:!0},"Command Code needs to execute ",P.createElement(C,{color:"cyan"},a()),".")),e.workingDirectory&&P.createElement(x,{marginBottom:1},P.createElement(C,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&P.createElement(x,{marginBottom:1},P.createElement(C,{color:"gray",italic:!0},e.description)),P.createElement(re,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:i,initialIndex:n,indicatorComponent:({isSelected:e})=>P.createElement(C,{color:"cyan"},e?Y.pointer:" "),itemComponent:({label:e,isSelected:t})=>P.createElement(C,{color:t?"cyan":"white"},e)}))},"ShellPermissionPrompt"),an={name:"command-code",version:"0.0.4-alpha.3",description:"Command Code — Coding Agent by Langbase",type:"module",main:"dist/index.mjs",bin:{cmd:"dist/index.mjs"},scripts:{build:"tsup","build:obfuscated":"tsup --config tsup.config.obfuscated.ts","build:balanced":"tsup --config tsup.config.balanced.ts","build:bun":"bun run build.bun.js","build:bun:exe":"bun build ./src/index.ts --compile --outfile dist/command-code","build:pkg":"pnpm build && pkg dist/index.cjs -t node18-macos-x64,node18-linux-x64,node18-win-x64 --out-path dist/binaries",dev:"tsup --watch",typecheck:"tsc --noEmit",start:"node dist/index.js",test:"vitest run",prepublishOnly:"pnpm run build:obfuscated","publish:prod":"pnpm run build:obfuscated && npm publish --access public","test:watch":"vitest","test:coverage":"vitest run --coverage"},keywords:["command","command code","langbase","coding agent","ai"],author:{name:"Langbase",url:"https://Langbase.com/docs"},license:"UNLICENSED",files:["dist"],private:!1,publishConfig:{access:"public"},packageManager:"pnpm@10.8.1",dependencies:{"@anthropic-ai/sdk":"^0.60.0","@clack/core":"^0.5.0","@clack/prompts":"^0.11.0","@crosscopy/clipboard":"^0.2.8","@sindresorhus/slugify":"^2.2.1","@types/uuid":"^10.0.0",chalk:"^5.5.0",commander:"^14.0.0",dedent:"^1.6.0",diff:"^8.0.2",figures:"^6.1.0",glob:"^11.0.3",ink:"^6.1.0","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",langbase:"^1.2.3","log-symbols":"^7.0.1",marked:"^16.1.2","marked-terminal":"^7.3.0",minimatch:"^10.0.3",react:"^19.1.1","react-devtools-core":"^4.28.5","registry-auth-token":"^5.1.0","registry-url":"^7.2.0",sharp:"^0.34.3","strip-ansi":"^7.1.0",uuid:"^11.1.0",zod:"^4.0.17"},devDependencies:{"@types/marked":"^6.0.0","@types/marked-terminal":"^6.1.1","@types/node":"^24.2.0","@types/react":"^19.0.3","javascript-obfuscator":"^4.1.1",pkg:"^5.8.1","rollup-plugin-obfuscator":"^1.1.0",terser:"^5.43.1",tsup:"^8.5.0",tsx:"^4.20.3",vitest:"^3.2.4"}},cn=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole"),{setText:ln}=J,un=__name(({resume:e=!1,continue:t=!1,updateStatus:n,updateFailedInfo:r})=>{const{exit:o}=k(),[s,i]=A(""),[a,c]=A("Ready..."),[l,u]=A(n),{stdout:d}=T(),[m,p]=A(!1),[h,g]=A(0),{executeBash:f,executionState:y}=Qe(),[w,b]=A(""),[E,C]=A([]),[S,$]=A(!1),[F,R]=A([]),[M,j]=A(crypto.randomUUID()),[O,U]=A(!1),[_,N]=A(!1),[L,B]=A(!1),[z,W]=A(!1),[q,G]=A(!0),[J,V]=A(!1),[H,Y]=A(0),[Q,K]=A(null),[Z,X]=A(null),ee=D(Z);I(()=>{ee.current=Z},[Z]);const[te,ne]=A(!1),[re,oe]=A(""),se=D([]),ie=D(null),[ae,ce]=A(null),{requestShellPermission:le,service:ue,respondToPrompt:de,clearSessionPermissions:me,setEnabled:pe}=rn({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{ce({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),ie.current&&c("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{ce({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),ie.current&&c("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?c("Permission granted"):c("Permission denied")},"onPermissionResponse")});I(()=>{(async()=>{if(await vt.isProjectInitialized())if(W(!0),G(!1),t){const e=await vt.listSessions();if(e.length>0){const t=e[0];ve(t.id)}}else e&&U(!0);else B(!0),G(!1)})()},[e,t,o]),I(()=>{se.current=F},[F]),I(()=>{if(!S)return;const e=setInterval(()=>{c(Je())},7e3);return()=>clearInterval(e)},[S]),v((e,t)=>{if(t.ctrl&&"c"===e&&o(),t.escape)if(ae)de({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),ae.resolve(!1),ce(null),c("Permission denied");else if(S&&ie.current){ie.current.interrupt(!0),$(!1),c("Interrupted by user");const e=Oe("Interrupted by user");C(t=>[...t,e])}t.meta||t.ctrl}),I(()=>{const e=__name(()=>{cn(),g(e=>e+1)},"handleResize");if(d)return d.on("resize",e),()=>{d.off("resize",e)}},[d]),I(()=>{ie.current||!z||O||_||(ie.current=new _t({onFeedUpdate:__name(e=>{C(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...se.current];return se.current=[],R([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Y(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{K(e)},"onContextUsageUpdate"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&ue){const e={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${t.args?.join(" ")||""}`};return ue.requestShellPermission(e).then(e=>e.allowed)}if(ue){const n={action:e.includes("edit")?"edit":e.includes("write")?"create":e.includes("delete")?"delete":"edit",filePath:t.filePath||t.file_path||t.path||t.absolutePath||"unknown",description:t.description||`${e} operation`};return ue.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=ee.current;return e?{sessionId:M,secret:e.secret}:null},"getShareInfo")},M),(async()=>{await Ee()})())},[M,O,_,z]);const he=D(!1),ge=__name(async({role:e,input:t,images:n})=>{if(t.length)if(l&&u(null),Y(0),"bash"===e){if(he.current)return;he.current=!0;const e=Ne(t);C([...E,e]),i(""),await f(t,e=>{C(e)}),he.current=!1}else{if(S)return R(e=>[...e,t]),void i("");if(he.current)return;he.current=!0,$(!0),c(Je()),i("");try{ie.current&&await ie.current.sendMessage(t,n)}catch(e){"Interrupted by user"===e.message||"InterruptedError"===e.name||"AbortError"===e.name||(console.error("Chat error:",e),c("Error occurred"))}finally{$(!1),"Interrupted by user"!==a&&"Permission denied"!==a&&c("Ready..."),he.current=!1}}},"handleSubmit"),fe=__name(()=>{const e=Vt.filter(e=>"/help"!==e.command).map(e=>`**${e.command}** - ${e.description}`).join("\n"),t=`**Command Code v${an.version}**\n\nAlways review Command Code's responses, especially when running code. Command Code has read access to files in the current directory and can run commands and edit files with your permission.\n\n**Usage Modes:**\n• REPL: **cmd** (interactive session)\n\nRun **cmd -h** for all command line options\n\n**Common Tasks:**\n• Ask questions about your codebase > How does foo.ts work?\n• Edit files > Update bar.ts to...\n• Fix errors > Fix build error...\n• Run commands > /help\n• Run bash commands > !ls\n\n**Interactive Mode Commands:**\n${e}`;C(e=>[...e,Le(t)])},"handleHelpCommand"),we=__name(()=>{if(C([]),cn(),ie.current){ie.current=null;const e=crypto.randomUUID();j(e),ie.current=new _t({onFeedUpdate:__name(e=>{C(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...se.current];return se.current=[],R([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Y(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{K(e)},"onContextUsageUpdate"),getShareInfo:__name(()=>{const t=ee.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e),Ee().catch(console.error)}g(e=>e+1),K(null),Y(0)},"handleClearCommand"),be=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await ve(t)}switch(e){case"/exit":o();break;case"/clear":we();break;case"/help":fe();break;case"/permissions":c("Permissions are enabled");break;case"/permissions:enable":pe(!0),c("File edit permissions enabled");break;case"/permissions:disable":pe(!1),c("File edit permissions disabled");break;case"/permissions:clear":me(),c("Session permissions cleared");break;case"/share":xe();break;case"/unshare":Ce()}},"handleCommand"),Ee=__name(async()=>{const e=ie.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&X({url:t.url,secret:t.secret})}},"loadShareInfo"),xe=__name(async()=>{if(M){if(Z)return await ln(Z.url),c(""),ne(!0),void setTimeout(()=>{ne(!1)},3e3);try{c("Creating share link...");const e=ie.current?.getMessages()||[],t=Ot.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=getApiBaseUrl(),r=await fetch(`${n}${ye.CREATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:M,messages:t})});if(!r.ok)throw new Error(`Failed to create share: ${r.statusText}`);const o=await r.json(),s={url:o.url,secret:o.secret};X(s);const i=ie.current?.getSessionManager();i&&await i.saveShareInfo({url:o.url,secret:o.secret}),await ln(o.url),c(""),ne(!0),setTimeout(()=>{ne(!1)},5e3)}catch(e){c(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else c("No active session to share")},"handleShareCommand"),Ce=__name(async()=>{if(M){if(!Z)return oe("🔓 NOT SHARED: Session is not currently shared"),void setTimeout(()=>oe(""),5e3);try{c("Removing share link...");const e=getApiBaseUrl(),t=await fetch(`${e}${ye.DELETE}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:M,secret:Z.secret})});if(!t.ok)throw new Error(`Failed to unshare: ${t.statusText}`);const n=ie.current?.getSessionManager();n&&await n.deleteShareInfo(),oe("🔓 UNSHARED: Sharing has stopped"),c(""),X(null),setTimeout(()=>{oe("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;c(t),setTimeout(()=>c(""),5e3)}}else c("No active session to unshare")},"handleUnshareCommand"),ve=__name(async e=>{try{C([]),ie.current=null,j(e),U(!1),N(!0),await new Promise(e=>setTimeout(e,100)),ie.current=new _t({onFeedUpdate:__name(e=>{C(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...se.current];return se.current=[],R([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Y(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{K(e)},"onContextUsageUpdate"),getShareInfo:__name(()=>{const t=ee.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const t=await ie.current.loadSession(e);await Ee(),C(t),cn(),g(e=>e+1)}catch(e){console.error("Failed to load session:",e),U(!0),j(crypto.randomUUID())}},"handleSelectSession"),Se=__name(async()=>{C([]),ie.current=null,j(crypto.randomUUID()),U(!1),N(!1)},"handleNewSession"),ke=__name(async()=>{try{await vt.initializeProject(),B(!1),e?(console.log("No conversations found to resume."),V(!0),o()):W(!0)}catch(e){console.error("Failed to initialize project:",e),B(!1),V(!0),o()}},"handleTrust"),Te=__name(()=>{o()},"handleNoTrust");if(J)return null;if(L)return P.createElement(tn,{onTrust:ke,onExit:Te});if(q)return null;if(O)return P.createElement(en,{onSelectSession:ve,onNewSession:Se});if(!z)return null;if(ae){if("shell_command"===ae.toolName){const e=ae.params;return P.createElement(x,{flexDirection:"column",width:"100%"},P.createElement(Bt,{staticKey:h,feed:E,showHeader:!0}),P.createElement(x,{marginY:1},P.createElement(sn,{request:e,onResponse:e=>{de(e);const t="no"!==e.value;ae.resolve(t),ce(null),c(t?"Shell command allowed":"Shell command denied")}})))}{const e={action:ae.toolName.includes("edit")?"edit":ae.toolName.includes("write")?"create":ae.toolName.includes("delete")?"delete":"edit",filePath:ae.params.filePath||ae.params.file_path||ae.params.path||ae.params.absolutePath||ae.params.notebook_path||"unknown",description:`Allow ${ae.toolName} operation`,newContent:ae.params.new_content||ae.params.content};return P.createElement(x,{flexDirection:"column",width:"100%"},P.createElement(Bt,{staticKey:h,feed:E,showHeader:!0}),P.createElement(x,{marginY:1},P.createElement(on,{request:e,onResponse:e=>{de(e);const t="no"!==e.value;ae.resolve(t),ce(null),c(t?"File operation allowed":"File operation denied")}})))}}return P.createElement(x,{flexDirection:"column",width:"100%"},P.createElement(Bt,{staticKey:h,feed:E,showHeader:!0}),P.createElement(Xt,{queuedMessages:F,isProcessing:S,executionState:y,status:a,input:s,setInput:i,onSubmit:ge,showFileList:m,setShowFileList:p,fileSearchQuery:w,setFileSearchQuery:b,onCommand:be,outputTokens:H,contextUsage:Q,shareInfo:Z,showShareNotification:te,unshareNotificationMessage:re,updateStatus:l,updateFailedInfo:r}))},"InteractiveCLI"),dn=ie(M.writeFile),mn=ie(M.mkdir),pn=ie(M.readFile),hn=__name((e,t)=>e.localeCompare(t,"en-US",{numeric:!0}),"compareVersions"),gn=__name(e=>encodeURIComponent(e).replace(/^%40/,"@"),"encode"),fn=__name(async(e,t)=>{const n=h(),r=l(n,"update-check");M.existsSync(r)||await mn(r);let o=`${e.name}-${t}.json`;return e.scope&&(o=`${e.scope}-${o}`),l(r,o)},"getFile"),yn=__name(async(e,t,n)=>{if(M.existsSync(e)){const r=await pn(e,"utf8"),{lastUpdate:o,latest:s}=JSON.parse(r);if(o+n>t)return{shouldCheck:!1,latest:s}}return{shouldCheck:!0,latest:null}},"evaluateCache"),wn=__name(async(e,t,n)=>{const r={latest:t,lastUpdate:n};await dn(e,JSON.stringify(r),"utf8")},"updateCache"),bn=__name((e,t)=>new Promise((n,r)=>{const o={host:e.hostname,path:e.pathname,port:e.port?parseInt(e.port,10):void 0,headers:{accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"},timeout:2e3};t&&(o.headers.authorization=`${t.type} ${t.token}`);const s=("https:"===e.protocol?ce:ae).get(o,e=>{const{statusCode:t}=e;if(200!==t){const n=new Error(`Request failed with code ${t}`);return n.code=t,r(n),void e.resume()}let o="";e.setEncoding("utf8"),e.on("data",e=>{o+=e}),e.on("end",()=>{try{const e=JSON.parse(o);n(e)}catch(e){r(e)}})});s.on("error",r),s.on("timeout",r)}),"loadPackage"),En=__name(async(e,t)=>{const n=le(e.scope),r=new se(e.full,n);let o=null;try{o=await bn(r)}catch(e){if(!e.code||!String(e.code).startsWith("4"))throw e;{const t=ue(n,{recursive:!0});if(!t)throw e;o=await bn(r,t)}}if(!o)throw new Error("Failed to load package specification");const s=o["dist-tags"][t];if(!s)throw new Error(`Distribution tag ${t} is not available`);return s},"getMostRecent"),xn={interval:36e5,distTag:"latest"},Cn=__name(e=>{const t={full:gn(e),scope:void 0,name:""};if(e.includes("/")){const n=e.split("/");t.scope=n[0],t.name=n[1]}else t.scope=void 0,t.name=e;return t},"getDetails"),vn=__name(async(e,t)=>{if("object"!=typeof e)throw new Error("The first parameter should be your package.json file content");const n=Cn(e.name),r=Date.now(),{distTag:o,interval:s}=Object.assign({},xn,t),i=await fn(n,o);let a=null,c=!0;return({shouldCheck:c,latest:a}=await yn(i,r,s)),c&&(a=await En(n,o),await wn(i,a,r)),-1===hn(e.version,a)?{latest:a,fromCache:!c}:null},"default"),Sn=i.join(p.homedir(),".command-code"),kn=i.join(Sn,"update-status.json"),Tn=i.join(Sn,"update-failed.json");function ensureCommandCodeDir(){j.existsSync(Sn)||j.mkdirSync(Sn,{recursive:!0})}async function checkForUpdateAvailable(){try{const e=await vn(an,{interval:864e5});return e?{currentVersion:an.version,latestVersion:e.latest,updateAvailable:!0}:{currentVersion:an.version,latestVersion:an.version,updateAvailable:!1}}catch(e){return null}}async function performAutoUpdate(){const e=await checkForUpdateAvailable();if(!e||!e.updateAvailable)return{success:!1};console.log(`Updating command-code from v${e.currentVersion} to v${e.latestVersion}...`);try{g("npm update -g command-code",{stdio:"inherit"}),ensureCommandCodeDir();const t={updatedFrom:e.currentVersion,updatedTo:e.latestVersion,updatedAt:Date.now()};return j.writeFileSync(kn,JSON.stringify(t,null,2)),console.log(`\nSuccessfully updated to version ${e.latestVersion}\n`),console.log("Please restart command-code to use the new version."),{success:!0}}catch(t){console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm update -g command-code"),ensureCommandCodeDir();const n={currentVersion:e.currentVersion,latestVersion:e.latestVersion,failedAt:Date.now()};return j.writeFileSync(Tn,JSON.stringify(n,null,2)),{success:!1,updateInfo:e}}}function getUpdateStatus(){try{if(ensureCommandCodeDir(),j.existsSync(kn)){const e=JSON.parse(j.readFileSync(kn,"utf-8"));return j.unlinkSync(kn),e}}catch(e){}return null}function getFailedUpdateInfo(){try{if(ensureCommandCodeDir(),j.existsSync(Tn)){const e=JSON.parse(j.readFileSync(Tn,"utf-8"));return j.unlinkSync(Tn),{currentVersion:e.currentVersion,latestVersion:e.latestVersion}}}catch(e){}return null}__name(ensureCommandCodeDir,"ensureCommandCodeDir"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(performAutoUpdate,"performAutoUpdate"),__name(getUpdateStatus,"getUpdateStatus"),__name(getFailedUpdateInfo,"getFailedUpdateInfo");var Pn=__name(async(e={})=>{process.stdin.isTTY||(console.error("Error: Interactive mode requires a TTY terminal."),console.error("Please run this command directly in your terminal, not through a pipe or redirect."),process.exit(1));const t=getUpdateStatus(),n=getFailedUpdateInfo();enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()}),(e.resume||e.continue)&&await vt.isProjectInitialized()&&0===(await vt.listSessions()).length&&(console.log("No conversations found to resume."),process.exit(0)),S(P.createElement(un,{resume:e.resume,continue:e.continue,updateStatus:t,updateFailedInfo:n}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})},"interactive"),{red:An,yellow:In}=me,Dn=__name((e="ERROR: ",t,n=!0,r=!0)=>{if(t){if(console.log(),n?(console.log(`${pe.error} ${An(e)}`),console.log(`${pe.error} ${An("ERROR →")} ${t.name}`),console.log(`${pe.info} ${An("REASON →")} ${t.message}`),console.log(`${pe.info} ${An("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${pe.warning} ${In(e)}\n`),!r)return!1;process.exit(0)}},"handleError"),$n=__name(()=>{process.on("unhandledRejection",e=>{Dn(de`CRITICAL: Unhandled Promise Rejection!
3
- This is an unexpected error. Please file a bug report at https://github.com/LangbaseInc/command-code/issues/new`,e)})},"handleUnhandledErrors");function getPackageJson(){const e=import.meta.url,t=oe(e),n=c(t);return JSON.parse(O(l(n,"./../package.json"),"utf8"))}async function checkAuthAndPromptLogin(){try{if(!await Ee.get("anthropic")){console.log(me.white(Lt)),console.log(me.dim("Welcome to Command by Langbase. Agentic coding agent.")),console.log(""),console.log(`${H.warning} Authentication required to use Command Code`),console.log("You need to sign in with your Claude Pro/Max subscription or API key."),console.log("");const e=b.createInterface({input:process.stdin,output:process.stdout}),t=await e.question(`Would you like to sign in now? ${me.dim("(y/n)")}: `);e.close();const n=t.trim().toLowerCase();if(""!==n&&"y"!==n&&"yes"!==n)return console.log(""),console.log(`${H.info} You can authenticate later by running: cmd auth login`),!1;console.log(""),console.log(`${H.arrowUp} Running: cmd auth login`),console.log("");try{return g("cmd auth login",{stdio:"inherit",cwd:process.cwd()}),await Ee.get("anthropic")?(console.log(""),console.log(`${H.tick} Authentication successful! Starting Command Code...`),console.log(""),!0):(console.log(""),console.log(`${H.cross} Authentication failed. Please try again with: cmd auth login`),!1)}catch(e){return console.log(""),console.log(`${H.cross} Login command failed. Please run: cmd auth login`),!1}}return!0}catch(e){return console.error("Error checking authentication:",e),!1}}__name(getPackageJson,"getPackageJson"),__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var Fn=getPackageJson(),Rn=process.cwd();global.COMMAND_CODE_CWD=Rn;var Mn=new ge("CommandCode");$n(),(async()=>{(await performAutoUpdate()).success&&process.exit(0);const t=new e;async function commanderAction(e){switch(await checkAuthAndPromptLogin()||process.exit(1),!0){case e.resume:Pn({resume:!0});break;case e.continue:Pn({continue:!0});break;default:Pn()}}__name(commanderAction,"commanderAction"),t.name(Fn.name).description(Fn.description||"Command Code — Coding Agent by Langbase").version(Fn.version).option("-r, --resume","Resume a conversation").option("-c, --continue","Continue the last conversation").action(commanderAction),t.addCommand(Se),t.addCommand(Ce),t.addCommand(ke),t.hook("preAction",()=>{Mn.debug("Command starting...")}),t.hook("postAction",()=>{Mn.debug("Command completed.")}),t.parse()})();
2
+ import{Command as e}from"commander";import t,{mainSymbols as n}from"figures";import*as r from"fs/promises";import o,{mkdir as s,writeFile as i}from"fs/promises";import*as a from"path";import c,{relative as l,dirname as u,join as d,isAbsolute as m,resolve as h}from"path";import*as p from"os";import g from"os";import{execSync as f,spawn as y}from"child_process";import{z as w}from"zod";import b from"crypto";import E from"readline/promises";import{Static as x,Box as C,Text as v,useInput as S,render as k,useApp as T,useStdout as P}from"ink";import $,{useState as A,useEffect as I,useRef as D,useCallback as F,useMemo as R}from"react";import M from"@anthropic-ai/sdk";import*as j from"fs";import O,{readFileSync as _,promises as U,constants as N,existsSync as L,readdirSync as B,statSync as z}from"fs";import{minimatch as W}from"minimatch";import{glob as q}from"glob";import G from"@sindresorhus/slugify";import{MessageStream as J}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import V from"@crosscopy/clipboard";import H from"ink-gradient";import{setOptions as K,parse as Y}from"marked";import Q from"marked-terminal";import*as Z from"diff";import X from"ink-text-input";import ee from"sharp";import{EventEmitter as te}from"events";import ne from"ink-select-input";import re from"semver";import{fileURLToPath as oe}from"url";import se from"dedent";import ie from"chalk";import ae from"log-symbols";var ce=Object.defineProperty,__name=(e,t)=>ce(e,"name",{value:t,configurable:!0}),le=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${t.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${t.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${t.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${t.warning} ${e}`)}debug(e){process.env.DEBUG&&console.log(`[${this.prefix}] ${t.bullet} ${e}`)}};function formatDate(e=new Date){return e.toISOString().split("T")[0]}function parseJSON(e){try{return JSON.parse(e)}catch{return null}}__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON");var ue="/alpha/generate",de={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",DATA:"/alpha/share/data",APPEND:"/alpha/share/append",CONNECT:"/alpha/share/connect"},me=new le("Config"),he=a.join(p.homedir(),".command-code-config.json");async function loadConfig(){try{return parseJSON(await r.readFile(he,"utf-8"))||{}}catch{return{}}}async function saveConfig(e){await r.writeFile(he,JSON.stringify(e,null,2))}__name(loadConfig,"loadConfig"),__name(saveConfig,"saveConfig");var pe,ge,fe=new e("config").description("Manage CLI configuration").addCommand(new e("get").description("Get a configuration value").argument("<key>","Configuration key").action(async e=>{const t=(await loadConfig())[e];void 0!==t?me.info(`${e}: ${JSON.stringify(t)}`):me.warn(`Key "${e}" not found in configuration`)})).addCommand(new e("set").description("Set a configuration value").argument("<key>","Configuration key").argument("<value>","Configuration value").action(async(e,t)=>{const n=await loadConfig();let r=t;"true"===t?r=!0:"false"===t?r=!1:isNaN(Number(t))||(r=Number(t)),n[e]=r,await saveConfig(n),me.success(`Set ${e} = ${JSON.stringify(r)}`)})).addCommand(new e("list").description("List all configuration values").action(async()=>{const e=await loadConfig();0===Object.keys(e).length?me.info("No configuration values set"):(me.info("Current configuration:"),Object.entries(e).forEach(([e,t])=>{console.log(` ${e}: ${JSON.stringify(t)}`)}))})).addCommand(new e("reset").description("Reset all configuration").action(async()=>{await saveConfig({}),me.success("Configuration reset successfully")})),ye=new le("Info"),we=new e("info").description("Display system information").option("-v, --verbose","Show verbose output").action(e=>{if(ye.info("System Information:"),console.log("-------------------"),console.log(`${t.info} Date: ${formatDate()}`),console.log(`${t.info} Platform: ${p.platform()}`),console.log(`${t.info} Architecture: ${p.arch()}`),console.log(`${t.info} CPUs: ${p.cpus().length}`),console.log(`${t.info} Memory: ${Math.round(p.totalmem()/1024/1024/1024)} GB`),console.log(`${t.info} Home Directory: ${p.homedir()}`),e.verbose){console.log("\nDetailed CPU Information:"),p.cpus().forEach((e,t)=>{console.log(` CPU ${t}: ${e.model} @ ${e.speed} MHz`)}),console.log("\nNetwork Interfaces:");const e=p.networkInterfaces();Object.keys(e).forEach(t=>{const n=e[t];n&&n.forEach(e=>{"IPv4"!==e.family||e.internal||console.log(` ${t}: ${e.address}`)})})}ye.success("Information displayed successfully!")});async function loginAction(){try{console.log(`${t.info} Starting Anthropic OAuth login…\n`);const{url:e,verifier:n,state:r}=ge.createAuthorizationUrl();console.log("Go to:",e),console.log("");try{"darwin"===process.platform?f(`open "${e}"`,{stdio:"ignore"}):"win32"===process.platform?f(`start "${e}"`,{stdio:"ignore"}):f(`xdg-open "${e}"`,{stdio:"ignore"}),console.log(`${t.tick} Browser opened automatically`)}catch{console.log(`${t.info} Please copy and paste the URL above into your browser`)}console.log("");const o=E.createInterface({input:process.stdin,output:process.stdout}),s=await o.question("After authorizing, paste the authorization code here: ");o.close(),s.trim()||(console.log(`${t.cross} No authorization code provided`),process.exit(1));const i=s.split("#")[0].trim();console.log(`\n${t.circleFilled} Exchanging code for tokens…`),await ge.exchangeCodeForTokens(i,n,r),console.log(`${t.tick} Login successful!`),console.log("OAuth tokens saved to ~/.command-code/auth.json")}catch(e){console.error(`${t.cross} Login failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function logoutAction(){try{if(console.log(`${t.circleFilled} Removing authentication…`),!await pe.get("anthropic"))return void console.log(`${t.info} Not currently authenticated`);await pe.remove("anthropic"),console.log(`${t.tick} Logged out successfully`)}catch(e){console.error(`${t.cross} Logout failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function statusAction(){try{const e=await pe.get("anthropic");if(!e)return console.log(`${t.warning} Not authenticated`),void console.log("Run 'cmd auth login' to authenticate with Anthropic");if(console.log(`${t.tick} Authenticated with Anthropic`),console.log("Type:","oauth"===e.type?"OAuth (Claude Pro/Max)":"API Key"),"oauth"===e.type){const n=e.expires<Date.now(),r=new Date(e.expires).toLocaleString();n?console.log(`${t.circleFilled} Token expired:`,r,"(will auto-refresh on next use)"):console.log(`${t.tick} Token expires:`,r)}}catch(e){console.error(`${t.cross} Status check failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}(e=>{e.OAuth=w.object({type:w.literal("oauth"),refresh:w.string(),access:w.string(),expires:w.number()}),e.ApiKey=w.object({type:w.literal("api"),key:w.string()}),e.Info=w.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const t=__name(()=>c.join(g.homedir(),".command-code"),"getAuthDir"),n=__name(()=>c.join(t(),"auth.json"),"getAuthFile");async function get(e){try{const t=await o.readFile(n(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,r){const s=t(),i=n();await o.mkdir(s,{recursive:!0});let a={};try{const e=await o.readFile(i,"utf-8");a=JSON.parse(e)}catch{}a[e]=r,await o.writeFile(i,JSON.stringify(a,null,2)),await o.chmod(i,384)}async function remove(e){const t=n();try{const n=await o.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await o.unlink(t):(await o.writeFile(t,JSON.stringify(r,null,2)),await o.chmod(t,384))}catch{}}async function list(){try{const e=await o.readFile(n(),"utf-8");return JSON.parse(e)}catch{return{}}}e.get=get,__name(get,"get"),e.set=set,__name(set,"set"),e.remove=remove,__name(remove,"remove"),e.list=list,__name(list,"list")})(pe||(pe={})),(e=>{const t="9d1c250a-e61b-44d9-88ed-5944d1962f5e",n="https://console.anthropic.com/v1/oauth/token",r="https://console.anthropic.com/oauth/code/callback";function generateCodeVerifier(){return b.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return b.createHash("sha256").update(e).digest("base64url")}function generateState(){return b.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),o=generateState();return{url:`https://claude.ai/oauth/authorize?${new URLSearchParams({code:"true",client_id:t,response_type:"code",redirect_uri:r,scope:"org:create_api_key user:profile user:inference",code_challenge:n,code_challenge_method:"S256",state:o}).toString()}`,verifier:e,state:o}}async function exchangeCodeForTokens(e,o,s){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:s})});if(!i.ok){const e=await i.text();throw new Error(`Token exchange failed: ${e}`)}const a=await i.json();await pe.set("anthropic",{type:"oauth",refresh:a.refresh_token,access:a.access_token,expires:Date.now()+1e3*a.expires_in})}async function refreshAccessToken(){const e=await pe.get("anthropic");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return e.access;try{const r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t,refresh_token:e.refresh})});if(!r.ok)return void await pe.remove("anthropic");const o=await r.json();return await pe.set("anthropic",{type:"oauth",refresh:o.refresh_token,access:o.access_token,expires:Date.now()+1e3*o.expires_in}),o.access_token}catch(e){return void await pe.remove("anthropic")}}}async function getValidAccessToken(){const e=await pe.get("anthropic");if(e)return"api"===e.type?e.key:"oauth"===e.type?await refreshAccessToken():void 0}__name(generateCodeVerifier,"generateCodeVerifier"),__name(generateCodeChallenge,"generateCodeChallenge"),__name(generateState,"generateState"),e.createAuthorizationUrl=createAuthorizationUrl,__name(createAuthorizationUrl,"createAuthorizationUrl"),e.exchangeCodeForTokens=exchangeCodeForTokens,__name(exchangeCodeForTokens,"exchangeCodeForTokens"),e.refreshAccessToken=refreshAccessToken,__name(refreshAccessToken,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken,__name(getValidAccessToken,"getValidAccessToken")})(ge||(ge={})),__name(loginAction,"loginAction"),__name(logoutAction,"logoutAction"),__name(statusAction,"statusAction");var be=new e("auth").description("Manage authentication with Anthropic");be.command("login").description("Login with Claude Pro/Max subscription via OAuth").action(loginAction),be.command("logout").description("Remove stored authentication").action(logoutAction),be.command("status").description("Show authentication status").action(statusAction);var Ee=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{const s=y("/bin/bash",["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"]});let i="",a="",c=null;n>0&&(c=setTimeout(()=>{s.kill("SIGTERM"),t({stdout:i,stderr:a+(a?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),s.stdout?.on("data",e=>{i+=e.toString()}),s.stderr?.on("data",e=>{a+=e.toString()}),s.on("close",n=>{c&&clearTimeout(c),t({stdout:i.trim(),stderr:a.trim(),exitCode:n??0,command:e})}),s.on("error",n=>{c&&clearTimeout(c),t({stdout:i,stderr:a+`\n[Error: ${n.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),xe=__name(e=>{let t="";return e.stdout&&(t+=e.stdout),e.stderr&&(t&&(t+="\n"),t+=e.stderr),0===e.exitCode||e.stderr||(t&&(t+="\n"),t+=`[Process exited with code ${e.exitCode}]`),t||"(No output)"},"formatBashOutput"),Ce=w.object({id:w.string(),timestamp:w.number(),type:w.literal("image"),source:w.object({type:w.enum(["base64","url"]),media_type:w.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:w.string()})}),ve=w.object({id:w.string(),timestamp:w.number(),input:w.string(),output:w.string().optional(),metadata:w.record(w.string(),w.any()).optional(),images:w.array(Ce).optional().default([])}),Se=ve.extend({role:w.literal("user")}),ke=ve.extend({role:w.literal("assistant")}),Te=ve.extend({role:w.literal("tool"),name:w.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),Pe=ve.extend({role:w.literal("bash"),command:w.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),$e=ve.extend({role:w.literal("system")}),Ae=w.discriminatedUnion("role",[Se,ke,Te,Pe,$e]),Ie=__name((e,t)=>Ae.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),De=__name(e=>Ae.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),Fe=__name((e,t,n)=>Ae.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Re=__name(e=>Ae.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),Me=__name(e=>Ae.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),je=__name((e,t)=>{const n={...e,output:t};return Ae.parse(n)},"updateEntryWithOutput"),Oe=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),_e=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),Ue=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),Ne=["Thinking…","Yapping…","Yawning…","Brewing…","Contemplating…","Conjuring…","Pondering…","Mixing…","Stirring…","Channeling…","Sculpting…","Crystallizing…","Spinning…","Tuning…","Sparking…","Revving…","Cruising…","Exploring…","Blazing…","Climbing…","Diving…","Surfing…","Riding…","Dancing…","Juggling…","Performing…","Casting…","Cooking…","Baking…","Seasoning…","Garnishing…","Vibing…","Chilling…","Grooving…","Jamming…","Swaying…","Bouncing…","Flowing…","Gliding…","Floating…","Drifting…","Wandering…","Meandering…","Strolling…","Skipping…","Hopping…","Leaping…","Soaring…","Glowing…","Shimmering…","Twinkling…","Flickering…","Pulsing…","Humming…","Buzzing…","Whirring…","Purring…","Chirping…","Whistling…","Giggling…","Snickering…","Chuckling…","Grinning…","Smirking…","Winking…","Nodding…","Stretching…","Flexing…","Wiggling…","Swirling…","Twirling…","Spiraling…","Weaving…","Bobbing…","Rocking…","Swinging…","Swooshing…","Zipping…","Zooming…","Whizzing…","Zapping…","Popping…","Snapping…","Crackling…","Sizzling…","Bubbling…","Fizzing…"],Le=__name(()=>Ne[Math.floor(Math.random()*Ne.length)],"getRandomLLMStatus"),Be=__name(e=>{switch(e){case"read_file":return"Read";case"edit_file":return"Edit";case"write_file":return"Write";case"read_directory":return"List";case"read_multiple_files":return"Read Multiple";case"grep":return"Search";case"shell_command":return"Shell";case"todo_write":return"Todos";case"think":return"Thinking…";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),ze=__name((e,t)=>{try{switch(e){case"read_file":case"write_file":return t.absolutePath||t.file_path||t.path||"file";case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path||"file";case"read_directory":return t.path||"directory";case"grep":return`"${t.pattern}" in ${t.path||"files"}`;case"shell_command":return t.command&&t.args&&t.args.length>0?`${t.command} ${t.args.join(" ")}`:t.command||"";case"todo_write":return`${t.todos?t.todos.length:0} items`;case"think":return t.content||"planning";case"read_multiple_files":const e=t.include||[];return Array.isArray(e)?e.join(", "):"multiple files";default:return JSON.stringify(t||{})}}catch{return"parameters"}},"getToolInputContent"),We=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput"),qe=__name(()=>{const[e,t]=A({isExecuting:!1,currentCommand:null});return{executeBash:F(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Ee(e,{timeout:3e4,cwd:process.cwd()}),o=xe(t);n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const r=n[t];if("bash"===r.role&&"command"in r&&r.command===e&&!r.output){n[t]=je(r,o);break}}return n}),r()}catch(t){const o=t instanceof Error?t.message:"Unknown error occurred";n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const r=n[t];if("bash"===r.role&&"command"in r&&r.command===e&&!r.output){n[t]=je(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution"),Ge=new le("AnthropicClient"),Je=class{static{__name(this,"AnthropicClient")}static instance=null;constructor(){}static async initialize(){if(this.instance)return this.instance;const e=await ge.getValidAccessToken();if(e)try{return this.instance=new M({authToken:e,defaultHeaders:{"anthropic-beta":"oauth-2025-04-20"}}),process.env.DEBUG&&Ge.debug("Anthropic client initialized with OAuth"),this.instance}catch(e){throw Ge.error("Failed to initialize Anthropic client with OAuth"),e}const t=process.env.ANTHROPIC_API_KEY;if(!t)throw Ge.error("No authentication found"),Ge.info("Please either:"),Ge.info(' 1. Run "cmd auth login" to authenticate with Claude Pro/Max'),Ge.info(" 2. Or set ANTHROPIC_API_KEY environment variable"),new Error('No authentication found. Use "cmd auth login" or set ANTHROPIC_API_KEY');try{return this.instance=new M({apiKey:t}),process.env.DEBUG&&Ge.debug("Anthropic client initialized with API key"),this.instance}catch(e){throw Ge.error("Failed to initialize Anthropic client with API key"),e}}static async getClient(){return this.instance?this.instance:await this.initialize()}static async isConfigured(){return!(!await ge.getValidAccessToken()&&!process.env.ANTHROPIC_API_KEY)}static reset(){this.instance=null,Ge.debug("Anthropic client reset")}};function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var Ve=w.object({absolutePath:w.string().describe("The absolute path to the file to read"),offset:w.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:w.number().optional().describe("Optional number of lines to read")});w.object({content:w.union([w.string(),w.instanceof(Buffer)]),contentType:w.enum(["text","binary"]),fileType:w.string(),size:w.number(),linesRead:w.number().optional()});var He=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};async function readFileContent(e){const{absolutePath:t,offset:n,limit:o}=e;if(!a.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw new He("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=a.normalize(t);try{await r.access(s,j.constants.F_OK|j.constants.R_OK)}catch{throw new He(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await r.stat(s)).isFile())throw new He("Path does not point to a file","NOT_A_FILE");const i=getFileType(s),c=isBinaryFile(i);if(void 0!==n&&void 0===o||void 0===n&&void 0!==o)throw new He("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new He("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new He("Limit must be > 0","INVALID_LIMIT");try{if(c){const e=await r.readFile(s);return{fileType:i,content:e,size:e.length,contentType:"binary"}}if(void 0!==n&&void 0!==o){const e=await readTextFileLines(s,n,o);return{fileType:i,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await r.readFile(s,"utf8");return{content:e,fileType:i,contentType:"text",size:e.length}}}catch(e){if(e instanceof He)throw e;throw new He(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var Ke={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".pdf":"application/pdf",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf"};function getFileType(e){const t=a.extname(e).toLowerCase();return{".txt":"text",".md":"markdown",".csv":"csv",".log":"log",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".env":"env",".js":"javascript",".ts":"typescript",".jsx":"jsx",".tsx":"tsx",".py":"python",".java":"java",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c-header",".hpp":"cpp-header",".cs":"csharp",".go":"go",".rb":"ruby",".php":"php",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".clj":"clojure",".elm":"elm",".erl":"erlang",".ex":"elixir",".exs":"elixir",".hs":"haskell",".lua":"lua",".pl":"perl",".r":"r",".dart":"dart",".f":"fortran",".f90":"fortran",".groovy":"groovy",".jl":"julia",".m":"matlab",".sh":"shell",".bash":"bash",".zsh":"zsh",".ps1":"powershell",".sql":"sql",".vue":"vue",".svelte":"svelte",".astro":"astro",".component.ts":"angular",".module.ts":"angular",".service.ts":"angular",".razor":"razor",".cshtml":"razor",".erb":"ruby-template",".mustache":"mustache",".handlebars":"handlebars",".hbs":"handlebars",".ejs":"ejs",".pug":"pug",".liquid":"liquid",".twig":"twig",...Ke}[t]||"unknown"}function isBinaryFile(e){return Object.values(Ke).includes(e)}async function readTextFileLines(e,t,n){const o=(await r.readFile(e,"utf8")).split(/\r?\n/),s=t,i=Math.min(s+n,o.length),a=o.slice(s,i);return{content:a.join("\n"),linesRead:a.length}}async function processFileReferences(e){const t=[];let n=e;const r=[...e.matchAll(/@([^\s@]+)/g)];for(const e of r){const r=e[0],o=e[1];try{const e=a.isAbsolute(o)?o:a.resolve(process.cwd(),o),s=await readFileContent({absolutePath:e});if("binary"===s.contentType)continue;const i=String(s.content),c=a.relative(process.cwd(),e);t.push({token:r,resolvedPath:e,content:i});const l=`{${c}: ${i}}`;n=n.replace(r,l)}catch(e){continue}}return{displayContent:e,processedContent:n,fileReferences:t}}function reconstructContent(e,t){let n=e;for(const e of t){const t=`{${a.relative(process.cwd(),e.resolvedPath)}: ${e.content}}`;n=n.replace(e.token,t)}return n}function formatOutput(e){const t=[];if(void 0!==e.linesRead)t.push(`Read ${e.linesRead} lines`);else if("binary"===e.contentType)t.push(`Binary file: ${e.size} bytes`);else{const n=e.content?String(e.content).split("\n").length:0;t.push(`Read ${n} lines`)}return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),__name(formatOutput,"formatOutput");var Ye={name:"read_file",description:"Reads the contents of a file from the local filesystem, handling both text and binary files appropriately. \nThis tool automatically detects the file type based on extension and processes it accordingly - text files are returned as readable strings while binary files return metadata about the file type and size. \nFor large text files, you can optionally read specific line ranges using the offset and limit parameters to avoid loading the entire file into memory. \nThe tool validates that the provided path is absolute and that the file exists and is readable before attempting to read it. \nIt should be used when you need to examine file contents, verify file existence, or extract specific portions of text files for analysis or processing.",input_schema:{type:"object",properties:{absolutePath:{type:"string",description:'The absolute path to the file to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). Relative paths like "./file.txt" or "../file.txt" are not accepted. The file must exist and be readable by the current process.'},offset:{type:"number",description:"The line number to start reading from (0-based index, where 0 is the first line). This parameter must be used together with the limit parameter for reading specific line ranges. Cannot be negative. Use this when you need to read a specific section of a large file without loading the entire content."},limit:{type:"number",description:"The maximum number of lines to read starting from the offset. Must be a positive integer and used together with the offset parameter. This helps manage memory usage when dealing with large files by reading only the necessary portion."}},required:["absolutePath"]},execute:__name(async e=>{try{const t=Ve.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${t.cross} Error: ${e.message}`:`${t.cross} Error: Unknown error occurred while reading file`}},"execute")},Qe=w.object({filePath:w.string().describe("The absolute path to the file to edit"),oldValue:w.string().describe("The text to replace"),newValue:w.string().describe("The new text to insert"),replacementCount:w.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:w.boolean().optional().describe("Whether to replace all occurrences (default: false)")});function createFileEditError(e,t){const n=new Error(e);return n.name="FileEditError",n.code=t,n}async function editFile(e){const{filePath:t,oldValue:n,newValue:r,replaceAll:o=!1,replacementCount:s=1}=e;if(!t)throw createFileEditError("filePath is required","INVALID_PATH");if(!a.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!n)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==r)throw createFileEditError("newValue is required","INVALID_INPUT");if(!o&&s<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await U.access(t,N.F_OK|N.R_OK|N.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${t}`,"FILE_ACCESS_ERROR")}let i;try{const e=await readFileContent({absolutePath:t});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");i=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const c=(i.match(new RegExp(escapeRegExp(n),"g"))||[]).length;if(0===c)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let l,u;if(o)l=c;else if(l=s,l>c)throw createFileEditError(`Expected ${l} replacements, but only found ${c} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||l===c)u=i.split(n).join(r),d=c;else{u=i;for(let e=0;e<l;e++){const e=u.indexOf(n);-1!==e&&(u=u.substring(0,e)+r+u.substring(e+n.length),d++)}}if(0===d)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await U.writeFile(t,u,"utf-8"),console.log(`Successfully made ${d} replacement${1!==d?"s":""} in ${t}\n`),{path:t,replacementsCount:d,oldContent:i,newContent:u}}catch(e){throw createFileEditError(`Failed to write file: ${e instanceof Error?e.message:"Unknown error"}`,"WRITE_ERROR")}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function formatOutput2(e){const t=1!==e.replacementsCount?"s":"",n=`Edited ${e.path} (${e.replacementsCount} replacement${t})`;return e.newContent.length<500?`${n}\n\n${e.newContent}`:n}w.object({path:w.string(),replacementsCount:w.number(),oldContent:w.string(),newContent:w.string()}),w.object({name:w.string(),message:w.string(),code:w.string().optional()}),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),__name(formatOutput2,"formatOutput");var Ze={name:"edit_file",description:"Performs precise text replacements in files by finding and replacing exact string matches, similar to a str_replace operation.\nThis tool is designed for making targeted edits to text files, allowing you to replace specific occurrences of text with new content while preserving the rest of the file unchanged.\nIt validates that the file exists, is accessible, and is a text file (not binary) before attempting any modifications, ensuring data integrity.\nThe tool can replace a single occurrence, a specific number of occurrences, or all occurrences of the target text based on your requirements.\nIt should be used when you need to fix typos, update variable names, modify configuration values, or make any other precise text changes in code or text files.\nThe tool will report the exact number of replacements made and will fail safely if the target text is not found or if multiple matches exist when expecting a unique match.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path to the file to edit. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The file must exist and have write permissions. Binary files cannot be edited with this tool."},oldValue:{type:"string",description:"The exact text string to search for in the file. This must match exactly including whitespace, indentation, and line breaks. The match is case-sensitive. If multiple matches exist and replaceAll is false, only the first occurrence from the beginning of the file will be replaced."},newValue:{type:"string",description:"The replacement text that will be inserted in place of each matched occurrence of oldValue. Can be an empty string to effectively delete the matched text. Preserves any surrounding whitespace and formatting."},replaceAll:{type:"boolean",description:"When true, replaces all occurrences of oldValue in the file. When false (default), replaces only the number of occurrences specified by replacementCount. Use true when you need to update all instances, such as renaming a variable throughout a file."},replacementCount:{type:"number",description:"The number of occurrences to replace when replaceAll is false. Default is 1. Must be a positive integer. If set higher than the actual number of occurrences, the tool will report an error. Use this for controlled, partial replacements."}},required:["filePath","oldValue","newValue"]},execute:__name(async e=>{try{const t=Qe.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${t.cross} Error: ${e.message}`:`${t.cross} Error: Unknown error occurred while editing file`}},"execute")},Xe=w.object({path:w.string().describe("The absolute path to the directory to read"),exclude:w.array(w.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:w.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});w.object({files:w.array(w.string()),directories:w.array(w.string())});var et=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}};async function readDirectory(e){const{path:t,exclude:n=[],respectGitIgnore:o=!1}=e;if(!a.isAbsolute(t))throw new et("Path must be absolute, not relative","INVALID_PATH");try{if(!(await r.stat(t)).isDirectory())throw new et("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof et)throw e;throw new et(`Directory does not exist or is not accessible: ${t}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await r.readdir(t);let s=[];o&&(s=await loadGitIgnorePatterns(t));const i=[...n,...s],c=[],l=[];for(const n of e){if(shouldIgnoreEntry(n,i))continue;const e=a.join(t,n);try{const t=await r.stat(e);t.isDirectory()?l.push(n):t.isFile()&&c.push(n)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:c.sort(),directories:l.sort()}}catch(e){if(e instanceof et)throw e;throw new et(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(e){const t=[];try{if(!await isInGitRepository(e))return t;let n=a.resolve(e);const o=await findGitRoot(e);for(;n&&isWithinGitRoot(n,o);){const e=a.join(n,".gitignore");try{const n=(await r.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));t.push(...n)}catch(e){}const o=a.dirname(n);if(o===n)break;n=o}}catch(e){}return t}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(e){let t=a.resolve(e);for(;;){try{const e=a.join(t,".git");if((await r.stat(e)).isDirectory())return t}catch{}const e=a.dirname(t);if(e===t)throw new Error("Not in a git repository");t=e}}function isWithinGitRoot(e,t){const n=a.resolve(e),r=a.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(W(e,n))return!0;return!1}function formatOutput3(e){const t=e.directories.length+e.files.length,n=[];return n.push(`Found ${t} items (${e.directories.length} dirs, ${e.files.length} files)`),e.directories.length>0&&(n.push("Directories:"),e.directories.forEach(e=>n.push(` ${e}/`))),e.files.length>0&&(n.push("Files:"),e.files.forEach(e=>n.push(` ${e}`))),0===t&&n.push("(empty directory)"),n.join("\n")}__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),__name(formatOutput3,"formatOutput");var tt={name:"read_directory",description:"Lists the contents of a directory, providing separate arrays of files and subdirectories found at the specified path.\nThis tool is essential for exploring project structure, discovering available files, and understanding directory organization before performing operations on specific files.\nIt automatically respects .gitignore patterns by default when operating within git repositories, ensuring you don't see files that are intentionally excluded from version control.\nThe tool supports custom exclusion patterns using glob syntax, allowing you to filter out specific files or directories based on your needs, such as build artifacts or temporary files.\nResults are always sorted alphabetically for consistent output, making it easier to locate specific items in large directories.\nIt should be used when you need to explore a directory's contents, verify file existence, or understand project structure before performing file operations.",input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the directory to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The directory must exist and be accessible. Returns an error if the path points to a file instead of a directory."},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude from results. Uses minimatch syntax for pattern matching. Examples: ["*.log", "temp*", "**/*.tmp"] would exclude all log files, anything starting with "temp", and all .tmp files in any subdirectory. Patterns are applied in addition to any .gitignore rules.'}},required:["path"]},execute:__name(async e=>{try{const t=Xe.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${t.cross} Error: ${e.message}`:`${t.cross} Error: Unknown error occurred while reading directory`}},"execute")},nt=w.object({filePath:w.string().describe("The absolute path where the file should be written"),content:w.string().describe("The content to write to the file")});async function writeFile2({filePath:e,content:t}){if(!m(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=u(e);L(n)||await s(n,{recursive:!0}),await i(e,t,"utf-8");const r=Buffer.byteLength(t,"utf-8");return console.log(`Successfully wrote ${r} bytes to: ${e}\n`),{path:e,bytesWritten:r}}catch(t){const n=t instanceof Error?t.message:"Unknown error occurred";throw new Error(`Failed to write file '${e}': ${n}`)}}function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}w.object({success:w.boolean(),message:w.string(),path:w.string().optional()}),__name(writeFile2,"writeFile"),__name(formatOutput4,"formatOutput");var rt={name:"write_file",description:"Creates or overwrites a file with the specified content at the given absolute path, automatically creating any necessary parent directories.\nThis tool handles the complete file writing process, including directory creation, making it ideal for generating new files, saving processed output, or creating configuration files.\nIf the file already exists, it will be completely overwritten with the new content - the previous contents will be lost, so use with caution on existing files.\nThe tool automatically creates any missing parent directories in the path, eliminating the need to manually ensure directory structure exists before writing.\nIt should be used when you need to create new files, save generated content, write configuration files, or output processed data to the filesystem.\nAll content is written as UTF-8 encoded text, making it suitable for source code, configuration files, documentation, and other text-based formats.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path where the file should be written. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). If parent directories do not exist, they will be created automatically. Existing files at this path will be overwritten without warning."},content:{type:"string",description:"The text content to write to the file. Can be any UTF-8 string including multi-line text, JSON, XML, source code, or any other text format. Empty strings are valid and will create an empty file. Line endings are preserved as provided."}},required:["filePath","content"]},execute:__name(async e=>{try{const t=nt.parse(e),n=await writeFile2(t);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")},ot=w.object({include:w.array(w.string()).describe("Array of glob patterns to include files"),exclude:w.array(w.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:w.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:w.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:w.string().optional().describe("Base directory for relative paths. Default: current working directory")}),st=w.object({filePath:w.string(),content:w.string(),fileType:w.string(),size:w.number()});w.object({content:w.string(),filesRead:w.array(w.string()),errors:w.array(w.object({file:w.string(),error:w.string()})),fileDetails:w.array(st)});var it=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},at=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const o=new Set;for(const s of e)try{(await q(s,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>o.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${s}": ${e}`)}return Array.from(o).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:t,exclude:n=[],gitIgnore:r=!0,defaultExclude:o=!0,targetDirectory:s=process.cwd()}=e;if(!t||0===t.length)throw new it("At least one include pattern must be provided","NO_PATTERNS");const i=c.resolve(s),a={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(...at);const s=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:i});for(const e of s)try{const t=c.resolve(i,e),n=await readFileContent({absolutePath:t}),r=processFileResult({content:n,filePath:e});a.fileDetails.push(r),a.content+=`\n// File: ${e} (${n.fileType})\n`,a.content+=r.content,a.content+="\n",a.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);a.errors.push({file:e,error:n}),a.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return a}catch(e){if(e instanceof it)throw e;throw new it(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getReadSummary(e){return{totalFiles:e.fileDetails.length,successfulReads:e.filesRead.length,failedReads:e.errors.length,totalSize:e.fileDetails.reduce((e,t)=>e+t.size,0),fileTypesCounts:e.fileDetails.reduce((e,t)=>(e[t.fileType]=(e[t.fileType]||0)+1,e),{}),contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];return n.push(`Read ${t.successfulReads}/${t.totalFiles} files (${t.totalSize} bytes)`),e.errors.length>0&&(n.push("\nErrors:"),e.errors.forEach(e=>n.push(` - ${e.file}: ${e.error}`))),n.push("\n--- File Contents ---"),n.push(e.content),n.join("\n")}__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles"),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var ct={name:"read_multiple_files",description:"Reads multiple files simultaneously based on glob patterns, returning their contents concatenated with clear file headers for easy identification.\nThis tool is designed for bulk file operations, such as analyzing all source files in a project, reviewing multiple configuration files, or processing sets of related documents.\nIt automatically excludes common non-source directories like node_modules and build folders by default, and respects .gitignore patterns to avoid processing files that shouldn't be analyzed.\nThe tool handles both text and binary files appropriately - text files have their content included while binary files are noted with their type and size information.\nEach file's content is clearly separated with a header showing the file path and type, making it easy to distinguish between different files in the concatenated output.\nIt should be used when you need to analyze multiple files at once, search across multiple files for patterns, or gather content from various sources for processing or review.\nThe tool provides detailed feedback including which files were successfully read, any errors encountered, and statistics about the operation.",input_schema:{type:"object",properties:{include:{type:"array",items:{type:"string"},description:'Array of glob patterns to match files for reading. Uses standard glob syntax with support for wildcards (* for single level, ** for recursive). Examples: ["**/*.ts"] matches all TypeScript files, ["src/**/*.js", "lib/**/*.js"] matches JavaScript files in src and lib directories. At least one pattern must be provided.'},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude files from reading. Applied after include patterns. Examples: ["**/*.test.ts", "**/*.spec.js"] excludes test files, ["**/generated/**"] excludes generated directories. These patterns are additive with default exclusions and .gitignore rules.'},defaultExclude:{type:"boolean",description:"Whether to apply default exclusions for common non-source directories and files. Default is true. When enabled, automatically excludes: node_modules, dist, build, .git, coverage, tmp, temp, .DS_Store, *.log, *.tmp, *.cache, and other common build artifacts. Set to false to read all matching files regardless of common conventions."},gitIgnore:{type:"boolean",description:"Whether to respect .gitignore files when matching patterns. Default is true. When enabled, any files or directories listed in .gitignore files will be excluded from results. Useful for avoiding generated files, secrets, or other intentionally untracked files. Set to false to include all files matching your patterns."},targetDirectory:{type:"string",description:"The base directory from which to resolve glob patterns. Default is the current working directory. Must be an absolute path. All include and exclude patterns will be resolved relative to this directory. Use this to scope your file search to a specific part of the filesystem."}},required:["include"]},execute:__name(async e=>{try{const t=ot.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${t.cross} Error: ${e.message}`:`${t.cross} Error: Unknown error occurred while reading multiple files`}},"execute")},lt=w.object({pattern:w.string().min(1,"Pattern is required"),include:w.array(w.string()).optional(),directory:w.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=y(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",i="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{i+=e.toString()}),o.on("close",e=>{0===e?n(s):1!==e||i?r(new Error(i||`Command failed with exit code ${e}`)):n("")}),o.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,o]=t;return{file:n,line:parseInt(r,10),column:1,content:o.trim(),match:o.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",o=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)o.splice(-1,0,"--glob",e);o.splice(-1,0,"--glob","!node_modules/**"),o.splice(-1,0,"--glob","!.git/**"),o.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:o,command:"rg"})}catch(s){if(!(s instanceof Error&&s.message.includes("ENOENT")))throw s;if(r="grep",o=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)o.splice(-1,0,"--include",e);o.splice(-1,0,"--exclude-dir=node_modules"),o.splice(-1,0,"--exclude-dir=.git"),o.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:o,command:"grep"})}if(!e.trim())return[];const s=e.trim().split("\n"),i=[];for(const e of s){const t=parseGrepLine(e);t&&i.push(t)}return i}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),__name(formatGrepResults,"formatGrepResults");var ut={name:"grep",description:"Searches for text patterns across files in a directory using regular expressions, providing powerful pattern matching capabilities for code analysis, debugging, and content discovery.\nThis tool performs recursive searches through directory structures, examining file contents to find all occurrences of the specified pattern, making it ideal for locating specific code implementations, finding TODO comments, searching for function usage, or identifying configuration values.\nThe search uses Perl-compatible regular expressions (PCRE), supporting advanced patterns including lookaheads, lookbehinds, character classes, and quantifiers, with results showing file paths and line numbers for each match.\nFile filtering can be applied using glob patterns to search only specific file types, improving performance and relevance by focusing on the files that matter for your search.\nIt should be used when you need to find where something is defined or used in a codebase, locate specific text patterns across multiple files, verify the presence of certain code patterns, or analyze code structure and dependencies.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'The regular expression pattern to search for in file contents. Supports full PCRE syntax including special characters (\\d, \\w, \\s), quantifiers (*, +, ?, {n,m}), anchors (^, $), and groups. Special regex characters like ., *, [, ], (, ), {, }, |, \\, ^, $ must be escaped with backslash when matching literally. Examples: "TODO.*urgent" finds TODO comments marked urgent, "function\\s+\\w+\\(" finds function definitions, "import.*from.*react" finds React imports.'},include:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to filter which files to search. Only files matching at least one pattern will be searched. Supports standard glob syntax: * matches any characters except /, ** matches any characters including /, ? matches single character, [abc] matches character set. Examples: ["*.ts", "*.tsx"] searches TypeScript files, ["src/**/*.js"] searches JavaScript files in src directory, ["*.{js,jsx,ts,tsx}"] searches all JavaScript/TypeScript files. If omitted, searches all files except those in .gitignore.'},directory:{type:"string",description:'Optional directory to search in, specified as a relative path from the current working directory. Cannot be an absolute path. Examples: "src" searches in src folder, "packages/core" searches in packages/core, "." or omitted searches current directory. The directory must exist and be readable. Defaults to the current working directory if not specified.'}},required:["pattern"]},execute:__name(async e=>{try{const t=lt.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${t.cross} Error: ${e.message}`:`${t.cross} Error: Unknown error occurred while searching files`}},"execute")},dt=w.object({command:w.string().min(1,"Command cannot be empty"),args:w.array(w.string()).optional(),directory:w.string().optional(),timeout:w.number().optional()}),mt=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,i){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=i}};async function executeShellCommand(e){const{command:t,args:n=[],directory:r,timeout:s=3e4}=e,i=Date.now();if(!t.trim())throw new mt("Command cannot be empty","EMPTY_COMMAND");let c;if(r){if(a.isAbsolute(r))throw new mt("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");c=a.resolve(process.cwd(),r)}else c=process.cwd();try{if(!(await o.stat(c)).isDirectory())throw new mt(`Path is not a directory: ${r}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof mt)throw e;throw new mt(`Directory does not exist or is not accessible: ${r||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:c,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((r,o)=>{let a="",c="",l=!1;const u=setTimeout(()=>{if(!l){d.kill("SIGTERM");const e=Date.now()-i;o(new mt(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",a,c,e))}},s),d=y(t,n,e);d.stdout?.on("data",e=>{a+=e.toString()}),d.stderr?.on("data",e=>{c+=e.toString()}),d.on("close",(e,t)=>{l=!0,clearTimeout(u);const n=Date.now()-i;0===e?r({stdout:a.trim(),stderr:c.trim(),exitCode:e,signal:t,duration:n}):o(new mt(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,a.trim(),c.trim(),n))}),d.on("error",e=>{l=!0,clearTimeout(u);const t=Date.now()-i;o(new mt(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),c.trim(),t))})})}catch(e){if(e instanceof mt)throw e;throw new mt(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}function formatShellCommandResult(e){const t=[];return 0===e.exitCode||null===e.exitCode||t.push(`Exit code: ${e.exitCode}`),e.signal&&t.push(`Signal: ${e.signal}`),e.stdout&&t.push(e.stdout),e.stderr&&t.push(e.stderr),t.join("\n")}__name(executeShellCommand,"executeShellCommand"),__name(formatShellCommandResult,"formatShellCommandResult");var ht={name:"shell_command",description:"Executes shell commands in a controlled environment with comprehensive output capture, timeout protection, and working directory management, enabling system operations, build processes, and tool integrations.\nThis tool spawns commands as child processes with full control over execution environment, capturing both standard output and error streams while monitoring exit codes and signals, making it ideal for running build scripts, executing CLI tools, performing system operations, or integrating with external programs.\nCommands run with shell interpretation enabled for cross-platform compatibility, supporting pipes, redirections, and shell built-ins, with automatic timeout termination to prevent hanging processes from blocking execution.\nThe tool provides detailed execution results including stdout, stderr, exit codes, and execution duration, helping diagnose issues and verify successful completion of operations.\nIt should be used when you need to run build or test commands, execute system utilities, interact with CLI tools, perform file operations that require shell commands, or integrate with external programs and scripts.\nImportant: Commands execute with the permissions of the current process. Be cautious with commands that modify the filesystem or system state. Always validate and sanitize any user-provided input before including it in commands.",input_schema:{type:"object",properties:{command:{type:"string",description:'The shell command to execute. Can be any valid shell command available in the system PATH or built-in shell commands. Common commands include: "npm" for Node.js packages, "git" for version control, "ls"/"dir" for listing files, "echo" for output, "cat"/"type" for file contents. The command string is passed to the system shell (sh on Unix, cmd.exe on Windows). Special characters should be properly escaped. Cannot be empty.'},args:{type:"array",items:{type:"string"},description:'Optional array of arguments to pass to the command. Each argument is passed as a separate string and is automatically escaped for shell safety. Use this instead of including arguments in the command string for better security and cross-platform compatibility. Examples: ["install", "--save-dev", "typescript"] for npm, ["status", "--short"] for git, ["-la", "/usr"] for ls. Arguments containing spaces or special characters are automatically quoted.'},directory:{type:"string",description:'Optional working directory where the command should be executed, specified as a relative path from the current working directory. Must be a relative path (absolute paths are not allowed for security). The directory must exist and be accessible. Examples: "src" runs in src folder, "packages/core" runs in packages/core, "../sibling" runs in sibling directory. If omitted, uses the current working directory. Useful for running commands that depend on specific file locations or configurations.'},timeout:{type:"number",description:"Optional maximum time in milliseconds to wait for the command to complete before forcibly terminating it. Must be between 100 and 300000 (5 minutes). Defaults to 30000ms (30 seconds). The command process is killed with SIGTERM if it exceeds this duration. Useful for preventing long-running or hanging processes. Set higher for operations known to take time (builds, installs), lower for quick operations. Examples: 5000 for quick commands, 60000 for npm install, 120000 for large builds."}},required:["command"]},execute:__name(async e=>{try{const t=dt.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const n=e;if(n.stdout||n.stderr){let r=`${t.cross} Error: ${e.message}`;return n.stdout&&(r+=`\nOutput:\n${n.stdout}`),n.stderr&&(r+=`\nError output:\n${n.stderr}`),r}return`${t.cross} Error: ${e.message}`}return`${t.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}__name(think,"think");var pt={name:"think",description:'Use this tool to think step by step about complex problems. Use first-person language: "I need to understand..." or "Let me figure out..." rather than "The user wants...". Show your reasoning process.',input_schema:{type:"object",properties:{thought:{type:"string",description:"Your step-by-step reasoning and thought process"}},required:["thought"]},execute:think};async function todoWrite(e){return JSON.stringify(e.todos)}__name(todoWrite,"todoWrite");var gt=[Ye,Ze,tt,rt,ct,ut,ht,pt,{name:"todo_write",description:"Create and manage a structured task list. Use this to track progress, organize complex tasks, and show thoroughness to the user. Create todos when tasks require multiple steps, are non-trivial, or when explicitly requested.",input_schema:{type:"object",properties:{todos:{type:"array",description:"The updated todo list",items:{type:"object",properties:{content:{type:"string",minLength:1,description:"The todo item content"},status:{type:"string",enum:["pending","in_progress","completed"],description:"The status of the todo item"},id:{type:"string",description:"Unique identifier for the todo item"}},required:["content","status","id"]}}},required:["todos"]},execute:todoWrite}],ft=new Map(gt.map(e=>[e.name,e]));async function executeTool(e,t){const n=ft.get(e);if(!n)throw new Error(`Tool "${e}" not found. Available tools: ${Array.from(ft.keys()).join(", ")}`);try{return await n.execute(t)}catch(e){return e instanceof Error?`Error: ${e.message}`:"Error: Unknown error occurred"}}function getToolSchemas(){return gt.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(1.1*t));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)"text"===n.type?t+=estimateTextTokens(n.text):"image"===n.type&&"source"in n&&"base64"===n.source.type&&(t+=estimateImageTokens(n.source.data));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/3.5;const n=.1*e.split(/\s+/).length;return Math.ceil(t-n)}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>25e3}function getOversizedOutputError(e,t){return`Error: Output too large (${e.toLocaleString()} tokens, max ${25e3.toLocaleString()}). Try using grep or ripgrep with more specific patterns to filter results.`}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?getOversizedOutputError(estimateTokens(e)):e}function calculateUsageFromResponse(e){return(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.output_tokens||0)}__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse");var yt=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return c.join(g.homedir(),".command-code","projects")}static getCurrentProjectDirName(){return G(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=c.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=c.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=f("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await o.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),!1}}async isProjectInitialized(){try{return(await o.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{const n=JSON.stringify(e);if(n===this.lastSavedMessagesHash)return;await this.initializeProject();const r=[];for(const n of e){const e=crypto.randomUUID(),o={id:e,timestamp:n.meta.timestamp,sessionId:this.sessionId,parentId:this.lastMessageId,role:n.message.role,content:n.message.content,gitBranch:this.gitBranch,metadata:{...n.meta,...t?.metadata||{}}};r.push(JSON.stringify(o)),this.lastMessageId=e}await o.writeFile(this.sessionFilePath,r.join("\n")+"\n"),this.lastSavedMessagesHash=n}catch(e){console.error("Failed to save messages to session:",e)}}async loadMessages(e){const t=e||this.sessionId,n=c.join(this.projectPath,`${t}.jsonl`);try{const e=(await o.readFile(n,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);"user"!==e.role&&"assistant"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}})}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading messages:",e),[]}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),o=crypto.randomUUID();if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n&&t.push({id:o,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const r of e.content)if("text"===r.type)n+=r.text;else if("tool_use"===r.type){const e=ze(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}n&&t.push({id:o,timestamp:r,role:"assistant",input:n,images:[]})}}return t}async loadSession(e){const t=e||this.sessionId,n=c.join(this.projectPath,`${t}.jsonl`);try{const e=(await o.readFile(n,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);t.push(e)}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading session:",e),[]}}convertToFeedEntries(e){return e.map(e=>{const t={id:e.id,timestamp:new Date(e.timestamp).getTime(),role:e.role,metadata:e.metadata};return"object"==typeof e.content&&null!==e.content&&"input"in e.content?{...t,input:e.content.input,output:e.content.output,...e.content.name?{name:e.content.name}:{},...e.content.command?{command:e.content.command}:{}}:{...t,input:"string"==typeof e.content?e.content:JSON.stringify(e.content)}})}convertToAnthropicMessages(e){return e.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>{let t;if(t="string"==typeof e.content?e.content:e.content&&"object"==typeof e.content?e.content.input||JSON.stringify(e.content):"","user"===e.role&&e.metadata?.fileReferences)try{t=reconstructContent(t,e.metadata.fileReferences)}catch(e){console.error("Failed to reconstruct file content from session:",e)}return{role:e.role,content:t}})}static async isProjectInitialized(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=c.join(e,t);try{return(await o.stat(n)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=c.join(e,t);try{return await o.mkdir(n,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=c.join(_SessionManager.getProjectsBasePath(),e);try{try{await o.access(t)}catch{return[]}const e=(await o.readdir(t)).filter(e=>e.endsWith(".jsonl")),n=[];for(const r of e){const e=r.replace(".jsonl",""),s=c.join(t,r);try{const r=await o.stat(s),i=(await o.readFile(s,"utf-8")).trim().split("\n").filter(e=>e.trim());if(i.length>0){let o="",s="";const a=JSON.parse(i[0]);a.gitBranch&&(s=a.gitBranch);for(const e of i){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)o=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){o=e.text;break}}else t.content?.input&&(o=t.content.input);if(o)break}}n.push({id:e,createdAt:r.birthtime.toISOString(),lastModified:r.mtime.toISOString(),firstMessage:o||"No messages",messageCount:i.length,projectPath:t,gitBranch:s||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return n.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const t=c.join(this.projectPath,`${this.sessionId}.share.json`);try{await o.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=c.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await o.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=c.join(this.projectPath,`${this.sessionId}.share.json`);try{await o.unlink(e)}catch(e){}}};function getApiBaseUrl({prod:e}={}){return(void 0!==e?e:"development"!==process.env.ENVIRONMENT)?"https://api.claicode.com":"http://localhost:9090"}__name(getApiBaseUrl,"getApiBaseUrl");var wt=class _APIError extends Error{static{__name(this,"APIError")}status;headers;error;code;param;type;request_id;constructor(e,t,n,r){super(_APIError.makeMessage(e,t,n)),this.status=e,this.headers=r,this.request_id=r?.["lb-request-id"];const o=t;this.error=o,this.code=o?.code,this.status=o?.status}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e)return new bt({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Et(e,o,n,r);case 401:return new xt(e,o,n,r);case 403:return new Ct(e,o,n,r);case 404:return new vt(e,o,n,r);case 409:return new St(e,o,n,r);case 422:return new kt(e,o,n,r);case 429:return new Tt(e,o,n,r);default:return e>=500?new Pt(e,o,n,r):new _APIError(e,o,n,r)}}},bt=class extends wt{static{__name(this,"APIConnectionError")}status=void 0;constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Et=class extends wt{static{__name(this,"BadRequestError")}status=400},xt=class extends wt{static{__name(this,"AuthenticationError")}status=401},Ct=class extends wt{static{__name(this,"PermissionDeniedError")}status=403},vt=class extends wt{static{__name(this,"NotFoundError")}status=404},St=class extends wt{static{__name(this,"ConflictError")}status=409},kt=class extends wt{static{__name(this,"UnprocessableEntityError")}status=422},Tt=class extends wt{static{__name(this,"RateLimitError")}status=429},Pt=class extends wt{static{__name(this,"InternalServerError")}},$t=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=this.buildHeaders({headers:e.headers});let o;try{o=await this.makeRequest({url:n,options:e,headers:r})}catch(e){throw new bt({cause:e instanceof Error?e:void 0})}return o.ok||await this.handleErrorResponse({response:o}),e.stream?o.body:o.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}buildHeaders({headers:e}){return{"Content-Type":"application/json",...this.config.apiKey?{Authorization:`Bearer ${this.config.apiKey}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const s=await fetch(e,{method:t.method,headers:n,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return o&&clearTimeout(o),s}catch(e){throw o&&clearTimeout(o),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};throw e.headers.forEach((e,t)=>{n[t]=e}),wt.generate(e.status,t,e.statusText,n)}async post(e){return this.send({...e,method:"POST"})}async get(e){return this.send({...e,method:"GET"})}async put(e){return this.send({...e,method:"PUT"})}async delete(e){return this.send({...e,method:"DELETE"})}},At=class _PathSanitizer{static{__name(this,"PathSanitizer")}projectRoot;homeDir;options;constructor(e={}){this.projectRoot=e.projectRoot||process.cwd(),this.homeDir=this.getHomeDirectory(),this.options={projectRoot:this.projectRoot,useHomeShorthand:e.useHomeShorthand??!0,customReplacements:e.customReplacements||[]}}sanitizeMessage(e){if(!e)return e;const t=JSON.parse(JSON.stringify(e)),n=t.message||t;return"string"==typeof n.content?n.content=this.sanitizeText(n.content):Array.isArray(n.content)?n.content=n.content.map(e=>"text"===e.type&&"string"==typeof e.text?{...e,text:this.sanitizeText(e.text)}:"tool_use"===e.type&&e.input?{...e,input:this.sanitizeToolInput(e.input)}:e):n.content&&"object"==typeof n.content&&(n.content.input&&(n.content.input=this.sanitizeText(n.content.input)),n.content.output&&(n.content.output=this.sanitizeText(n.content.output))),t.message&&(t.message=n),t.metadata&&(t.metadata=this.sanitizeObject(t.metadata)),t}sanitizeToolInput(e){if(!e||"object"!=typeof e)return e;const t={...e},n=["absolutePath","filePath","path","file_path"];for(const e of n)t[e]&&"string"==typeof t[e]&&(t[e]=this.sanitizePath(t[e]));return t.directory&&"string"==typeof t.directory&&(t.directory=this.sanitizePath(t.directory)),t.content&&"string"==typeof t.content&&(t.content=this.sanitizeText(t.content)),t}sanitizeText(e){if(!e||"string"!=typeof e)return e;let t=e;for(const{pattern:e,replacement:n}of this.options.customReplacements)t=t.replace(e,n);return t=this.replaceAbsolutePaths(t),t}sanitizePath(e){if(!e||"string"!=typeof e)return e;if(!c.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=c.relative(this.projectRoot,e);if(!t.startsWith("../../../"))return t.startsWith("../")?t:`./${t}`}catch(e){}if(this.options.useHomeShorthand&&e.startsWith(this.homeDir))return e.replace(this.homeDir,"~");const t=c.basename(e);return c.dirname(e),this.isUserPath(e)?`<user-home>/${c.relative(this.homeDir,e)}`:`<system-path>/${t}`}replaceAbsolutePaths(e){return e.match(/\/(?:Users|home)\/[^\/\s]+(?:\/[^\s]*)?/g),(e=e.replace(/\/(?:Users|home)\/[^\/\s]+(?:\/[^\s]*)?/g,e=>this.sanitizePath(e))).match(/[A-Za-z]:\\(?:Users\\[^\\]+(?:\\[^\\]*)*|[^\s]*)/g),(e=e.replace(/[A-Za-z]:\\(?:Users\\[^\\]+(?:\\[^\\]*)*|[^\s]*)/g,e=>this.sanitizePath(e))).match(/(?:^|\s)([A-Za-z]:\\[^\s]*|\/[^\s]*)/g),e.replace(/(?:^|\s)([A-Za-z]:\\[^\s]*|\/[^\s]*)/g,(e,t)=>e.substring(0,e.length-t.length)+this.sanitizePath(t))}sanitizeObject(e){if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.sanitizeObject(e));const t={};for(const[n,r]of Object.entries(e))t[n]="string"==typeof r?this.sanitizeText(r):"object"==typeof r?this.sanitizeObject(r):r;return t}isWindowsAbsolutePath(e){return/^[A-Za-z]:\\/.test(e)}isUserPath(e){return e.includes("/Users/")||e.includes("/home/")||e.includes("\\Users\\")}getHomeDirectory(){return process.env.HOME||process.env.USERPROFILE||""}static forProject(e){return new _PathSanitizer({projectRoot:e,useHomeShorthand:!0})}static sanitizeMessage(e,t){return _PathSanitizer.forProject(t).sanitizeMessage(e)}static sanitizeMessages(e,t){const n=_PathSanitizer.forProject(t);return e.map(e=>n.sanitizeMessage(e))}};function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${g.platform()}-${g.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return O.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!e.name.startsWith(".")).filter(e=>!t.has(e.name)).map(e=>e.name).sort()}catch{return[]}}function isGitRepository(){try{return f("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return f("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=f("git branch -r",{encoding:"utf8",cwd:getCurrentWorkingDirectory()});return e.includes("origin/main")?"main":e.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=f("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),n=t.filter(e=>e.startsWith(" M")).length,r=t.filter(e=>e.startsWith("A ")).length,o=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,i=[];return n>0&&i.push(`M ${n}`),r>0&&i.push(`A ${r}`),o>0&&i.push(`D ${o}`),s>0&&i.push(`?? ${s}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=f("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getRootDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[]}}__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext");var It=new le("ContextEngine"),Dt=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();constructor(e,t){const n=getApiBaseUrl();this.request=new $t({baseUrl:n}),this.callbacks=e,this.sessionManager=new yt(t)}async getClient(){return this.anthropic||(this.anthropic=await Je.getClient()),this.anthropic}async interrupt(e=!1){if(this.abortController){this.abortController.abort(),this.abortController=null,It.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)&&t.message.content.some(e=>"tool_use"===e.type)&&(this.messages.pop(),It.debug("Removed assistant message with pending tool calls to prevent API errors")),e){this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[{type:"text",text:"Interrupted by user"}]}));const e=Ie("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>It.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t){let n=e,r=[];try{const t=await processFileReferences(e);n=t.processedContent,r=t.fileReferences}catch(e){console.error("File reference processing failed:",e)}const o=Ie(e);t&&t.length>0&&(o.metadata={...o.metadata,images:t}),r&&r.length>0&&(o.metadata={...o.metadata,fileReferences:r}),this.callbacks.onFeedUpdate(o);const s=[];t&&t.length>0&&t.forEach(e=>{s.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),n.trim()&&s.push({type:"text",text:n});const i={role:"user",content:s};return this.addMessageAndSync(this.createMessageWithMeta(i)),this.sessionManager.saveMessages(this.messages,o).catch(e=>It.error(`Failed to save messages to session: ${e}`)),await this.processMessages()}async processMessages(){let e="";this.abortController=new AbortController;let t=!1;for(;;)try{if(this.abortController?.signal.aborted)throw new Error("Interrupted by user");if(!t){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message),t=!0}const n=getToolSchemas(),r=await ge.getValidAccessToken(),o={tools:n,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:"anthropic:claude-sonnet-4-20250514"},s={config:getEnvironmentContext(),params:o};It.debug(`🔍 API Call: ${o.model}, ${this.messages.length} messages, ${n.length} tools, streaming: true`);const i=await this.request.post({body:s,stream:!0,endpoint:ue,signal:this.abortController?.signal,headers:{"x-oauth-token":`Bearer ${r}`}}),a=J.fromReadableStream(i);a.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let c,l=null;a.on("error",e=>{l="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});try{c=await a.finalMessage()}catch(e){if(l)throw l;if("AbortError"===e.name||e.message?.includes("aborted")||this.abortController?.signal.aborted)throw new Error("Interrupted by user");throw e}if(l)throw l;if("usage"in c){const e=c.usage;if(e?.input_tokens){const t=calculateUsageFromResponse(e);this.contextTokensUsed=t,this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:2e5})}}const u=c.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),d=c.content.filter(e=>"tool_use"===e.type);if(e=u,0===d.length){const e=c.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(e.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:e})),u.trim()){const e=De(u);this.callbacks.onFeedUpdate(e),this.sessionManager.saveMessages(this.messages,e).catch(e=>It.error(`Failed to save messages: ${e}`))}if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0){const t=[];for(const n of e){t.push({type:"text",text:n});const e=Ie(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>It.error(`Failed to save messages: ${e}`));continue}}break}const m=c.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(m.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:m})),u.trim()){const e=De(u);this.callbacks.onFeedUpdate(e)}const h=[],p=new Set;let g=!1;for(const e of d){if(this.abortController?.signal.aborted)throw new Error("Interrupted by user");try{if(["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&this.callbacks.onPermissionRequest&&!await this.callbacks.onPermissionRequest(e.name,e.input)){const t=ze(e.name,e.input),n="edit_file"===e.name?e.input:void 0,r=Fe(e.name,t,n),o=je(r,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o),g=!0;break}const t=await executeTool(e.name,e.input);if(this.abortController?.signal.aborted)throw new Error("Interrupted by user");const n=checkToolOutputTokensLimit(t,e.name),r=estimateTokens(n);this.currentInteractionTokens+=r,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),h.push({type:"tool_result",tool_use_id:e.id,content:n}),p.add(e.id);const o=ze(e.name,e.input),s="edit_file"===e.name?e.input:void 0,i=Fe(e.name,o,s),a=je(i,n);this.callbacks.onFeedUpdate(a)}catch(t){const n=t instanceof Error?t.message:"Unknown error";h.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}),p.add(e.id);const r=ze(e.name,e.input),o="edit_file"===e.name?e.input:void 0,s=Fe(e.name,r,o),i=je(s,Oe(n));this.callbacks.onFeedUpdate(i)}}if(g){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?p.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const f=[...h];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){f.push({type:"text",text:t});const e=Ie(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:f})),this.sessionManager.saveMessages(this.messages).catch(e=>It.error(`Failed to save messages: ${e}`))}catch(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||this.abortController?.signal.aborted)throw It.debug("Request interrupted by user"),new Error("Interrupted by user");throw It.error(`Failed to get response: ${e}`),e}return this.abortController=null,e}getHistory(){return[...this.messages]}async loadSession(e){const t=await this.sessionManager.loadMessages(e);this.messages=t;const n=this.sessionManager.reconstructFeedFromMessages(t);return It.debug(`Loaded session ${e} with ${t.length} messages`),n}getMessages(){return[...this.messages]}getRawMessages(){return this.messages.map(e=>e.message)}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){It.error(`Failed to sync message to share: ${e}`)}}))}async syncMessageToShare(e,t){try{const n=At.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r=`${getApiBaseUrl()}${de.APPEND}`,o={sessionId:e.sessionId,secret:e.secret,message:n},s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const e=await s.text();It.error(`Share sync failed with status ${s.status}: ${e}`)}}catch(e){throw e}}};function Markdown({children:e,...t}){const n={...t};K({renderer:new Q(n),breaks:!0,gfm:!0});const r=Y(e);return $.createElement(v,null,r.toString().trim())}function AssistantMessage({content:e}){return $.createElement(C,null,$.createElement(v,null,n.nodejs),$.createElement(C,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},$.createElement(Markdown,null,e)))}function UserMessage({content:e}){const t="Interrupted by user"===e;return $.createElement(C,null,$.createElement(v,{color:t?"red":"dim"},n.pointer),$.createElement(C,{marginLeft:1},$.createElement(v,{color:t?"red":void 0,dimColor:!t,wrap:"wrap"},e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage"),__name(UserMessage,"UserMessage");var Ft="#6B7280";function truncateToolOutputForDisplay(e){const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),n=t.split("\n");return n.length<=4?t:`${n.slice(0,4).join("\n")}\n… (${n.length-4} more lines)`}function generateDiff(e,t,n){const r=Z.diffLines(e,t);let o=0,s=0,i=0;return r.forEach(e=>{e.added?o+=e.count||1:e.removed&&(s+=e.count||1)}),$.createElement(C,{flexDirection:"column"},$.createElement(v,{color:"gray"},"Updated ",$.createElement(v,{color:"white",bold:!0},n)," with ",$.createElement(v,{color:"#22C55E"},o)," addition",1!==o?"s":""," and ",$.createElement(v,{color:"#EF4444"},s)," removal",1!==s?"s":""),$.createElement(C,{flexDirection:"column",marginLeft:2},r.map((e,t)=>{const n=e.value.split("\n").filter(e=>e);return e.added||e.removed?n.map((n,r)=>e.removed?(i++,$.createElement(C,{key:`${t}-${r}-removed`,width:"100%"},$.createElement(v,{color:"gray"},i.toString().padStart(3)," "),$.createElement(C,{backgroundColor:"#712F37"},$.createElement(v,null,"-"),$.createElement(v,null," ",n.replace(/\s/g," "))))):e.added?(i++,$.createElement(C,{key:`${t}-${r}-added`,width:"100%"},$.createElement(v,{color:"gray"},i.toString().padStart(3)," "),$.createElement(C,{backgroundColor:"#325B30"},$.createElement(v,null,"+"),$.createElement(v,null," ",n.replace(/\s/g," "))))):null):(i+=n.length,null)})))}function formatTodosForDisplay(e){const t=We(e);return t?$.createElement(C,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?"☒":"☐";let r,o=!1;switch(e.status){case"completed":r="#22C55E",o=!0;break;case"in_progress":r="#E4CCFF";break;default:r="white"}return $.createElement(C,{key:e.id||t,flexDirection:"row"},$.createElement(C,{width:2},$.createElement(v,{color:r},n)),$.createElement(v,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):$.createElement(v,null,e)}function ToolMessage({name:e,input:t,output:r,isPending:o=!1,hasError:s=!1,metadata:i}){const a="Thinking…"===e,c="Todos"===e,l="Edit"===e,u=!a&&t,d=!a&&!c;let m,h;if(o)m="yellow",h="→";else if(s)m="red",h=n.nodejs;else if(a)m=Ft,h="✻";else if(c&&r){const e=We(r),t=e?.every(e=>"completed"===e.status);m=t?"#22C55E":"#D4A017",h=n.nodejs}else m="#22C55E",h=n.nodejs;return $.createElement(C,null,$.createElement(v,{color:m,italic:a},h),$.createElement(C,{flexDirection:"column",marginLeft:1},$.createElement(C,null,$.createElement(v,{bold:!a,color:a?Ft:void 0,italic:a},`${e} `),u&&$.createElement(v,null,$.createElement(Markdown,null,`(${t})`))),r&&$.createElement(C,{columnGap:1},d&&$.createElement(v,null,"⎿"," "),c?formatTodosForDisplay(r):a?$.createElement(C,{width:"100%",flexDirection:"column"},$.createElement(v,null," "),$.createElement(v,{color:Ft,wrap:"wrap",italic:!0},r)):l&&i?.oldValue&&i?.newValue?generateDiff(i.oldValue,i.newValue,t):$.createElement(C,{width:"100%"},$.createElement(v,{color:s?"red":"",wrap:"wrap"},truncateToolOutputForDisplay(r)))),o&&$.createElement(C,{columnGap:1},$.createElement(v,null,"⎿"," "),$.createElement(v,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,s;return n?(o="yellow",s="→"):r?(o="red",s="✗"):(o="green",s="✓"),$.createElement(C,null,$.createElement(v,{color:o},s),$.createElement(C,{flexDirection:"column",marginLeft:1},$.createElement(C,null,$.createElement(v,{color:"gray"},"$ "),$.createElement(v,{color:o,bold:!0},e)),$.createElement(C,{columnGap:1},$.createElement(v,null,"⎿"," "),$.createElement(v,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}function SystemMessage({content:e}){return $.createElement(C,{flexDirection:"column"},$.createElement(v,{wrap:"wrap"},$.createElement(Markdown,null,e)))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage"),__name(SystemMessage,"SystemMessage");var Rt="\n ██████╗ ██████╗ ███╗ ███╗███╗ ███╗ █████╗ ███╗ ██╗██████╗\n██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔══██╗████╗ ██║██╔══██╗\n██║ ██║ ██║██╔████╔██║██╔████╔██║███████║██╔██╗ ██║██║ ██║\n██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║\n╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝\n ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝\n",Mt=$.memo(({feed:e,showHeader:t=!1,staticKey:n})=>{const r=t?["header",...e]:e;return $.createElement(x,{items:r,key:n},e=>{if("header"===e)return $.createElement(C,{key:"header",marginBottom:1},$.createElement(H,{name:"vice"},$.createElement(v,null,Rt),$.createElement(v,null,"Welcome to Command by Langbase. Agentic coding agent.")));const t=e,n=(()=>{switch(t.role){case"user":return $.createElement(UserMessage,{content:t.input});case"assistant":return $.createElement(AssistantMessage,{content:t.input});case"tool":return $.createElement(ToolMessage,{name:Be(t.name||""),input:t.input,output:t.output||"",isPending:Ue(t),hasError:_e(t),metadata:t.metadata});case"bash":return $.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:Ue(t),hasError:_e(t)});case"system":return $.createElement(SystemMessage,{content:t.input});default:return $.createElement($.Fragment,null)}})();return $.createElement(C,{key:t.id,marginBottom:1},n)})}),jt=__name(({messages:e})=>0===e.length?null:$.createElement(C,{borderStyle:"round",borderColor:"#D97706",padding:1,marginBottom:1},$.createElement(C,{flexDirection:"column"},$.createElement(C,{marginBottom:1},$.createElement(v,{color:"#D97706",bold:!0},"Queued Messages (",e.length,")")),e.map((t,n)=>$.createElement(C,{key:n,marginBottom:n===e.length-1?0:1},$.createElement(v,{color:"gray"},"•"),$.createElement(C,{marginLeft:1},$.createElement(v,{dimColor:!0},t.length>60?`${t.substring(0,60)}...`:t)))))),"QueuedMessages"),Ot=["dim","dim2","normal","normal2","bright","bright2","brighter","brighter2","brightest","brightest","brighter2","brighter","bright2","bright","normal2","normal","dim2","dim"],_t=__name(e=>{switch(e){case"dim":return"#8A6BA3";case"dim2":return"#9D7AB8";case"normal":return"#B799E6";case"normal2":return"#C9AAEE";case"bright":default:return"#E4CCFF";case"bright2":return"#EBDAFF";case"brighter":return"#F0D9FF";case"brighter2":return"#F5E8FF";case"brightest":return"#FFFFFF"}},"getGlowColor"),Ut=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=A(0),[s,i]=A(0);function formatToken(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}function formatTime(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}return I(()=>{const e=setInterval(()=>{o(e=>(e+1)%Ot.length)},120);return()=>clearInterval(e)},[]),I(()=>{if(s===n)return;const e=n-s,t=Math.max(1,Math.ceil(Math.abs(e)/20)),r=e>0?t:-t,o=setInterval(()=>{i(e=>{const t=e+r;return r>0&&t>=n||r<0&&t<=n?n:t})},100);return()=>clearInterval(o)},[n,s]),__name(formatToken,"formatToken"),__name(formatTime,"formatTime"),$.createElement(C,{columnGap:1},$.createElement(C,{paddingLeft:1,paddingRight:0},$.createElement(v,{color:_t(Ot[r]),bold:!0},"⌘")),$.createElement(C,null,$.createElement(v,{color:"#E4CCFF",wrap:"wrap"},e)),$.createElement(C,{columnGap:1},$.createElement(v,{dimColor:!0},`(${formatTime(t)}`),$.createElement(v,{dimColor:!0},"•"),$.createElement(v,{color:"gray"},"↑"),$.createElement(v,{dimColor:!0},`${formatToken(Math.round(s))}`),$.createElement(v,{dimColor:!0},"•"),$.createElement(C,{columnGap:1},$.createElement(v,{bold:!0,color:"gray"},"esc"),$.createElement(v,{dimColor:!0},"to interrupt)"))))},"Status"),Nt=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=A(process.cwd()),[s,i]=A([]),[a,c]=A(0),[m,p]=A(0),g=n.trim()?15:10,f=F((e,t=process.cwd())=>{if(!e.trim())return[];const n=[],r=e.toLowerCase(),o=__name((e,s=0)=>{if(!(s>8))try{B(e).forEach(i=>{const a=d(e,i);try{const e=z(a),c=l(t,a),u=c.toLowerCase();(i.toLowerCase().includes(r)||u.includes(r))&&n.push({name:c,path:a,isDirectory:e.isDirectory()}),e.isDirectory()&&(["node_modules"].includes(i)||o(a,s+1))}catch(e){}})}catch(e){}},"searchRecursively");return o(t),n.sort((e,t)=>{const n=e.name.toLowerCase(),o=t.name.toLowerCase(),s=n===r,i=o===r;if(s&&!i)return-1;if(!s&&i)return 1;const a=n.split("/").pop()||"",c=o.split("/").pop()||"",l=a.includes(r),u=c.includes(r);if(l&&!u)return-1;if(!l&&u)return 1;const d=e.name.split("/").length,m=t.name.split("/").length;return d!==m?d-m:e.name.localeCompare(t.name)}),n.slice(0,50)},[]),y=F(e=>{try{const t=B(e),n=[];"/"!==e&&n.push({name:"..",path:u(e),isDirectory:!0}),t.forEach(t=>{const r=d(e,t);try{const e=z(r);n.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),n.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),i(n),c(0),p(0)}catch{}},[]);I(()=>{if(n.trim()){const e=f(n);i(e),c(0),p(0)}else y(r)},[r,y,n,f]),S((r,i)=>{if(i.escape)t();else if(i.upArrow)c(e=>{const t=Math.max(0,e-1);return t<m&&p(t),t});else if(i.downArrow)c(e=>{const t=Math.min(s.length-1,e+1);return t>=m+g&&p(t-g+1),t});else if(i.return){const t=s[a];if(!t)return;return void(t.isDirectory&&!n.trim()?o(h(t.path)):e(t.path))}});const w=s.slice(m,m+g);return $.createElement(C,{flexDirection:"column",paddingLeft:2},$.createElement(C,{marginBottom:1,flexDirection:"column"},$.createElement(v,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),$.createElement(v,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • Enter to select/open • Esc to close")),0===w.length?$.createElement(v,{color:"dim"},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):w.map((e,t)=>{const n=m+t,r=e.name;return $.createElement(v,{key:e.path,color:n===a?"white":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList"),Lt=[{command:"/resume",description:"Resume a past conversation"},{command:"/clear",description:"Clear the conversation"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"}],Bt=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=A(0),s=R(()=>{if(!n)return Lt;const e=n.toLowerCase();return Lt.map(t=>{const n=t.command.toLowerCase(),r=t.description.toLowerCase();let o=0;return n.startsWith("/"+e)?o+=100:n.includes(e)&&(o+=50),r.includes(e)&&(o+=25),{...t,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]);return I(()=>{o(0)},[n]),S((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>Math.max(0,e-1));else if(i.downArrow)o(e=>Math.min(s.length-1,e+1));else if(i.return){const t=s[r];return void(t&&e(t.command))}}),0===s.length?$.createElement(C,{flexDirection:"column",paddingLeft:2},$.createElement(v,{color:"dim"},"No commands found")):$.createElement(C,{flexDirection:"column",paddingLeft:2},$.createElement(C,{columnGap:4},$.createElement(C,{flexDirection:"column"},s.map((e,t)=>$.createElement(v,{key:e.command,color:r===t?"white":"dim"},e.command))),$.createElement(C,{flexDirection:"column"},s.map((e,t)=>$.createElement(v,{key:e.command,color:r===t?"white":"dim"},e.description)))))},"CommandMenu"),zt=__name(({onSelectSession:e,onClose:t})=>{const[r,o]=A([]),[s,i]=A(0),[a,c]=A(!0);I(()=>{l()},[]);const l=__name(async()=>{c(!0);const e=await yt.listSessions();o(e.slice(0,30)),c(!1)},"loadSessions");if(S((n,o)=>{o.escape?t():o.upArrow?i(e=>Math.max(0,e-1)):o.downArrow?i(e=>Math.min(r.length-1,e+1)):o.return&&r.length>0&&s<r.length&&e(r[s].id)}),a)return $.createElement(C,{flexDirection:"column",paddingLeft:2},$.createElement(v,{color:"gray"},"Loading sessions..."));if(0===r.length)return $.createElement(C,{flexDirection:"column",paddingLeft:2},$.createElement(v,{color:"gray"},"No previous sessions found"),$.createElement(v,{color:"dim",dimColor:!0},"Press ESC to go back"));const u=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),d=__name((e,t=45)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return $.createElement(C,{flexDirection:"column",paddingLeft:2},$.createElement(v,{color:"cyan",bold:!0},"Resume Session"),$.createElement(v,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),$.createElement(C,{marginTop:1}),$.createElement(C,{columnGap:2,marginBottom:1},$.createElement(C,{width:5},$.createElement(v,{color:"gray"}," ")),$.createElement(C,{width:13},$.createElement(v,{color:"gray"},"Modified")),$.createElement(C,{width:20},$.createElement(v,{color:"gray"},"Git Branch")),$.createElement(C,{width:11},$.createElement(v,{color:"gray"},"# Messages")),$.createElement(C,null,$.createElement(v,{color:"gray"},"Summary"))),$.createElement(C,{columnGap:2},$.createElement(C,{flexDirection:"column",width:5},r.map((e,t)=>$.createElement(v,{key:`sel-${t}`,color:s===t?"cyan":"gray"},s===t?`${n.pointer} ${t+1}.`:` ${t+1}.`))),$.createElement(C,{flexDirection:"column",width:13},r.map((e,t)=>$.createElement(v,{key:`mod-${e.id}`,color:s===t?"white":"gray"},u(e.lastModified)))),$.createElement(C,{flexDirection:"column",width:20},r.map((e,t)=>$.createElement(v,{key:`branch-${e.id}`,color:s===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),$.createElement(C,{flexDirection:"column",width:11},r.map((e,t)=>$.createElement(v,{key:`msg-${e.id}`,color:s===t?"white":"gray"},e.messageCount))),$.createElement(C,{flexDirection:"column"},r.map((e,t)=>$.createElement(v,{key:`summary-${e.id}`,color:s===t?"white":"gray"},d(e.firstMessage))))))},"SessionsResumeTable"),Wt=__name(({usage:e})=>{if(!e)return null;const t=__name(e=>e>=1e3?`${Math.round(e/1e3)}K`:e.toString(),"formatNumber"),n=Math.min(e.current/e.limit*100,100),r=__name(e=>e>=90?"red":e>=70?"yellow":"gray","getColor");return $.createElement(C,{paddingRight:1},$.createElement(v,{color:r(n),dimColor:!0},n.toFixed(1),"% context used (",t(e.current),"/",t(e.limit),")"))},"ContextUsage");async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=ee(n),s=await o.metadata();if(!s.width||!s.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const i=1200;let a,c,{width:l,height:u}=s;(l>i||u>i)&&(l>u?(u=Math.round(u*i/l),l=i):(l=Math.round(l*i/u),u=i)),t.includes("png")&&s.hasAlpha?(a=await o.resize(l,u,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(a=await o.resize(l,u,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const d=a.length;return{compressedBase64:a.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:d,compressionRatio:r/d}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}async function detectClipboardImage(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasImage())return null;let t=null;try{if(t=await e.default.getImageBase64(),!t){const n=e.default.getImageBase64();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}if(!t||0===t.length)return null;if(t.length>32e6)return console.log("Image too large:",t.length,"bytes"),null;try{const e=await compressImageForSharing(t,"image/png");return e?{data:e.compressedBase64,mediaType:e.mediaType}:(console.log("Failed to compress clipboard image"),null)}catch(e){return console.log("Failed to process clipboard image:",e),null}}catch(e){return null}}async function detectClipboardText(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasText())return null;let t=null;try{if(t=await e.default.getText(),!t){const n=e.default.getText();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}return t&&0!==t.length?t:null}catch(e){return null}}function processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};let r=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");return r=r.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),{isPasteStart:t,isPasteEnd:n,cleanedContent:r}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}__name(compressImageForSharing,"compressImageForSharing"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode");var qt=__name(()=>$.createElement(C,{flexDirection:"column",paddingLeft:2},$.createElement(v,{color:"dim",bold:!0},"Available Shortcuts:"),$.createElement(C,{columnGap:4},$.createElement(C,{flexDirection:"column"},$.createElement(v,{color:"dim"},"! for bash mode"),$.createElement(v,{color:"dim"},"/ for commands"),$.createElement(v,{color:"dim"},"@ for file paths")),$.createElement(C,{flexDirection:"column"},$.createElement(v,{color:"dim"},"double tap esc to clear input"),$.createElement(v,{color:"dim"},"shift + ⏎ for newline"),$.createElement(v,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Gt=__name(({input:e,onSubmit:t,setInput:r,showCursor:o=!0,placeholder:s="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:c,setFileSearchQuery:u,onCommand:d,contextUsage:m,shareInfo:h,showShareNotification:p,unshareNotificationMessage:g,updateStatus:f,updateFailedInfo:y})=>{const[w,b]=A(0),[E,x]=A(!1),[k,T]=A(!1),[P,I]=A(!1),[M,j]=A(!1),[O,_]=A(""),[U,N]=A(!1),[L,B]=A(null),[z,W]=A([]),[q,G]=A([]),[J,V]=A(""),H=D(!1),[K,Y]=A(!1),Q=F(()=>{r(""),T(!1),j(!1),_(""),N(!1),W([]),G([]),V(""),Y(!1),b(e=>e+1)},[r]),Z=F(e=>{if(0===e.length)return e;let t=e.length;for(;t>0&&/\s/.test(e[t-1]);)t--;for(;t>0&&!/\s/.test(e[t-1]);)t--;return e.slice(0,t)},[]),ee=F(()=>{const t=Z(e);r(t),b(e=>e+1)},[e,Z,r]);function handlePastedContent(t){if(t.length>200){const n=`[Text#${z.length+1}]`;W(e=>[...e,t]),r(e+n),b(e=>e+1)}else r(e+t),b(e=>e+1)}S(async(t,n)=>{if(!n.ctrl&&!n.meta&&!n.shift){if(""===t)return void Q();if(""===t)return void ee()}if(n.meta&&n.delete)return H.current=!0,void ee();if(n.meta&&n.backspace)Q();else if(n.alt&&n.backspace)ee();else{if(n.ctrl&&"w"===t)return H.current=!0,void ee();if(n.meta&&"w"===t)return H.current=!0,void Q();if(n.meta&&"v"===t||n.ctrl&&"v"===t){if(n.ctrl&&"darwin"===process.platform){const t=e,n=await detectClipboardImage();if(n){const e=`[Image#${q.length+1}]`;G(e=>[...e,n]),r(t+e),b(e=>e+1)}else{const e=await detectClipboardText();e&&handlePastedContent(e)}return void(H.current=!0)}}else{if((n.ctrl||n.meta)&&"u"===t)return H.current=!0,void Q();if(n.ctrl&&t)switch(t.toLowerCase()){case"k":case"a":return void Q();case"z":return I(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100)}if(n.escape){if(U)return N(!1),r(J),void b(e=>e+1);const e=Date.now(),t=500;return L&&e-L<t?(Q(),B(null)):(B(e),setTimeout(()=>B(null),t)),x(!1),void T(!1)}E&&(n.backspace||n.delete)&&0===e.length&&x(!1)}}}),__name(handlePastedContent,"handlePastedContent");const te=F(async t=>{const n=processBracketedPaste(t);if(n.isPasteStart&&!K){if(Y(!0),n.isPasteEnd){Y(!1);const t=await detectClipboardImage();if(t){const n=`[Image#${q.length+1}]`;G(e=>[...e,t]),r(e+n),b(e=>e+1)}else if(n.cleanedContent)handlePastedContent(n.cleanedContent);else{const e=await detectClipboardText();e&&handlePastedContent(e)}return}return}if(K&&!n.isPasteEnd)return;if(K&&n.isPasteEnd){Y(!1);const e=await detectClipboardImage();if(e){const t=`[Image#${q.length+1}]`;G(t=>[...t,e]),r(n.cleanedContent+t),b(e=>e+1)}else{const e=await detectClipboardText();e?handlePastedContent(e):n.cleanedContent&&handlePastedContent(n.cleanedContent)}return}if(n.isPasteEnd&&!n.isPasteStart)return;if(H.current)return void(H.current=!1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!E)return x(!0),r(""),void b(e=>e+1);if("!"===s&&!k)return x(!1),T(!0),r(""),void b(e=>e+1);"/"!==s||M||(j(!0),_(""))}if(M){const e=t.lastIndexOf("/");if(-1!==e){const n=t.substring(e+1);_(n)}}if("@"!==s||i||(a(!0),u("")),i)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!1),u("");else{const n=t.substring(e+1);n.includes("/")||n.includes(".")?(a(!1),u("")):u(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);u(e),a(!1)}else u(n)}}E&&(t!==e||t.length<e.length)&&x(!1),0===t.length&&(T(!1),j(!1),_(""),N(!1),G([]),W([]),u(""),V(""),Y(!1)),r(t)},[E,e,r,i,a,k,K,q]),ne=F(async()=>{if(E)return void x(!1);let n=e.trim(),r=[];const o=q.length>0,s=z.length>0;if(!k&&o){const e=[];q.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!k&&s){let e=n;z.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:k?"bash":"user",images:r}),T(!1),j(!1),_(""),G([]),W([])},[t,E,e,k,q]),re=F(t=>{const n=l(process.cwd(),t);let o;if(i&&""!==c){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+n:n}else o=`${e}${n}`;r(o),a(!1),u(""),b(e=>e+1)},[r,a,e,i,c,u]),oe=F(()=>{a(!1),u("")},[a,u]),se=F(t=>{"/resume"===t?(V(e),j(!1),_(""),N(!0),r(""),b(e=>e+1)):(j(!1),_(""),r(""),b(e=>e+1),d&&d(t))},[d,r,e]),ie=F(()=>{j(!1),_(""),r(""),b(e=>e+1)},[r]),ae=F(e=>{N(!1),r(""),V(""),b(e=>e+1),d&&d(`/resume:${e}`)},[d]),ce=F(()=>{N(!1),r(J),b(e=>e+1)},[J]),le=R(()=>!E&&0===e.length&&!k&&!U,[E,e,k,M,U]),ue=__name(()=>E||i||M||U||P?0:le||k?3:4,"getBottomMargin");return $.createElement(C,{width:"100%",flexDirection:"column",marginBottom:ue()},!U&&$.createElement(C,{borderStyle:"round",borderColor:k?"green":"gray",paddingX:1,paddingY:0,width:"100%"},$.createElement(v,{color:k?"green":"dim"},k?"!":n.pointer),$.createElement(C,{flexGrow:1,paddingLeft:1},$.createElement(X,{key:w,value:e,placeholder:s,onChange:te,onSubmit:()=>{i||M||U||ne()},showCursor:o}))),E&&$.createElement(qt,null),P&&$.createElement(C,{paddingTop:1},$.createElement(v,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&$.createElement(Nt,{onSelectFile:re,onClose:oe,searchQuery:c}),M&&$.createElement(Bt,{onSelectCommand:se,onClose:ie,searchQuery:O}),U&&$.createElement(zt,{onSelectSession:ae,onClose:ce}),le&&$.createElement(C,{flexDirection:"row",justifyContent:"space-between",paddingLeft:2,paddingRight:2},$.createElement(v,{color:"dim"},"? for shortcuts"),$.createElement(C,{flexDirection:"row"},f&&$.createElement(C,{marginRight:2},$.createElement(v,{color:"green",dimColor:!0},`${n.tick} Command Code updated: v${f.updatedFrom} ${n.arrowRight} v${f.updatedTo}`)),y&&$.createElement(C,{marginRight:2},$.createElement(v,{color:"yellow",dimColor:!0},n.info," Update available:"," ",y.currentVersion," ",n.arrowRight," ",y.latestVersion)),$.createElement(Wt,{usage:m||null}))),k&&$.createElement(C,{paddingLeft:2},$.createElement(v,{color:"green"},"! for bash mode")),p&&h&&$.createElement(C,{paddingLeft:2},$.createElement(v,{color:"#E4CCFF"},"🔗 SHARED: ",h.url," (copied to clipboard)")),g&&$.createElement(C,{paddingLeft:2},$.createElement(v,{color:g.includes("NOT SHARED")?"red":"#E4CCFF"},g)))},"InputBox"),Jt=$.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,outputTokens:m=0,contextUsage:h,shareInfo:p,showShareNotification:g,unshareNotificationMessage:f,updateStatus:y,updateFailedInfo:w})=>{const[b,E]=A(0);return I(()=>{if(!t)return void E(0);const e=setInterval(()=>{E(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),$.createElement(C,{flexDirection:"column"},$.createElement(jt,{messages:e}),(t||n.isExecuting)&&$.createElement(Ut,{tokens:m,timeElapsed:b,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),$.createElement(Gt,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:h,shareInfo:p,showShareNotification:g,unshareNotificationMessage:f,updateStatus:y,updateFailedInfo:w}))}),Vt=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:r}=T(),[o,s]=A([]),[i,a]=A(0),[c,l]=A(!0),[u,d]=A(0),m=30;I(()=>{h()},[]);const h=__name(async()=>{l(!0);const e=await yt.listSessions();s(e),l(!1)},"loadSessions");if(S((t,n)=>{n.upArrow?a(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):n.downArrow?a(e=>{const t=Math.min(o.length-1,e+1);return t>=u+m&&d(t-m+1),t}):n.return?o.length>0&&e(o[i].id):(n.escape||n.ctrl&&"c"===t)&&r()}),c)return $.createElement(C,{flexDirection:"column",paddingLeft:2,paddingTop:1},$.createElement(v,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5),i=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:s<7?`${s} day${s>1?"s":""} ago`:1===i?"1 week ago":`${i} weeks ago`},"formatRelativeTime"),g=__name((e,t=50)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===o.length)return $.createElement(C,{flexDirection:"column"},$.createElement(v,{color:"gray"},"No sessions available"));const f=o.slice(u,u+m),y=u;return $.createElement(C,{flexDirection:"column",paddingLeft:1},o.length>m&&$.createElement(C,{marginBottom:1},$.createElement(v,{color:"dim"},"Showing ",u+1,"-",Math.min(u+m,o.length)," ","of ",o.length," sessions",u>0&&" (↑ for more)",u+m<o.length&&" (↓ for more)")),$.createElement(C,{columnGap:2,marginBottom:1},$.createElement(C,{width:7},$.createElement(v,{color:"gray"}," ")),$.createElement(C,{width:13},$.createElement(v,{color:"gray"},"Modified")),$.createElement(C,{width:11},$.createElement(v,{color:"gray"},"# Messages")),$.createElement(C,{width:20},$.createElement(v,{color:"gray"},"Git Branch")),$.createElement(C,null,$.createElement(v,{color:"gray"},"Summary"))),$.createElement(C,{columnGap:2},$.createElement(C,{flexDirection:"column",width:7},f.map((e,t)=>{const r=y+t;return $.createElement(v,{key:`sel-${r}`,color:i===r?"cyan":"gray"},i===r?`${n.pointer} ${r+1}.`:` ${r+1}.`)})),$.createElement(C,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return $.createElement(v,{key:`mod-${e.id}`,color:i===n?"white":"gray"},p(e.lastModified))})),$.createElement(C,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return $.createElement(v,{key:`msg-${e.id}`,color:i===n?"white":"gray"},e.messageCount)})),$.createElement(C,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return $.createElement(v,{key:`branch-${e.id}`,color:i===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),$.createElement(C,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return $.createElement(v,{key:`summary-${e.id}`,color:i===n?"white":"gray"},g(e.firstMessage))}))))},"SessionTable"),Ht=__name(({onTrust:e,onExit:t})=>{const{exit:r}=T(),[o,s]=A(1),i=process.cwd().replace(process.env.HOME||"","~");return S((n,i)=>{i.upArrow||i.downArrow?s(1===o?2:1):i.return?1===o?e():(t(),r()):"1"===n?e():("2"===n||i.escape||i.ctrl&&"c"===n)&&(t(),r())}),$.createElement(C,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1},$.createElement(v,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),$.createElement(C,{marginTop:1},$.createElement(v,{color:"gray"},i)),$.createElement(C,{marginTop:1,flexDirection:"column"},$.createElement(v,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),$.createElement(C,{marginTop:1},$.createElement(v,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),$.createElement(C,{marginTop:1,flexDirection:"column"},$.createElement(C,null,$.createElement(v,{color:1===o?"cyan":"gray"},1===o?n.pointer:" "," 1. Yes, proceed")),$.createElement(C,null,$.createElement(v,{color:2===o?"cyan":"gray"},2===o?n.pointer:" "," 2. No, exit"))))},"TrustPrompt"),Kt=class extends te{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||c.join(e,".command-code","settings.local.json"),this.config=this.getDefaultConfig(),this.loadConfig()}getDefaultConfig(){return{enabled:!0,defaultScope:"session",autoApprove:{create:!1,edit:!1,delete:!1,execute:!1,shellCommands:!1},trustedPaths:[],trustedCommands:[],sessionPermissions:new Map,projectPermissions:new Map,sessionShellPermissions:new Map,projectShellPermissions:new Map}}async loadConfig(){try{const e=await o.readFile(this.configPath,"utf-8"),t=JSON.parse(e);t.permissions&&("acceptEdits"===t.permissions.defaultMode&&(this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0),t.permissions.allow&&t.permissions.allow.forEach(e=>{if(e.startsWith("Bash(")&&e.endsWith(")")){const t=e.slice(5,-1);this.config.trustedCommands.push(t)}}))}catch(e){}}async requestPermission(e){if(!this.config.enabled)return{allowed:!0};const t=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)?{allowed:!0}:this.config.sessionPermissions.has(t)?{allowed:this.config.sessionPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("permission-request",e,n=>{this.handleUserChoice(e,n).then(t)})})}async handleUserChoice(e,t){const n=e.action,r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionPermissions.set(n,!0);break;case"project":await this.createCommandCodeSettings(),this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getFileKey(e){const t=c.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=c.relative(this.projectRoot,e);return this.config.trustedPaths.some(n=>t.startsWith(n)||e.startsWith(n))}async requestShellPermission(e){if(!this.config.enabled)return{allowed:!0};const t=this.getCommandKey(e);return this.config.autoApprove.shellCommands||this.isTrustedCommand(e.command)?{allowed:!0}:this.config.projectShellPermissions.has(t)?{allowed:this.config.projectShellPermissions.get(t)||!1,scope:"project"}:this.config.sessionShellPermissions.has(t)?{allowed:this.config.sessionShellPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("shell-permission-request",e,n=>{this.handleShellUserChoice(e,n).then(t)})})}async handleShellUserChoice(e,t){const n=this.getCommandKey(e),r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionShellPermissions.set(n,!0);break;case"project":await this.addCommandToSettings(e.command),this.config.projectShellPermissions.set(n,!0)}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getCommandKey(e){return`${e.command.split(" ")[0]}:${e.args?e.args.join(" "):""}`.trim()}isTrustedCommand(e){return this.config.trustedCommands.some(t=>{if(t===e)return!0;if(t.endsWith(":*")){const n=t.slice(0,-2);return e===n||e.startsWith(n+" ")}return e.startsWith(t)})}clearSessionPermissions(){this.config.sessionPermissions.clear(),this.config.sessionShellPermissions.clear()}clearProjectPermissions(){this.config.projectPermissions.clear(),this.config.projectShellPermissions.clear()}setAutoApprove(e,t){this.config.autoApprove[e]=t}addTrustedPath(e){this.config.trustedPaths.includes(e)||this.config.trustedPaths.push(e)}removeTrustedPath(e){const t=this.config.trustedPaths.indexOf(e);t>-1&&this.config.trustedPaths.splice(t,1)}addTrustedCommand(e){this.config.trustedCommands.includes(e)||this.config.trustedCommands.push(e)}removeTrustedCommand(e){const t=this.config.trustedCommands.indexOf(e);t>-1&&this.config.trustedCommands.splice(t,1)}setEnabled(e){this.config.enabled=e}getConfig(){return{...this.config}}async createCommandCodeSettings(){const e=c.join(this.projectRoot,".command-code"),t=c.join(e,"settings.local.json");try{await o.mkdir(e,{recursive:!0});let n={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await o.readFile(t,"utf-8"),r=JSON.parse(e);r.permissions&&r.permissions.allow&&(n.permissions.allow=[...new Set([...r.permissions.allow,...n.permissions.allow])]),r.permissions&&r.permissions.deny&&(n.permissions.deny=r.permissions.deny)}catch(e){}await o.writeFile(t,JSON.stringify(n,null,2),"utf-8")}catch(e){console.error("Failed to create .command-code settings:",e)}}async addCommandToSettings(e){const t=c.join(this.projectRoot,".command-code"),n=c.join(t,"settings.local.json"),r=`Bash(${e.split(" ")[0]}:*)`;try{let e;await o.mkdir(t,{recursive:!0});try{const t=await o.readFile(n,"utf-8");e=JSON.parse(t)}catch(t){e={permissions:{allow:[],deny:[],defaultMode:"ask"}}}e.permissions||(e.permissions={allow:[],deny:[],defaultMode:"ask"}),e.permissions.allow||(e.permissions.allow=[]),e.permissions.allow.includes(r)||e.permissions.allow.push(r),await o.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .command-code settings:",e)}}},Yt=__name((e={})=>{const[t,n]=A(null),[r,o]=A(null),[s,i]=A(!1);return I(()=>{const t=e.projectRoot||process.cwd(),r=new Kt(t);return r.on("permission-request",(t,n)=>{o(t),i(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),i(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:F(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:F(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:F(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),i(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),i(!1)}},[t]),clearSessionPermissions:F(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:F(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:F((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:F(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions"),Qt=__name(({request:e,onResponse:t})=>{const[r]=A(0),o=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, for this session only",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"Yes, and always allow modifying files in this project",value:"yes-project",description:"Allow and remember for this project",scope:"project"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],s=__name(e=>{const n=o.find(t=>t.value===e.value);n&&t(n)},"handleSelect"),i=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),a=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const t=c.basename(e.filePath),n=c.relative(process.cwd(),e.filePath);return n&&!n.startsWith("../")&&n.length<50?n:t||e.filePath}catch{return e.filePath}},"getDisplayPath"),l=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return $.createElement(C,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},$.createElement(C,{marginBottom:1},$.createElement(v,{bold:!0,color:"yellow"},l())),$.createElement(C,{marginBottom:1},$.createElement(v,{bold:!0},"Do you want to ",i()," ",$.createElement(v,{color:"cyan"},a()),"?")),$.createElement(ne,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>$.createElement(v,{color:"cyan"},e?n.pointer:" "),itemComponent:({label:e,isSelected:t})=>$.createElement(v,{color:t?"cyan":"white"},e.includes("(")?$.createElement($.Fragment,null,e.split("(")[0],$.createElement(v,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),Zt=__name(({request:e,onResponse:t})=>{const[r]=A(0),o=__name(()=>e.command.split(" ")[0],"getCommandName"),s=__name(()=>e.workingDirectory||process.cwd(),"getProjectPath"),i=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, for this session only",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:`Yes, and don't ask again for ${o()} commands in ${s()}`,value:"yes-project",description:"Allow and remember for this project",scope:"project"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],a=__name(e=>{const n=i.find(t=>t.value===e.value);n&&t(n)},"handleSelect"),c=__name(()=>{const t=e.args&&e.args.length>0?`${e.command} ${e.args.join(" ")}`:e.command;return t.length>60?t.substring(0,57)+"...":t},"getCommandDisplay");return $.createElement(C,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},$.createElement(C,{marginBottom:1},$.createElement(v,{bold:!0,color:"yellow"},"Execute Shell Command")),$.createElement(C,{marginBottom:1},$.createElement(v,{bold:!0},"Command Code needs to execute ",$.createElement(v,{color:"cyan"},c()),".")),e.workingDirectory&&$.createElement(C,{marginBottom:1},$.createElement(v,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&$.createElement(C,{marginBottom:1},$.createElement(v,{color:"gray",italic:!0},e.description)),$.createElement(ne,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:r,indicatorComponent:({isSelected:e})=>$.createElement(v,{color:"cyan"},e?n.pointer:" "),itemComponent:({label:e,isSelected:t})=>$.createElement(v,{color:t?"cyan":"white"},e)}))},"ShellPermissionPrompt"),Xt=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole"),en=__name(({staticKey:e})=>$.createElement(x,{items:[{staticKey:e}],key:e},()=>$.createElement(v,{key:e},"\0")),"Responsive"),{setText:tn}=V,nn=__name(({resume:e=!1,continue:t=!1,updateStatus:n,updateFailedInfo:r})=>{const{exit:o}=T(),[s,i]=A(""),[a,c]=A("Ready..."),[l,u]=A(n),{stdout:d}=P(),[m,h]=A(!1),[p,g]=A(0),{executeBash:f,executionState:y}=qe(),[w,b]=A(""),[E,x]=A([]),[v,k]=A(!1),[F,R]=A([]),[M,j]=A(crypto.randomUUID()),[O,_]=A(!1),[U,N]=A(!1),[L,B]=A(!1),[z,W]=A(!1),[q,G]=A(!0),[J,V]=A(!1),[H,K]=A(0),[Y,Q]=A(null),[Z,X]=A(null),ee=D(Z);I(()=>{ee.current=Z},[Z]);const[te,ne]=A(!1),[re,oe]=A(""),se=D([]),ie=D(null),[ae,ce]=A(null),{requestShellPermission:le,service:ue,respondToPrompt:me,clearSessionPermissions:he,setEnabled:pe}=Yt({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{ce({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),ie.current&&c("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{ce({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),ie.current&&c("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?c("Permission granted"):c("Permission denied")},"onPermissionResponse")});I(()=>{(async()=>{if(await yt.isProjectInitialized())if(W(!0),G(!1),t){const e=await yt.listSessions();if(e.length>0){const t=e[0];ve(t.id)}}else e&&_(!0);else B(!0),G(!1)})()},[e,t,o]),I(()=>{se.current=F},[F]),I(()=>{if(!v)return;const e=setInterval(()=>{c(Le())},7e3);return()=>clearInterval(e)},[v]),S((e,t)=>{if(t.ctrl&&"c"===e&&o(),t.escape)if(ae)me({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),ae.resolve(!1),ce(null),c("Permission denied");else if(v&&ie.current){ie.current.interrupt(!0),k(!1),c("Interrupted by user");const e=Ie("Interrupted by user");x(t=>[...t,e])}t.meta||t.ctrl}),I(()=>{const e=__name(()=>{Xt(),g(e=>e+1)},"handleResize");if(d)return d.on("resize",e),()=>{d.off("resize",e)}},[d]),I(()=>{ie.current||!z||O||U||(ie.current=new Dt({onFeedUpdate:__name(e=>{x(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...se.current];return se.current=[],R([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{K(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Q(e)},"onContextUsageUpdate"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&ue){const e={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${t.args?.join(" ")||""}`};return ue.requestShellPermission(e).then(e=>e.allowed)}if(ue){const n={action:e.includes("edit")?"edit":e.includes("write")?"create":e.includes("delete")?"delete":"edit",filePath:t.filePath||t.file_path||t.path||t.absolutePath||"unknown",description:t.description||`${e} operation`};return ue.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=ee.current;return e?{sessionId:M,secret:e.secret}:null},"getShareInfo")},M),(async()=>{await Ee()})())},[M,O,U,z]);const ge=D(!1),fe=__name(async({role:e,input:t,images:n})=>{if(t.length)if(l&&u(null),K(0),"bash"===e){if(ge.current)return;ge.current=!0;const e=Re(t);x([...E,e]),i(""),await f(t,e=>{x(e)},()=>{Xt(),g(e=>e+1)}),ge.current=!1}else{if(v)return R(e=>[...e,t]),void i("");if(ge.current)return;ge.current=!0,k(!0),c(Le()),i("");try{ie.current&&await ie.current.sendMessage(t,n)}catch(e){"Interrupted by user"===e.message||"InterruptedError"===e.name||"AbortError"===e.name||(console.error("Chat error:",e),c("Error occurred"))}finally{k(!1),"Interrupted by user"!==a&&"Permission denied"!==a&&c("Ready..."),ge.current=!1}}},"handleSubmit"),ye=__name(()=>{const e=`**Command Code v0.0.4-alpha.4**\n\nAlways review Command Code's responses, especially when running code. Command Code has read access to files in the current directory and can run commands and edit files with your permission.\n\n**Usage Modes:**\n• REPL: **cmd** (interactive session)\n\nRun **cmd -h** for all command line options\n\n**Common Tasks:**\n• Ask questions about your codebase > How does foo.ts work?\n• Edit files > Update bar.ts to...\n• Fix errors > Fix build error...\n• Run commands > /help\n• Run bash commands > !ls\n\n**Interactive Mode Commands:**\n${Lt.filter(e=>"/help"!==e.command).map(e=>`**${e.command}** - ${e.description}`).join("\n")}`;x(t=>[...t,Me(e)])},"handleHelpCommand"),we=__name(()=>{if(x([]),Xt(),ie.current){ie.current=null;const e=crypto.randomUUID();j(e),ie.current=new Dt({onFeedUpdate:__name(e=>{x(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...se.current];return se.current=[],R([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{K(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Q(e)},"onContextUsageUpdate"),getShareInfo:__name(()=>{const t=ee.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e),Ee().catch(console.error)}g(e=>e+1),Q(null),K(0)},"handleClearCommand"),be=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await ve(t)}switch(e){case"/exit":o();break;case"/clear":we();break;case"/help":ye();break;case"/permissions":c("Permissions are enabled");break;case"/permissions:enable":pe(!0),c("File edit permissions enabled");break;case"/permissions:disable":pe(!1),c("File edit permissions disabled");break;case"/permissions:clear":he(),c("Session permissions cleared");break;case"/share":xe();break;case"/unshare":Ce()}},"handleCommand"),Ee=__name(async()=>{const e=ie.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&X({url:t.url,secret:t.secret})}},"loadShareInfo"),xe=__name(async()=>{if(M){if(Z)return await tn(Z.url),c(""),ne(!0),void setTimeout(()=>{ne(!1)},3e3);try{c("Creating share link...");const e=ie.current?.getMessages()||[],t=At.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=getApiBaseUrl(),r=await fetch(`${n}${de.CREATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:M,messages:t})});if(!r.ok)throw new Error(`Failed to create share: ${r.statusText}`);const o=await r.json(),s={url:o.url,secret:o.secret};X(s);const i=ie.current?.getSessionManager();i&&await i.saveShareInfo({url:o.url,secret:o.secret}),await tn(o.url),c(""),ne(!0),setTimeout(()=>{ne(!1)},5e3)}catch(e){c(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else c("No active session to share")},"handleShareCommand"),Ce=__name(async()=>{if(M){if(!Z)return oe("🔓 NOT SHARED: Session is not currently shared"),void setTimeout(()=>oe(""),5e3);try{c("Removing share link...");const e=getApiBaseUrl(),t=await fetch(`${e}${de.DELETE}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:M,secret:Z.secret})});if(!t.ok)throw new Error(`Failed to unshare: ${t.statusText}`);const n=ie.current?.getSessionManager();n&&await n.deleteShareInfo(),oe("🔓 UNSHARED: Sharing has stopped"),c(""),X(null),setTimeout(()=>{oe("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;c(t),setTimeout(()=>c(""),5e3)}}else c("No active session to unshare")},"handleUnshareCommand"),ve=__name(async e=>{try{x([]),ie.current=null,j(e),_(!1),N(!0),await new Promise(e=>setTimeout(e,100)),ie.current=new Dt({onFeedUpdate:__name(e=>{x(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...se.current];return se.current=[],R([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{K(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Q(e)},"onContextUsageUpdate"),getShareInfo:__name(()=>{const t=ee.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const t=await ie.current.loadSession(e);await Ee(),x(t),Xt(),g(e=>e+1)}catch(e){console.error("Failed to load session:",e),_(!0),j(crypto.randomUUID())}},"handleSelectSession"),Se=__name(async()=>{x([]),ie.current=null,j(crypto.randomUUID()),_(!1),N(!1)},"handleNewSession"),ke=__name(async()=>{try{await yt.initializeProject(),B(!1),e?(console.log("No conversations found to resume."),V(!0),o()):W(!0)}catch(e){console.error("Failed to initialize project:",e),B(!1),V(!0),o()}},"handleTrust"),Te=__name(()=>{o()},"handleNoTrust");if(J)return null;if(L)return $.createElement($.Fragment,null,$.createElement(en,{staticKey:p}),$.createElement(Ht,{onTrust:ke,onExit:Te}));if(q)return null;if(O)return $.createElement(Vt,{onSelectSession:ve,onNewSession:Se});if(!z)return null;if(ae){if("shell_command"===ae.toolName){const e=ae.params;return $.createElement(C,{flexDirection:"column",width:"100%"},$.createElement(Mt,{staticKey:p,feed:E,showHeader:!0}),$.createElement(C,{marginY:1},$.createElement(Zt,{request:e,onResponse:e=>{me(e);const t="no"!==e.value;ae.resolve(t),ce(null),c(t?"Shell command allowed":"Shell command denied")}})))}{const e={action:ae.toolName.includes("edit")?"edit":ae.toolName.includes("write")?"create":ae.toolName.includes("delete")?"delete":"edit",filePath:ae.params.filePath||ae.params.file_path||ae.params.path||ae.params.absolutePath||ae.params.notebook_path||"unknown",description:`Allow ${ae.toolName} operation`,newContent:ae.params.new_content||ae.params.content};return $.createElement(C,{flexDirection:"column",width:"100%"},$.createElement(Mt,{staticKey:p,feed:E,showHeader:!0}),$.createElement(C,{marginY:1},$.createElement(Qt,{request:e,onResponse:e=>{me(e);const t="no"!==e.value;ae.resolve(t),ce(null),c(t?"File operation allowed":"File operation denied")}})))}}return $.createElement(C,{flexDirection:"column",width:"100%"},$.createElement(Mt,{staticKey:p,feed:E,showHeader:!0}),$.createElement(Jt,{queuedMessages:F,isProcessing:v,executionState:y,status:a,input:s,setInput:i,onSubmit:fe,showFileList:m,setShowFileList:h,fileSearchQuery:w,setFileSearchQuery:b,onCommand:be,outputTokens:H,contextUsage:Y,shareInfo:Z,showShareNotification:te,unshareNotificationMessage:re,updateStatus:l,updateFailedInfo:r}))},"InteractiveCLI");function getPackageJson(){const e=import.meta.url,t=oe(e),n=u(t);return JSON.parse(_(d(n,"./../package.json"),"utf8"))}__name(getPackageJson,"getPackageJson");var rn=getPackageJson(),on=c.join(g.homedir(),".command-code"),sn=c.join(on,"update-status.json"),an=c.join(on,"update-failed.json");function ensureCommandCodeDir(){O.existsSync(on)||O.mkdirSync(on,{recursive:!0})}async function checkForUpdateAvailable(){try{const e=f("npm view command-code versions --json",{encoding:"utf-8"}),t=JSON.parse(e),n=rn.version,r=n.includes("alpha"),o=t.filter(e=>!e.includes("alpha")&&!e.includes("beta")),s=t.filter(e=>e.includes("alpha"));let i=n,a=!1;if(o.length>0){const e=o.sort(re.rcompare)[0];re.gt(e,n)&&(i=e,a=!0)}if(!a&&r&&s.length>0){const e=s.sort(re.rcompare)[0];re.gt(e,n)&&(i=e,a=!0)}return{currentVersion:n,latestVersion:i,updateAvailable:a}}catch(e){return null}}async function performAutoUpdate(){const e=await checkForUpdateAvailable();if(!e||!e.updateAvailable)return{success:!1};console.log(`Updating command-code from v${e.currentVersion} to v${e.latestVersion}...`);try{f(`npm update -g command-code@${e.latestVersion}`,{stdio:"inherit"}),ensureCommandCodeDir();const t={updatedFrom:e.currentVersion,updatedTo:e.latestVersion,updatedAt:Date.now()};return O.writeFileSync(sn,JSON.stringify(t,null,2)),console.log(`\nSuccessfully updated to version ${e.latestVersion}\n`),console.log("Please restart command-code to use the new version."),{success:!0}}catch(t){console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm update -g command-code"),ensureCommandCodeDir();const n={currentVersion:e.currentVersion,latestVersion:e.latestVersion,failedAt:Date.now()};return O.writeFileSync(an,JSON.stringify(n,null,2)),{success:!1,updateInfo:e}}}function getUpdateStatus(){try{if(ensureCommandCodeDir(),O.existsSync(sn)){const e=JSON.parse(O.readFileSync(sn,"utf-8"));return O.unlinkSync(sn),e}}catch(e){}return null}function getFailedUpdateInfo(){try{if(ensureCommandCodeDir(),O.existsSync(an)){const e=JSON.parse(O.readFileSync(an,"utf-8"));return O.unlinkSync(an),{currentVersion:e.currentVersion,latestVersion:e.latestVersion}}}catch(e){}return null}__name(ensureCommandCodeDir,"ensureCommandCodeDir"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(performAutoUpdate,"performAutoUpdate"),__name(getUpdateStatus,"getUpdateStatus"),__name(getFailedUpdateInfo,"getFailedUpdateInfo");var cn=__name(async(e={})=>{process.stdin.isTTY||(console.error("Error: Interactive mode requires a TTY terminal."),console.error("Please run this command directly in your terminal, not through a pipe or redirect."),process.exit(1));const t=getUpdateStatus(),n=getFailedUpdateInfo();enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()}),(e.resume||e.continue)&&await yt.isProjectInitialized()&&0===(await yt.listSessions()).length&&(console.log("No conversations found to resume."),process.exit(0)),k($.createElement(nn,{resume:e.resume,continue:e.continue,updateStatus:t,updateFailedInfo:n}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})},"interactive"),{red:ln,yellow:un}=ie,dn=__name((e="ERROR: ",t,n=!0,r=!0)=>{if(t){if(console.log(),n?(console.log(`${ae.error} ${ln(e)}`),console.log(`${ae.error} ${ln("ERROR →")} ${t.name}`),console.log(`${ae.info} ${ln("REASON →")} ${t.message}`),console.log(`${ae.info} ${ln("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${ae.warning} ${un(e)}\n`),!r)return!1;process.exit(0)}},"handleError"),mn=__name(()=>{process.on("unhandledRejection",e=>{dn(se`CRITICAL: Unhandled Promise Rejection!
3
+ This is an unexpected error. Please file a bug report at https://github.com/LangbaseInc/command-code/issues/new`,e)})},"handleUnhandledErrors");async function checkAuthAndPromptLogin(){try{if(!await pe.get("anthropic")){console.log(ie.white(Rt)),console.log(ie.dim("Welcome to Command by Langbase. Agentic coding agent.")),console.log(""),console.log(`${t.warning} Authentication required to use Command Code`),console.log("You need to sign in with your Claude Pro/Max subscription or API key."),console.log("");const e=E.createInterface({input:process.stdin,output:process.stdout}),n=await e.question(`Would you like to sign in now? ${ie.dim("(y/n)")}: `);e.close();const r=n.trim().toLowerCase();if(""!==r&&"y"!==r&&"yes"!==r)return console.log(""),console.log(`${t.info} You can authenticate later by running: cmd auth login`),!1;console.log(""),console.log(`${t.arrowUp} Running: cmd auth login`),console.log("");try{return f("cmd auth login",{stdio:"inherit",cwd:process.cwd()}),await pe.get("anthropic")?(console.log(""),console.log(`${t.tick} Authentication successful! Starting Command Code...`),console.log(""),!0):(console.log(""),console.log(`${t.cross} Authentication failed. Please try again with: cmd auth login`),!1)}catch(e){return console.log(""),console.log(`${t.cross} Login command failed. Please run: cmd auth login`),!1}}return!0}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var hn=getPackageJson(),pn=process.cwd();global.COMMAND_CODE_CWD=pn;var gn=new le("CommandCode");mn(),(async()=>{(await performAutoUpdate()).success&&process.exit(0);const t=new e;async function commanderAction(e){switch(await checkAuthAndPromptLogin()||process.exit(1),!0){case e.resume:cn({resume:!0});break;case e.continue:cn({continue:!0});break;default:cn()}}__name(commanderAction,"commanderAction"),t.name(hn.name).description(hn.description||"Command Code — Coding Agent by Langbase").version(hn.version).option("-r, --resume","Resume a conversation").option("-c, --continue","Continue the last conversation").action(commanderAction),t.addCommand(we),t.addCommand(fe),t.addCommand(be),t.hook("preAction",()=>{gn.debug("Command starting...")}),t.hook("postAction",()=>{gn.debug("Command completed.")}),t.parse()})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "command-code",
3
- "version": "0.0.4-alpha.3",
3
+ "version": "0.0.4-alpha.4",
4
4
  "description": "Command Code — Coding Agent by Langbase",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",
@@ -52,8 +52,7 @@
52
52
  "minimatch": "^10.0.3",
53
53
  "react": "^19.1.1",
54
54
  "react-devtools-core": "^4.28.5",
55
- "registry-auth-token": "^5.1.0",
56
- "registry-url": "^7.2.0",
55
+ "semver": "^7.7.2",
57
56
  "sharp": "^0.34.3",
58
57
  "strip-ansi": "^7.1.0",
59
58
  "uuid": "^11.1.0",
@@ -64,6 +63,7 @@
64
63
  "@types/marked-terminal": "^6.1.1",
65
64
  "@types/node": "^24.2.0",
66
65
  "@types/react": "^19.0.3",
66
+ "@types/semver": "^7.7.1",
67
67
  "javascript-obfuscator": "^4.1.1",
68
68
  "pkg": "^5.8.1",
69
69
  "rollup-plugin-obfuscator": "^1.1.0",