command-code 0.0.4-alpha.5 → 0.0.4-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import"dotenv/config";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 p}from"path";import*as h from"os";import g from"os";import*as f from"@clack/prompts";import{confirm as y,isCancel as w,cancel as b,note as E,password as C,select as x,outro as v}from"@clack/prompts";import S from"picocolors";import k from"open";import T from"crypto";import{z as P}from"zod";import{Static as A,Box as $,Text as I,useInput as D,render as F,useApp as j,useStdout as M}from"ink";import R,{useState as U,useEffect as O,useRef as _,useCallback as L,useMemo as N}from"react";import{execSync as B,spawn as z}from"child_process";import*as W from"fs";import q,{readFileSync as G,promises as J,constants as V,existsSync as H,readdirSync as K,statSync as Q}from"fs";import{minimatch as Y}from"minimatch";import{glob as Z}from"glob";import X from"@sindresorhus/slugify";import{MessageStream as ee}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import te from"@crosscopy/clipboard";import ne from"ink-gradient";import{setOptions as re,parse as oe}from"marked";import se from"marked-terminal";import*as ie from"diff";import ae from"ink-text-input";import ce from"sharp";import{EventEmitter as le}from"events";import ue from"ink-select-input";import de from"semver";import{fileURLToPath as me}from"url";import pe from"dedent";import he from"chalk";import ge from"log-symbols";import fe from"readline/promises";var ye=Object.defineProperty,__name=(e,t)=>ye(e,"name",{value:t,configurable:!0}),we=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 be="/alpha/generate",Ee={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",DATA:"/alpha/share/data",APPEND:"/alpha/share/append",CONNECT:"/alpha/share/connect"},Ce={GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug/rules/:ruleId",LIST:"/alpha/taste/:projectSlug/rules"},xe={ALPHA:{TASTE:{GET:new RegExp("/alpha/taste/[a-z0-9-]+"),UPDATE:new RegExp("/alpha/taste/[a-z0-9-]+/update"),DELETE:new RegExp("/alpha/taste/[a-z0-9-]+/rules/[a-z0-9-]+"),LIST:new RegExp("/alpha/taste/[a-z0-9-]+/rules")}}};function getStudioAuthUrl(e){return"dev"===e?"http://localhost:3000/settings/keys":"staging"===e?"https://staging.commandcode.ai/settings/keys":"https://commandcode.ai/settings/keys"}Object.values(xe.ALPHA.TASTE),Ee.CREATE,Ee.DELETE,Ee.APPEND,Object.values(Ce),__name(getStudioAuthUrl,"getStudioAuthUrl");var ve=new we("Config"),Se=a.join(h.homedir(),".command-code-config.json");async function loadConfig(){try{return parseJSON(await r.readFile(Se,"utf-8"))||{}}catch{return{}}}async function saveConfig(e){await r.writeFile(Se,JSON.stringify(e,null,2))}__name(loadConfig,"loadConfig"),__name(saveConfig,"saveConfig");var ke,Te,Pe=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?ve.info(`${e}: ${JSON.stringify(t)}`):ve.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),ve.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?ve.info("No configuration values set"):(ve.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({}),ve.success("Configuration reset successfully")})),Ae=new we("Info"),$e=new e("info").description("Display system information").option("-v, --verbose","Show verbose output").action(e=>{if(Ae.info("System Information:"),console.log("-------------------"),console.log(`${t.info} Date: ${formatDate()}`),console.log(`${t.info} Platform: ${h.platform()}`),console.log(`${t.info} Architecture: ${h.arch()}`),console.log(`${t.info} CPUs: ${h.cpus().length}`),console.log(`${t.info} Memory: ${Math.round(h.totalmem()/1024/1024/1024)} GB`),console.log(`${t.info} Home Directory: ${h.homedir()}`),e.verbose){console.log("\nDetailed CPU Information:"),h.cpus().forEach((e,t)=>{console.log(` CPU ${t}: ${e.model} @ ${e.speed} MHz`)}),console.log("\nNetwork Interfaces:");const e=h.networkInterfaces();Object.keys(e).forEach(t=>{const n=e[t];n&&n.forEach(e=>{"IPv4"!==e.family||e.internal||console.log(` ${t}: ${e.address}`)})})}Ae.success("Information displayed successfully!")});function heading({text:e,sub:t,dim:n,green:r}){return r?`${S.bgGreen(S.black(` ${e} `))} ${t&&t}`:n?`${S.bgBlack(S.white(` ${e} `))} ${t&&t}`:`${S.bold(S.bgCyan(S.black(` ${e} `)))} ${t&&t}`}__name(heading,"heading"),(e=>{e.OAuth=P.object({type:P.literal("oauth"),refresh:P.string(),access:P.string(),expires:P.number()}),e.ApiKey=P.object({type:P.literal("api"),key:P.string()}),e.Info=P.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const t=__name(()=>c.join(g.homedir(),".command-code"),"getAuthDir"),n=__name(()=>c.join(t(),"models.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")})(ke||(ke={})),(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 T.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return T.createHash("sha256").update(e).digest("base64url")}function generateState(){return T.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 ke.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 ke.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 ke.remove("anthropic");const o=await r.json();return await ke.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 ke.remove("anthropic")}}}async function getValidAccessToken(){const e=await ke.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")})(Te||(Te={}));var Ie=__name(()=>c.join(g.homedir(),".command-code"),"getAuthDir"),De=__name(()=>c.join(Ie(),"auth.json"),"getAuthFile");async function loginAction(){try{const e=process.argv.includes("--dev"),n=process.argv.includes("--staging"),r=getStudioAuthUrl(e?"dev":n?"staging":"prod");console.log("\n"),f.intro(heading({text:"Command Code Authentication",sub:""}));const s=await y({message:`Open the authentication page? ${S.dim("— copy your API key from there and paste it here.")}`});w(s)&&(b(`${t.cross} Login cancelled.`),process.exit(0)),s&&(await k(r),E(S.yellow("Please copy your API key from the opened page and paste it here.")));const i=await C({message:"Paste your API key string:",mask:"*"});w(i)&&(b(`${t.cross} No API key provided.`),process.exit(0)),i.trim()||(console.log(`${t.cross} No API key provided.`),process.exit(1));const a=Ie(),c=De();await o.mkdir(a,{recursive:!0}),await o.writeFile(c,JSON.stringify({apiKey:i},null,2)),await o.chmod(c,384);const l=await x({message:"Select provider",options:[{value:"anthropic",label:"Anthropic"},{value:"command",label:"Command Code"}]});let u="",d={anthropic:{oauth:!1},command:{command:!1}};if(w(l))b(`${t.cross} No provider selected.`);else if("anthropic"===l){u="anthropic";const e=await x({message:"Login method",options:[{value:"anthropic-oauth",label:"Claude Pro/Max"}]});if(w(e))b(`${t.cross} No login method selected.`);else if("anthropic-oauth"===e){const e=await anthropicAuth();d.anthropic={oauth:e}}}let m=`Authentication successful. API key is stored in ${c}`;m+="anthropic"===u&&d.anthropic.oauth?" and OAuth tokens are set up for Anthropic.":".",v(S.green(m)),process.exit(0)}catch(e){console.error(`${t.cross} Login failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function anthropicAuth(){try{const{url:e,verifier:n,state:r}=Te.createAuthorizationUrl();await y({message:"Open the Anthropic auth page?"})&&(await k(e),E(S.yellow("Please copy your authorization code from the opened page and paste it here.")));const o=await C({message:"Paste your authorization code:",mask:"*"});w(o)&&(b(`${t.cross} No API key provided.`),process.exit(1)),o.trim()||(console.log(`${t.cross} No authorization code provided`),process.exit(1));const s=o.split("#")[0].trim();return await Te.exchangeCodeForTokens(s,n,r),!0}catch(e){b(`${t.cross} Anthropic OAuth failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function logoutAction(){try{const e=De();await o.unlink(e),v(S.green("Successfully logged out from Command Code")),process.exit(0)}catch(e){b(`${t.cross} Logout failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function getAuthKey(){try{const e=De(),t=await o.readFile(e,"utf-8");return JSON.parse(t).apiKey||null}catch{return null}}async function statusAction(){try{await getAuthKey()||(b(`${t.cross} Not authenticated. Please login using "cmd auth login".`),process.exit(1)),v(S.green(`${t.tick} Authenticated with CLAI`)),process.exit(0)}catch(e){b(`${t.cross} Status check failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}__name(loginAction,"loginAction"),__name(anthropicAuth,"anthropicAuth"),__name(logoutAction,"logoutAction"),__name(getAuthKey,"getAuthKey"),__name(statusAction,"statusAction");var Fe=new e("auth").description("Manage authentication with CLAI");Fe.command("login").description("Login with CLAI account").allowUnknownOption().allowExcessArguments().action(loginAction),Fe.command("logout").description("Remove stored authentication").action(logoutAction),Fe.command("status").description("Show authentication status").action(statusAction);var je=new e("login").description("Login with CLAI account").allowUnknownOption().allowExcessArguments().action(loginAction),Me=new e("logout").description("Remove stored authentication").action(logoutAction),Re=new e("status").description("Show authentication status").action(statusAction),Ue=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{const s=z("/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"),Oe=__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"),_e="read_file",Le="edit_file",Ne="write_file",Be="read_directory",ze="read_multiple_files",We="grep",qe="shell_command",Ge="think",Je="todo_write",Ve="web_search",He="web_fetch",Ke=__name(e=>e===Ve,"isWebSearchTool"),Qe=P.object({id:P.string(),timestamp:P.number(),type:P.literal("image"),source:P.object({type:P.enum(["base64","url"]),media_type:P.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:P.string()})}),Ye=P.object({id:P.string(),timestamp:P.number(),input:P.string(),output:P.string().optional(),metadata:P.record(P.string(),P.any()).optional(),images:P.array(Qe).optional().default([])}),Ze=Ye.extend({role:P.literal("user")}),Xe=Ye.extend({role:P.literal("assistant")}),et=Ye.extend({role:P.literal("tool"),name:P.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),tt=Ye.extend({role:P.literal("bash"),command:P.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),nt=Ye.extend({role:P.literal("system")}),rt=P.discriminatedUnion("role",[Ze,Xe,et,tt,nt]),ot=__name((e,t)=>rt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),st=__name(e=>rt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),it=__name((e,t,n)=>rt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),at=__name(e=>rt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),ct=__name(e=>rt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),lt=__name((e,t)=>{const n={...e,output:t};return rt.parse(n)},"updateEntryWithOutput"),ut=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),dt=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),mt=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),pt=["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…"],ht=__name(()=>pt[Math.floor(Math.random()*pt.length)],"getRandomLLMStatus"),gt=__name(e=>{switch(e){case _e:return"Read";case Le:return"Edit";case Ne:return"Write";case Be:return"List";case ze:return"Read Multiple";case We:return"Search";case qe:return"Shell";case Je:return"Todos";case Ge:return"Thinking…";case Ve:return"Web Search";case He:return"Web Fetch";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),ft=__name((e,t)=>{try{switch(e){case _e:case Ne:case Le:return t.absolutePath||t.file_path||t.filePath||t.path||"file";case Be:return t.path||"directory";case We:return`"${t.pattern}" in ${t.path||"files"}`;case qe:return t.command&&t.args&&t.args.length>0?`${t.command} ${t.args.join(" ")}`:t.command||"";case Je:return`${t.todos?t.todos.length:0} items`;case Ge:return t.content||"planning";case ze:const e=t.include||[];return Array.isArray(e)?e.join(", "):"multiple files";case Ve:return t.query||"search";case He:return t.url||"fetch";default:return JSON.stringify(t||{})}}catch{return"parameters"}},"getToolInputContent"),yt=__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"),wt=__name(()=>{const[e,t]=U({isExecuting:!1,currentCommand:null});return{executeBash:L(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Ue(e,{timeout:3e4,cwd:process.cwd()}),o=Oe(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]=lt(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]=lt(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution"),bt=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 Et({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Ct(e,o,n,r);case 401:return new xt(e,o,n,r);case 403:return new vt(e,o,n,r);case 404:return new St(e,o,n,r);case 409:return new kt(e,o,n,r);case 422:return new Tt(e,o,n,r);case 429:return new Pt(e,o,n,r);default:return e>=500?new At(e,o,n,r):new _APIError(e,o,n,r)}}},Et=class extends bt{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)}},Ct=class extends bt{static{__name(this,"BadRequestError")}status=400},xt=class extends bt{static{__name(this,"AuthenticationError")}status=401},vt=class extends bt{static{__name(this,"PermissionDeniedError")}status=403},St=class extends bt{static{__name(this,"NotFoundError")}status=404},kt=class extends bt{static{__name(this,"ConflictError")}status=409},Tt=class extends bt{static{__name(this,"UnprocessableEntityError")}status=422},Pt=class extends bt{static{__name(this,"RateLimitError")}status=429},At=class extends bt{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=await this.buildHeaders({headers:e.headers});let o;try{o=await this.makeRequest({url:n,options:e,headers:r})}catch(e){throw new Et({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}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...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,{headers:n,method:t.method,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}),bt.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"})}};function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var It=P.object({absolutePath:P.string().describe("The absolute path to the file to read"),offset:P.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:P.number().optional().describe("Optional number of lines to read")});P.object({content:P.union([P.string(),P.instanceof(Buffer)]),contentType:P.enum(["text","binary"]),fileType:P.string(),size:P.number(),linesRead:P.number().optional()});var Dt=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 Dt("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,W.constants.F_OK|W.constants.R_OK)}catch{throw new Dt(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await r.stat(s)).isFile())throw new Dt("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 Dt("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new Dt("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new Dt("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 Dt)throw e;throw new Dt(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var Ft={".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",...Ft}[t]||"unknown"}function isBinaryFile(e){return Object.values(Ft).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 jt={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=It.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")},Mt=P.object({filePath:P.string().describe("The absolute path to the file to edit"),oldValue:P.string().describe("The text to replace"),newValue:P.string().describe("The new text to insert"),replacementCount:P.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:P.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 J.access(t,V.F_OK|V.R_OK|V.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 J.writeFile(t,u,"utf-8"),console.log(`Made ${d} replacement${1!==d?"s":""} in ${a.basename(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}P.object({path:P.string(),replacementsCount:P.number(),oldContent:P.string(),newContent:P.string()}),P.object({name:P.string(),message:P.string(),code:P.string().optional()}),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),__name(formatOutput2,"formatOutput");var Rt={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=Mt.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")},Ut=P.object({path:P.string().describe("The absolute path to the directory to read"),exclude:P.array(P.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:P.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});P.object({files:P.array(P.string()),directories:P.array(P.string())});var Ot=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 Ot("Path must be absolute, not relative","INVALID_PATH");try{if(!(await r.stat(t)).isDirectory())throw new Ot("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Ot)throw e;throw new Ot(`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 Ot)throw e;throw new Ot(`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(Y(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 _t={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=Ut.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")},Lt=P.object({filePath:P.string().describe("The absolute path where the file should be written"),content:P.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);return H(n)||await s(n,{recursive:!0}),await i(e,t,"utf-8"),{path:e,bytesWritten:Buffer.byteLength(t,"utf-8")}}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}`}P.object({success:P.boolean(),message:P.string(),path:P.string().optional()}),__name(writeFile2,"writeFile"),__name(formatOutput4,"formatOutput");var Nt={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=Lt.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")},Bt=P.object({include:P.array(P.string()).describe("Array of glob patterns to include files"),exclude:P.array(P.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:P.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:P.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:P.string().optional().describe("Base directory for relative paths. Default: current working directory")}),zt=P.object({filePath:P.string(),content:P.string(),fileType:P.string(),size:P.number()});P.object({content:P.string(),filesRead:P.array(P.string()),errors:P.array(P.object({file:P.string(),error:P.string()})),fileDetails:P.array(zt)});var Wt=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},qt=["**/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 Z(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 Wt("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(...qt);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 Wt)throw e;throw new Wt(`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 Gt={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=Bt.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")},Jt=P.object({pattern:P.string().min(1,"Pattern is required"),include:P.array(P.string()).optional(),directory:P.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=z(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 Vt={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=Jt.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")},Ht=P.object({command:P.string().min(1,"Command cannot be empty"),args:P.array(P.string()).optional(),directory:P.string().optional(),timeout:P.number().optional()}),Kt=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 Kt("Command cannot be empty","EMPTY_COMMAND");let c;if(r){if(a.isAbsolute(r))throw new Kt("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 Kt(`Path is not a directory: ${r}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof Kt)throw e;throw new Kt(`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 Kt(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",a,c,e))}},s),d=z(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 Kt(`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 Kt(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),c.trim(),t))})})}catch(e){if(e instanceof Kt)throw e;throw new Kt(`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 Qt={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=Ht.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 Yt={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 Zt=[jt,Rt,_t,Nt,Gt,Vt,Qt,Yt,{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}],Xt=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],en=new Map(Zt.map(e=>[e.name,e]));async function executeTool(e,t){const n=en.get(e);if(!n)throw new Error(`Tool "${e}" not found. Available tools: ${Array.from(en.keys()).join(", ")}`);try{return await n.execute(t)}catch(e){return e instanceof Error?`Error: ${e.message}`:"Error: Unknown error occurred"}}function getToolSchemas(){return[...Zt.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...Xt]}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 tn=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 X(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=B("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)t.push({id:o,timestamp:r,role:"assistant",input:e.content,images:[]});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){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=ft(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}else if("server_tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=ft(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}n.trim()&&t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),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(){const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(getApiBaseUrl,"getApiBaseUrl");var nn=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 q.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 B("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return B("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=B("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=B("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=B("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():[]}}function getProjectConfigPath(){const e=tn.getProjectsBasePath(),t=tn.getCurrentProjectDirName();return a.join(e,t,"config.json")}async function loadProjectConfig(){try{const e=getProjectConfigPath();return parseJSON(await r.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveProjectConfig(e){try{const t=getProjectConfigPath();await tn.initializeProject(),await r.writeFile(t,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save project config: ${e}`)}}async function isTasteLearningEnabled(){return(await loadProjectConfig()).tasteLearning??!1}async function isTasteUsageEnabled(){return(await loadProjectConfig()).tasteUsage??!1}async function setTasteConfig(e,t){const n=await loadProjectConfig();n.tasteLearning=e,n.tasteUsage=t,await saveProjectConfig(n)}__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"),__name(getProjectConfigPath,"getProjectConfigPath"),__name(loadProjectConfig,"loadProjectConfig"),__name(saveProjectConfig,"saveProjectConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(isTasteUsageEnabled,"isTasteUsageEnabled"),__name(setTasteConfig,"setTasteConfig");var rn=new we("ContextEngine"),on=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 tn(t)}async interrupt(e=!1){if(this.abortController){this.abortController.abort(),this.abortController=null,rn.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(),rn.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=ot("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>rn.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=ot(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=>rn.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 Te.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};rn.debug(`🔍 API Call: ${o.model}, ${this.messages.length} messages, ${n.length} tools, streaming: true`);const i=await isTasteLearningEnabled(),a=await isTasteUsageEnabled(),c={"x-project-slug":tn.getCurrentProjectDirName(),"x-taste-learning":i.toString(),"x-taste-usage":a.toString()};r&&(c["x-oauth-token"]=`Bearer ${r}`);const l=await this.request.post({body:s,stream:!0,endpoint:be,signal:this.abortController?.signal,headers:c}),u=ee.fromReadableStream(l);u.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let d,m=null;u.on("error",e=>{m="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});try{d=await u.finalMessage()}catch(e){if(m)throw m;if("AbortError"===e.name||e.message?.includes("aborted")||this.abortController?.signal.aborted)throw new Error("Interrupted by user");if(e instanceof Ct&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))throw new Error("Insufficient credits");throw e}if(m)throw m;if("usage"in d){const e=d.usage;if(e?.input_tokens){const t=calculateUsageFromResponse(e);this.contextTokensUsed=t,this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:2e5})}}let p="";const h=d.content.filter(e=>"tool_use"===e.type),g=d.content.filter(e=>"server_tool_use"===e.type);if(g.length>0){for(const e of d.content)if("text"===e.type)p+=e.text;else if("server_tool_use"===e.type){if(p.trim()){const e=st(p.trim());this.callbacks.onFeedUpdate(e),p=""}const t=ft(e.name,e.input),n=it(e.name,t),r=Ke(e.name)?"Found 10 results":"Content fetched",o=lt(n,r);this.callbacks.onFeedUpdate(o)}if(p.trim()){const e=st(p.trim());this.callbacks.onFeedUpdate(e)}}if(e=d.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===h.length){const t=d.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===g.length){const t=st(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>rn.error(`Failed to save messages: ${e}`))}if(0!==g.length&&this.sessionManager.saveMessages(this.messages).catch(e=>rn.error(`Failed to save messages: ${e}`)),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=ot(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>rn.error(`Failed to save messages: ${e}`));continue}}break}const f=d.content.filter(e=>"text"!==e.type||e.text.trim().length>0);f.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:f}));const y=[],w=new Set;let b=!1;for(const e of h){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=ft(e.name,e.input),n="edit_file"===e.name?e.input:void 0,r=it(e.name,t,n),o=lt(r,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o),b=!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),y.push({type:"tool_result",tool_use_id:e.id,content:n}),w.add(e.id);const o=ft(e.name,e.input),s="edit_file"===e.name?e.input:void 0,i=it(e.name,o,s),a=lt(i,n);this.callbacks.onFeedUpdate(a)}catch(t){const n=t instanceof Error?t.message:"Unknown error";y.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}),w.add(e.id);const r=ft(e.name,e.input),o="edit_file"===e.name?e.input:void 0,s=it(e.name,r,o),i=lt(s,ut(n));this.callbacks.onFeedUpdate(i)}}if(b){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?w.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const E=[...y];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){E.push({type:"text",text:t});const e=ot(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:E})),this.sessionManager.saveMessages(this.messages).catch(e=>rn.error(`Failed to save messages: ${e}`))}catch(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||this.abortController?.signal.aborted)throw rn.debug("Request interrupted by user"),new Error("Interrupted by user");if(e instanceof Ct&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))throw new Error("Insufficient credits");throw 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 rn.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){rn.error(`Failed to sync message to share: ${e}`)}}))}async syncMessageToShare(e,t){try{const n=nn.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:Ee.APPEND})}catch(e){throw e}}};function Markdown({children:e,...t}){const n={...t};re({renderer:new se(n),breaks:!0,gfm:!0});const r=oe(e);return R.createElement(I,null,r.toString().trim())}function AssistantMessage({content:e}){return R.createElement($,null,R.createElement(I,null,n.nodejs),R.createElement($,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},R.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage");var sn={"Interrupted by user":"Interrupted by user","Insufficient credits":"You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: https://commandcode.ai/settings/billing"};function UserMessage({content:e}){const t="Interrupted by user"===e||"Insufficient credits"===e;let r=t?sn[e]:e;return R.createElement($,null,R.createElement(I,{color:t?"red":"dim"},n.pointer),R.createElement($,{marginLeft:1},R.createElement(I,{color:t?"red":void 0,dimColor:!t,wrap:"wrap"},r)))}__name(UserMessage,"UserMessage");var an="#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=ie.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)}),R.createElement($,{flexDirection:"column"},R.createElement(I,{color:"gray"},"Updated ",R.createElement(I,{color:"white",bold:!0},n)," with ",R.createElement(I,{color:"#22C55E"},o)," addition",1!==o?"s":""," and ",R.createElement(I,{color:"#EF4444"},s)," removal",1!==s?"s":""),R.createElement($,{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++,R.createElement($,{key:`${t}-${r}-removed`,width:"100%"},R.createElement(I,{color:"gray"},i.toString().padStart(3)," "),R.createElement($,{backgroundColor:"#712F37"},R.createElement(I,null,"-"),R.createElement(I,null," ",n.replace(/\s/g," "))))):e.added?(i++,R.createElement($,{key:`${t}-${r}-added`,width:"100%"},R.createElement(I,{color:"gray"},i.toString().padStart(3)," "),R.createElement($,{backgroundColor:"#325B30"},R.createElement(I,null,"+"),R.createElement(I,null," ",n.replace(/\s/g," "))))):null):(i+=n.length,null)})))}function formatTodosForDisplay(e){const t=yt(e);return t?R.createElement($,{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 R.createElement($,{key:e.id||t,flexDirection:"row"},R.createElement($,{width:2},R.createElement(I,{color:r},n)),R.createElement(I,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):R.createElement(I,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,p;if(o)m="yellow",p="→";else if(s)m="red",p=n.nodejs;else if(a)m=an,p="✻";else if(c&&r){const e=yt(r),t=e?.every(e=>"completed"===e.status);m=t?"#22C55E":"#D4A017",p=n.nodejs}else m="#22C55E",p=n.nodejs;return R.createElement($,null,R.createElement(I,{color:m,italic:a},p),R.createElement($,{flexDirection:"column",marginLeft:1},R.createElement($,null,R.createElement(I,{bold:!a,color:a?an:void 0,italic:a},`${e} `),u&&R.createElement(I,null,R.createElement(Markdown,null,`(${t})`))),r&&R.createElement($,{columnGap:1},d&&R.createElement(I,null,"⎿"," "),c?formatTodosForDisplay(r):a?R.createElement($,{width:"100%",flexDirection:"column"},R.createElement(I,null," "),R.createElement(I,{color:an,wrap:"wrap",italic:!0},r)):l&&i?.oldValue&&i?.newValue?generateDiff(i.oldValue,i.newValue,t):R.createElement($,{width:"100%"},R.createElement(I,{color:s?"red":"",wrap:"wrap"},truncateToolOutputForDisplay(r)))),o&&R.createElement($,{columnGap:1},R.createElement(I,null,"⎿"," "),R.createElement(I,{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="✓"),R.createElement($,null,R.createElement(I,{color:o},s),R.createElement($,{flexDirection:"column",marginLeft:1},R.createElement($,null,R.createElement(I,{color:"gray"},"$ "),R.createElement(I,{color:o,bold:!0},e)),R.createElement($,{columnGap:1},R.createElement(I,null,"⎿"," "),R.createElement(I,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}function SystemMessage({content:e}){return R.createElement($,{flexDirection:"column"},R.createElement(I,{wrap:"wrap"},R.createElement(Markdown,null,e)))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage"),__name(SystemMessage,"SystemMessage");var cn="\n ██████╗ ██████╗ ███╗ ███╗███╗ ███╗ █████╗ ███╗ ██╗██████╗\n██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔══██╗████╗ ██║██╔══██╗\n██║ ██║ ██║██╔████╔██║██╔████╔██║███████║██╔██╗ ██║██║ ██║\n██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║\n╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝\n ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝\n",ln=R.memo(({feed:e,showHeader:t=!1,staticKey:n})=>{const r=t?["header",...e]:e;return R.createElement(A,{items:r,key:n},e=>{if("header"===e)return R.createElement($,{key:"header",marginBottom:1},R.createElement(ne,{name:"vice"},R.createElement(I,null,cn),R.createElement(I,null,"Welcome to Command by Langbase. Agentic coding agent.")));const t=e,n=(()=>{switch(t.role){case"user":return R.createElement(UserMessage,{content:t.input});case"assistant":return R.createElement(AssistantMessage,{content:t.input});case"tool":return R.createElement(ToolMessage,{name:gt(t.name||""),input:t.input,output:t.output||"",isPending:mt(t),hasError:dt(t),metadata:t.metadata});case"bash":return R.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:mt(t),hasError:dt(t)});case"system":return R.createElement(SystemMessage,{content:t.input});default:return R.createElement(R.Fragment,null)}})();return R.createElement($,{key:t.id,marginBottom:1},n)})}),un=__name(({messages:e})=>0===e.length?null:R.createElement($,{borderStyle:"round",borderColor:"#D97706",padding:1,marginBottom:1},R.createElement($,{flexDirection:"column"},R.createElement($,{marginBottom:1},R.createElement(I,{color:"#D97706",bold:!0},"Queued Messages (",e.length,")")),e.map((t,n)=>R.createElement($,{key:n,marginBottom:n===e.length-1?0:1},R.createElement(I,{color:"gray"},"•"),R.createElement($,{marginLeft:1},R.createElement(I,{dimColor:!0},t.length>60?`${t.substring(0,60)}...`:t)))))),"QueuedMessages"),dn=["dim","dim2","normal","normal2","bright","bright2","brighter","brighter2","brightest","brightest","brighter2","brighter","bright2","bright","normal2","normal","dim2","dim"],mn=__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"),pn=__name(({status:e,timeElapsed:n,tokens:r})=>{const[o,s]=U(0),[i,a]=U(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 O(()=>{const e=setInterval(()=>{s(e=>(e+1)%dn.length)},120);return()=>clearInterval(e)},[]),O(()=>{if(i===r)return;const e=r-i,t=Math.max(1,Math.ceil(Math.abs(e)/20)),n=e>0?t:-t,o=setInterval(()=>{a(e=>{const t=e+n;return n>0&&t>=r||n<0&&t<=r?r:t})},100);return()=>clearInterval(o)},[r,i]),__name(formatToken,"formatToken"),__name(formatTime,"formatTime"),R.createElement($,{columnGap:1},R.createElement($,{paddingLeft:1,paddingRight:0},R.createElement(I,{color:mn(dn[o]),bold:!0},"⌘")),R.createElement($,null,R.createElement(I,{color:"#E4CCFF",wrap:"wrap"},e)),R.createElement($,{columnGap:1},R.createElement(I,{dimColor:!0},`(${formatTime(n)}`),R.createElement(I,{dimColor:!0},"•"),R.createElement(I,{color:"gray"},t.arrowDown),R.createElement(I,{dimColor:!0},`${formatToken(Math.round(i))}`),R.createElement(I,{dimColor:!0},"•"),R.createElement($,{columnGap:1},R.createElement(I,{bold:!0,color:"gray"},"esc"),R.createElement(I,{dimColor:!0},"to interrupt)"))))},"Status"),hn=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=U(process.cwd()),[s,i]=U([]),[a,c]=U(0),[m,h]=U(0),g=n.trim()?15:10,f=L((e,t=process.cwd())=>{if(!e.trim())return[];const n=[],r=e.toLowerCase(),o=__name((e,s=0)=>{if(!(s>8))try{K(e).forEach(i=>{const a=d(e,i);try{const e=Q(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=L(e=>{try{const t=K(e),n=[];"/"!==e&&n.push({name:"..",path:u(e),isDirectory:!0}),t.forEach(t=>{const r=d(e,t);try{const e=Q(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),h(0)}catch{}},[]);O(()=>{if(n.trim()){const e=f(n);i(e),c(0),h(0)}else y(r)},[r,y,n,f]),D((r,i)=>{if(i.escape)t();else if(i.upArrow)c(e=>{const t=Math.max(0,e-1);return t<m&&h(t),t});else if(i.downArrow)c(e=>{const t=Math.min(s.length-1,e+1);return t>=m+g&&h(t-g+1),t});else if(i.return){const t=s[a];if(!t)return;return void(t.isDirectory&&!n.trim()?o(p(t.path)):e(t.path))}});const w=s.slice(m,m+g);return R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement($,{marginBottom:1,flexDirection:"column"},R.createElement(I,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),R.createElement(I,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • Enter to select/open • Esc to close")),0===w.length?R.createElement(I,{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 R.createElement(I,{key:e.path,color:n===a?"white":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList"),gn=[{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:"/taste",description:"Manage Taste learning and usage"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"}],fn=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=U(0),s=N(()=>{if(!n)return gn;const e=n.toLowerCase();return gn.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 O(()=>{o(0)},[n]),D((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?R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement(I,{color:"dim"},"No commands found")):R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement($,{columnGap:4},R.createElement($,{flexDirection:"column"},s.map((e,t)=>R.createElement(I,{key:e.command,color:r===t?"white":"dim"},e.command))),R.createElement($,{flexDirection:"column"},s.map((e,t)=>R.createElement(I,{key:e.command,color:r===t?"white":"dim"},e.description)))))},"CommandMenu"),yn=__name(({onSelectSession:e,onClose:t})=>{const[r,o]=U([]),[s,i]=U(0),[a,c]=U(!0);O(()=>{l()},[]);const l=__name(async()=>{c(!0);const e=await tn.listSessions();o(e.slice(0,30)),c(!1)},"loadSessions");if(D((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 R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement(I,{color:"gray"},"Loading sessions..."));if(0===r.length)return R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement(I,{color:"gray"},"No previous sessions found"),R.createElement(I,{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 R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement(I,{color:"cyan",bold:!0},"Resume Session"),R.createElement(I,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),R.createElement($,{marginTop:1}),R.createElement($,{columnGap:2,marginBottom:1},R.createElement($,{width:5},R.createElement(I,{color:"gray"}," ")),R.createElement($,{width:13},R.createElement(I,{color:"gray"},"Modified")),R.createElement($,{width:20},R.createElement(I,{color:"gray"},"Git Branch")),R.createElement($,{width:11},R.createElement(I,{color:"gray"},"# Messages")),R.createElement($,null,R.createElement(I,{color:"gray"},"Summary"))),R.createElement($,{columnGap:2},R.createElement($,{flexDirection:"column",width:5},r.map((e,t)=>R.createElement(I,{key:`sel-${t}`,color:s===t?"cyan":"gray"},s===t?`${n.pointer} ${t+1}.`:` ${t+1}.`))),R.createElement($,{flexDirection:"column",width:13},r.map((e,t)=>R.createElement(I,{key:`mod-${e.id}`,color:s===t?"white":"gray"},u(e.lastModified)))),R.createElement($,{flexDirection:"column",width:20},r.map((e,t)=>R.createElement(I,{key:`branch-${e.id}`,color:s===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),R.createElement($,{flexDirection:"column",width:11},r.map((e,t)=>R.createElement(I,{key:`msg-${e.id}`,color:s===t?"white":"gray"},e.messageCount))),R.createElement($,{flexDirection:"column"},r.map((e,t)=>R.createElement(I,{key:`summary-${e.id}`,color:s===t?"white":"gray"},d(e.firstMessage))))))},"SessionsResumeTable"),wn=__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 R.createElement($,{paddingRight:1},R.createElement(I,{color:r(n),dimColor:!0},n.toFixed(1),"% context used (",t(e.current),"/",t(e.limit),")"))},"ContextUsage"),bn=__name(({tasteLearning:e,tasteUsage:t,showSeparator:n=!1})=>{if(!e&&!t)return null;const r=[];return e&&r.push("learn"),t&&r.push("use"),R.createElement($,null,R.createElement(I,{color:"green",dimColor:!0},"● taste ",r.join(" & ")),n&&R.createElement(I,{color:"gray",dimColor:!0}," • "))},"TasteStatus");async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=ce(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 En=__name(()=>R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement(I,{color:"dim",bold:!0},"Available Shortcuts:"),R.createElement($,{columnGap:4},R.createElement($,{flexDirection:"column"},R.createElement(I,{color:"dim"},"! for bash mode"),R.createElement(I,{color:"dim"},"/ for commands"),R.createElement(I,{color:"dim"},"@ for file paths")),R.createElement($,{flexDirection:"column"},R.createElement(I,{color:"dim"},"double tap esc to clear input"),R.createElement(I,{color:"dim"},"shift + ⏎ for newline"),R.createElement(I,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Cn=__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,tasteLearning:p=!1,tasteUsage:h=!1,shareInfo:g,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w,updateStatus:b,updateFailedInfo:E})=>{const[C,x]=U(0),[v,S]=U(!1),[k,T]=U(!1),[P,A]=U(!1),[F,j]=U(!1),[M,O]=U(""),[B,z]=U(!1),[W,q]=U(null),[G,J]=U([]),[V,H]=U([]),[K,Q]=U(""),Y=_(!1),[Z,X]=U(!1),ee=L(()=>{r(""),T(!1),j(!1),O(""),z(!1),J([]),H([]),Q(""),X(!1),x(e=>e+1)},[r]),te=L(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)},[]),ne=L(()=>{const t=te(e);r(t),x(e=>e+1)},[e,te,r]);function handlePastedContent(t){if(t.length>200){const n=`[Text#${G.length+1}]`;J(e=>[...e,t]),r(e+n),x(e=>e+1)}else r(e+t),x(e=>e+1)}D(async(t,n)=>{if(!n.ctrl&&!n.meta&&!n.shift){if(""===t)return void ee();if(""===t)return void ne()}if(n.meta&&n.delete)return Y.current=!0,void ne();if(n.meta&&n.backspace)ee();else if(n.alt&&n.backspace)ne();else{if(n.ctrl&&"w"===t)return Y.current=!0,void ne();if(n.meta&&"w"===t)return Y.current=!0,void ee();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#${V.length+1}]`;H(e=>[...e,n]),r(t+e),x(e=>e+1)}else{const e=await detectClipboardText();e&&handlePastedContent(e)}return void(Y.current=!0)}}else{if((n.ctrl||n.meta)&&"u"===t)return Y.current=!0,void ee();if(n.ctrl&&t)switch(t.toLowerCase()){case"k":case"a":return void ee();case"z":return A(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100)}if(n.escape){if(B)return z(!1),r(K),void x(e=>e+1);const e=Date.now(),t=500;return W&&e-W<t?(ee(),q(null)):(q(e),setTimeout(()=>q(null),t)),S(!1),void T(!1)}v&&(n.backspace||n.delete)&&0===e.length&&S(!1)}}}),__name(handlePastedContent,"handlePastedContent");const re=L(async t=>{const n=processBracketedPaste(t);if(n.isPasteStart&&!Z){if(X(!0),n.isPasteEnd){X(!1);const t=await detectClipboardImage();if(t){const n=`[Image#${V.length+1}]`;H(e=>[...e,t]),r(e+n),x(e=>e+1)}else if(n.cleanedContent)handlePastedContent(n.cleanedContent);else{const e=await detectClipboardText();e&&handlePastedContent(e)}return}return}if(Z&&!n.isPasteEnd)return;if(Z&&n.isPasteEnd){X(!1);const e=await detectClipboardImage();if(e){const t=`[Image#${V.length+1}]`;H(t=>[...t,e]),r(n.cleanedContent+t),x(e=>e+1)}else{const e=await detectClipboardText();e?handlePastedContent(e):n.cleanedContent&&handlePastedContent(n.cleanedContent)}return}if(n.isPasteEnd&&!n.isPasteStart)return;if(Y.current)return void(Y.current=!1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!v)return S(!0),r(""),void x(e=>e+1);if("!"===s&&!k)return S(!1),T(!0),r(""),void x(e=>e+1);"/"!==s||F||(j(!0),O(""))}if(F){const e=t.lastIndexOf("/");if(-1!==e){const n=t.substring(e+1);O(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)}}v&&(t!==e||t.length<e.length)&&S(!1),0===t.length&&(T(!1),j(!1),O(""),z(!1),H([]),J([]),u(""),Q(""),X(!1)),r(t)},[v,e,r,i,a,k,Z,V]),oe=L(async()=>{if(v)return void S(!1);let n=e.trim(),r=[];const o=V.length>0,s=G.length>0;if(!k&&o){const e=[];V.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;G.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),O(""),H([]),J([])},[t,v,e,k,V]),se=L(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(""),x(e=>e+1)},[r,a,e,i,c,u]),ie=L(()=>{a(!1),u("")},[a,u]),ce=L(t=>{"/resume"===t?(Q(e),j(!1),O(""),z(!0),r(""),x(e=>e+1)):(j(!1),O(""),r(""),x(e=>e+1),d&&d(t))},[d,r,e]),le=L(()=>{j(!1),O(""),r(""),x(e=>e+1)},[r]),ue=L(e=>{z(!1),r(""),Q(""),x(e=>e+1),d&&d(`/resume:${e}`)},[d]),de=L(()=>{z(!1),r(K),x(e=>e+1)},[K]),me=N(()=>!v&&0===e.length&&!k&&!B,[v,e,k,F,B]),pe=__name(()=>v||i||F||B||P?0:me||k?3:4,"getBottomMargin");return R.createElement($,{width:"100%",flexDirection:"column",marginBottom:pe()},!B&&R.createElement($,{borderStyle:"round",borderColor:k?"green":"gray",paddingX:1,paddingY:0,width:"100%"},R.createElement(I,{color:k?"green":"dim"},k?"!":n.pointer),R.createElement($,{flexGrow:1,paddingLeft:1},R.createElement(ae,{key:C,value:e,placeholder:s,onChange:re,onSubmit:()=>{i||F||B||oe()},showCursor:o}))),v&&R.createElement(En,null),P&&R.createElement($,{paddingTop:1},R.createElement(I,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&R.createElement(hn,{onSelectFile:se,onClose:ie,searchQuery:c}),F&&R.createElement(fn,{onSelectCommand:ce,onClose:le,searchQuery:M}),B&&R.createElement(yn,{onSelectSession:ue,onClose:de}),me&&R.createElement($,{flexDirection:"row",justifyContent:"space-between",paddingLeft:2,paddingRight:2},R.createElement(I,{color:"dim"},"? for shortcuts"),R.createElement($,{flexDirection:"row"},b&&R.createElement($,{marginRight:2},R.createElement(I,{color:"green",dimColor:!0},`${n.tick} Command Code updated: v${b.updatedFrom} ${n.arrowRight} v${b.updatedTo}`)),E&&R.createElement($,{marginRight:2},R.createElement(I,{color:"yellow",dimColor:!0},n.info," Update available:"," ",E.currentVersion," ",n.arrowRight," ",E.latestVersion)),R.createElement(bn,{tasteLearning:p,tasteUsage:h,showSeparator:!!m}),R.createElement(wn,{usage:m||null}))),k&&R.createElement($,{paddingLeft:2},R.createElement(I,{color:"green"},"! for bash mode")),f&&g&&R.createElement($,{paddingLeft:2},R.createElement(I,{color:"#E4CCFF"},"SHARED: ",g.url," (copied to clipboard)")),y&&R.createElement($,{paddingLeft:2},R.createElement(I,{color:y.includes("NOT SHARED")?"red":"#E4CCFF"},y)),w&&R.createElement($,{paddingLeft:2},R.createElement(I,{color:"#E4CCFF"},w)))},"InputBox"),xn=R.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,tasteLearning:h,tasteUsage:g,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C})=>{const[x,v]=U(0);return O(()=>{if(!t)return void v(0);const e=setInterval(()=>{v(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),R.createElement($,{flexDirection:"column"},R.createElement(un,{messages:e}),(t||n.isExecuting)&&R.createElement(pn,{tokens:m,timeElapsed:x,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),R.createElement(Cn,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:p,tasteLearning:h,tasteUsage:g,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C}))}),vn=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:r}=j(),[o,s]=U([]),[i,a]=U(0),[c,l]=U(!0),[u,d]=U(0),m=30;O(()=>{p()},[]);const p=__name(async()=>{l(!0);const e=await tn.listSessions();s(e),l(!1)},"loadSessions");if(D((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 R.createElement($,{flexDirection:"column",paddingLeft:2,paddingTop:1},R.createElement(I,{color:"gray"},"Loading sessions..."));const h=__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 R.createElement($,{flexDirection:"column"},R.createElement(I,{color:"gray"},"No sessions available"));const f=o.slice(u,u+m),y=u;return R.createElement($,{flexDirection:"column",paddingLeft:1},o.length>m&&R.createElement($,{marginBottom:1},R.createElement(I,{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)")),R.createElement($,{columnGap:2,marginBottom:1},R.createElement($,{width:7},R.createElement(I,{color:"gray"}," ")),R.createElement($,{width:13},R.createElement(I,{color:"gray"},"Modified")),R.createElement($,{width:11},R.createElement(I,{color:"gray"},"# Messages")),R.createElement($,{width:20},R.createElement(I,{color:"gray"},"Git Branch")),R.createElement($,null,R.createElement(I,{color:"gray"},"Summary"))),R.createElement($,{columnGap:2},R.createElement($,{flexDirection:"column",width:7},f.map((e,t)=>{const r=y+t;return R.createElement(I,{key:`sel-${r}`,color:i===r?"cyan":"gray"},i===r?`${n.pointer} ${r+1}.`:` ${r+1}.`)})),R.createElement($,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return R.createElement(I,{key:`mod-${e.id}`,color:i===n?"white":"gray"},h(e.lastModified))})),R.createElement($,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return R.createElement(I,{key:`msg-${e.id}`,color:i===n?"white":"gray"},e.messageCount)})),R.createElement($,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return R.createElement(I,{key:`branch-${e.id}`,color:i===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),R.createElement($,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return R.createElement(I,{key:`summary-${e.id}`,color:i===n?"white":"gray"},g(e.firstMessage))}))))},"SessionTable"),Sn=__name(({onTrust:e,onExit:t})=>{const{exit:r}=j(),[o,s]=U(1),i=process.cwd().replace(process.env.HOME||"","~");return D((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())}),R.createElement($,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1},R.createElement(I,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),R.createElement($,{marginTop:1},R.createElement(I,{color:"gray"},i)),R.createElement($,{marginTop:1,flexDirection:"column"},R.createElement(I,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),R.createElement($,{marginTop:1},R.createElement(I,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),R.createElement($,{marginTop:1,flexDirection:"column"},R.createElement($,null,R.createElement(I,{color:1===o?"cyan":"gray"},1===o?n.pointer:" "," 1. Yes, proceed")),R.createElement($,null,R.createElement(I,{color:2===o?"cyan":"gray"},2===o?n.pointer:" "," 2. No, exit"))))},"TrustPrompt"),kn=class extends le{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)}}},Tn=__name((e={})=>{const[t,n]=U(null),[r,o]=U(null),[s,i]=U(!1);return O(()=>{const t=e.projectRoot||process.cwd(),r=new kn(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:L(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:L(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:L(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:L(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:L(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:L((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:L(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions"),Pn=__name(({request:e,onResponse:t})=>{const[r]=U(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 R.createElement($,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},R.createElement($,{marginBottom:1},R.createElement(I,{bold:!0,color:"yellow"},l())),R.createElement($,{marginBottom:1},R.createElement(I,{bold:!0},"Do you want to ",i()," ",R.createElement(I,{color:"cyan"},a()),"?")),R.createElement(ue,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>R.createElement(I,{color:"cyan"},e?n.pointer:" "),itemComponent:({label:e,isSelected:t})=>R.createElement(I,{color:t?"cyan":"white"},e.includes("(")?R.createElement(R.Fragment,null,e.split("(")[0],R.createElement(I,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),An=__name(({request:e,onResponse:t})=>{const[r]=U(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 R.createElement($,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},R.createElement($,{marginBottom:1},R.createElement(I,{bold:!0,color:"yellow"},"Execute Shell Command")),R.createElement($,{marginBottom:1},R.createElement(I,{bold:!0},"Command Code needs to execute ",R.createElement(I,{color:"cyan"},c()),".")),e.workingDirectory&&R.createElement($,{marginBottom:1},R.createElement(I,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&R.createElement($,{marginBottom:1},R.createElement(I,{color:"gray",italic:!0},e.description)),R.createElement(ue,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:r,indicatorComponent:({isSelected:e})=>R.createElement(I,{color:"cyan"},e?n.pointer:" "),itemComponent:({label:e,isSelected:t})=>R.createElement(I,{color:t?"cyan":"white"},e)}))},"ShellPermissionPrompt"),$n=__name(()=>process.stdout.write("win32"===process.platform?"[2J[0f":"[2J[3J[H"),"clearConsole"),In=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const{exit:r}=j(),[o,s]=U(0),[i,a]=U(!1),[c,l]=U(!1),[u,d]=U(!0),[m,p]=U(""),[h,g]=U(!1);O(()=>{__name(async()=>{try{const[e,t]=await Promise.all([isTasteLearningEnabled(),isTasteUsageEnabled()]);a(e),l(t)}catch(e){}finally{d(!1)}},"loadSettings")()},[]),D((t,n)=>{if(n.upArrow&&o>0)s(o-1);else if(n.downArrow&&o<3)s(o+1);else{if(!n.return&&" "!==t)return n.escape?h?(p(""),void g(!1)):($n(),void e()):void 0;0===o?f():1===o?y():2===o?w():3===o&&b()}});const f=__name(async()=>{const e=!i;a(e);try{await setTasteConfig(e,c),t?.()}catch(t){a(!e)}},"toggleTasteLearning"),y=__name(async()=>{const e=!c;l(e);try{await setTasteConfig(i,e),t?.()}catch(t){l(!e)}},"toggleTasteUsage"),w=__name(async()=>{try{p("Fetching taste learnings...");const e=new $t({baseUrl:getApiBaseUrl()}),t=tn.getCurrentProjectDirName(),n=await e.get({endpoint:`/alpha/taste/${t}/rules`});if(0===n.total)p("No taste learnings yet. Chat more to help agent learn!"),g(!1);else{const e=n.rules.map((e,t)=>`${t+1}. ${e.instruction} (${e.scope})`).join("\n");p(`Found ${n.total} taste learning${1===n.total?"":"s"}:\n${e}`),g(!0)}}catch(e){p("Failed to get taste learnings")}setTimeout(()=>p(""),8e3)},"handleListLearnings"),b=__name(async()=>{try{p("Clearing all taste learnings...");const e=new $t({baseUrl:getApiBaseUrl()}),t=tn.getCurrentProjectDirName();await e.delete({endpoint:`/alpha/taste/${t}`}),p("All taste learnings cleared successfully")}catch(e){p("Failed to clear taste learnings")}setTimeout(()=>p(""),3e3)},"handleClearLearnings");return u?R.createElement($,{key:n,borderStyle:"round",borderColor:"blue",padding:1,flexDirection:"column"},R.createElement(I,{color:"blue",bold:!0},"Taste Settings"),R.createElement(I,{dimColor:!0},"Loading configuration...")):R.createElement($,{key:n,borderStyle:"round",borderColor:"gray",padding:1,flexDirection:"column"},R.createElement(I,{bold:!0},"Taste Management"),R.createElement(I,{dimColor:!0},"Configure learning preferences and manage data"),R.createElement($,{marginTop:1}),R.createElement($,{justifyContent:"space-between"},R.createElement(I,{color:0===o?"white":"gray"},0===o?"▶ ":" ","Taste learning",R.createElement(I,{dimColor:!0}," - Learn taste from your interactions")),R.createElement(I,{color:i?"white":"gray"},i?"true":"false")),R.createElement($,{justifyContent:"space-between"},R.createElement(I,{color:1===o?"white":"gray"},1===o?"▶ ":" ","Taste usage",R.createElement(I,{dimColor:!0}," ","- Use learned taste to improve responses")),R.createElement(I,{color:c?"white":"gray"},c?"true":"false")),R.createElement($,{marginTop:1}),R.createElement($,null,R.createElement(I,{color:2===o?"white":"gray"},2===o?"▶ ":" ","List learnings",R.createElement(I,{dimColor:!0}," - View all learned taste preferences"))),R.createElement($,null,R.createElement(I,{color:3===o?"white":"gray"},3===o?"▶ ":" ","Clear all learnings",R.createElement(I,{dimColor:!0}," - Delete learned taste preferences"))),m&&R.createElement($,{marginTop:1},R.createElement(I,{dimColor:!0},m)),R.createElement($,{marginTop:1}),R.createElement(I,{dimColor:!0},"↑/↓ to select • Enter/Space to toggle/action •"," ",h?"Esc to clear list":"Esc to close"))},"TasteConfig"),Dn=__name(({staticKey:e})=>R.createElement(A,{items:[{staticKey:e}],key:e},()=>R.createElement(I,{key:e},"\0")),"Responsive"),{setText:Fn}=te,jn=__name(({resume:e=!1,continue:t=!1,updateStatus:n,updateFailedInfo:r})=>{const{exit:o}=j(),[s,i]=U(""),[a,c]=U("Ready..."),[l,u]=U(n),{stdout:d}=M(),[m,p]=U(!1),[h,g]=U(!1),[f,y]=U(0),{executeBash:w,executionState:b}=wt(),[E,C]=U(""),[x,v]=U([]),[S,k]=U(!1),[T,P]=U([]),[A,F]=U(crypto.randomUUID()),[L,N]=U(!1),[B,z]=U(!1),[W,q]=U(!1),[G,J]=U(!1),[V,H]=U(!0),[K,Q]=U(!1),[Y,Z]=U(0),[X,ee]=U(null),[te,ne]=U(null),re=_(te);O(()=>{re.current=te},[te]);const[oe,se]=U(!1),[ie,ae]=U(""),[ce,le]=U(!1),[ue,de]=U(!1),me=__name(async()=>{try{const[e,t]=await Promise.all([isTasteLearningEnabled(),isTasteUsageEnabled()]);le(e),de(t)}catch(e){}},"loadTasteStatus"),pe=_([]),he=_(null),[ge,fe]=U(null),{requestShellPermission:ye,service:we,respondToPrompt:be,clearSessionPermissions:Ce,setEnabled:xe}=Tn({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{fe({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),he.current&&c("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{fe({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),he.current&&c("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?c("Permission granted"):c("Permission denied")},"onPermissionResponse")});O(()=>{(async()=>{if(await tn.isProjectInitialized())if(J(!0),H(!1),me(),t){const e=await tn.listSessions();if(e.length>0){const t=e[0];De(t.id)}}else e&&N(!0);else q(!0),H(!1)})()},[e,t,o]),O(()=>{pe.current=T},[T]),O(()=>{if(!S)return;const e=setInterval(()=>{c(ht())},7e3);return()=>clearInterval(e)},[S]),D((e,t)=>{if(!h){if(t.ctrl&&"c"===e&&o(),t.escape)if(ge)be({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),ge.resolve(!1),fe(null),c("Permission denied");else if(S&&he.current){he.current.interrupt(!0),k(!1),c("Interrupted by user");const e=ot("Interrupted by user");v(t=>[...t,e])}t.meta||t.ctrl}}),O(()=>{const e=__name(()=>{$n(),y(e=>e+1)},"handleResize");if(d)return d.on("resize",e),()=>{d.off("resize",e)}},[d]),O(()=>{he.current||!G||L||B||(he.current=new on({onFeedUpdate:__name(e=>{v(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...pe.current];return pe.current=[],P([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Z(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{ee(e)},"onContextUsageUpdate"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&we){const e={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${t.args?.join(" ")||""}`};return we.requestShellPermission(e).then(e=>e.allowed)}if(we){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 we.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=re.current;return e?{sessionId:A,secret:e.secret}:null},"getShareInfo")},A),(async()=>{await Ae()})())},[A,L,B,G]);const ve=_(!1),Se=__name(async({role:e,input:t,images:n})=>{if(t.length)if(l&&u(null),Z(0),"bash"===e){if(ve.current)return;ve.current=!0;const e=at(t);v([...x,e]),i(""),await w(t,e=>{v(e)},()=>{$n(),y(e=>e+1)}),ve.current=!1}else{if(S)return P(e=>[...e,t]),void i("");if(ve.current)return;ve.current=!0,k(!0),c(ht()),i("");try{he.current&&await he.current.sendMessage(t,n)}catch(e){if("Interrupted by user"===e.message||"InterruptedError"===e.name||"AbortError"===e.name);else if("Insufficient credits"===e.message){c("Insufficient credits");const e=ot("Insufficient credits");v(t=>[...t,e])}else console.error("Chat error:",e),c("Error occurred")}finally{k(!1),"Interrupted by user"!==a&&"Permission denied"!==a&&"Insufficient credits"!==a&&c("Ready..."),ve.current=!1}}},"handleSubmit"),ke=__name(()=>{const e=`**Command Code v0.0.4-alpha.5**\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${gn.filter(e=>"/help"!==e.command).map(e=>`**${e.command}** - ${e.description}`).join("\n")}`;v(t=>[...t,ct(e)])},"handleHelpCommand"),Te=__name(()=>{if(v([]),$n(),he.current){he.current=null;const e=crypto.randomUUID();F(e),he.current=new on({onFeedUpdate:__name(e=>{v(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...pe.current];return pe.current=[],P([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Z(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{ee(e)},"onContextUsageUpdate"),getShareInfo:__name(()=>{const t=re.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e),Ae().catch(console.error)}y(e=>e+1),ee(null),Z(0)},"handleClearCommand"),Pe=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await De(t)}switch(e){case"/exit":o();break;case"/clear":Te();break;case"/help":ke();break;case"/permissions":c("Permissions are enabled");break;case"/permissions:enable":xe(!0),c("File edit permissions enabled");break;case"/permissions:disable":xe(!1),c("File edit permissions disabled");break;case"/permissions:clear":Ce(),c("Session permissions cleared");break;case"/share":$e();break;case"/unshare":Ie();break;case"/taste":g(!0)}},"handleCommand"),Ae=__name(async()=>{const e=he.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&ne({url:t.url,secret:t.secret})}},"loadShareInfo"),$e=__name(async()=>{if(A){if(te)return await Fn(te.url),c(""),se(!0),void setTimeout(()=>{se(!1)},3e3);try{c("Creating share link...");const e=he.current?.getMessages()||[],t=nn.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new $t({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:Ee.CREATE,body:{sessionId:A,messages:t}}),o={url:r.url,secret:r.secret};ne(o);const s=he.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await Fn(r.url),c(""),se(!0),setTimeout(()=>{se(!1)},5e3)}catch(e){c(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else c("No active session to share")},"handleShareCommand"),Ie=__name(async()=>{if(A){if(!te)return ae("NOT SHARED: Session is not currently shared"),void setTimeout(()=>ae(""),5e3);try{c("Removing share link...");const e=new $t({baseUrl:getApiBaseUrl()});await e.delete({endpoint:Ee.DELETE,body:{sessionId:A,secret:te.secret}});const t=he.current?.getSessionManager();t&&await t.deleteShareInfo(),ae("UNSHARED: Sharing has stopped"),c(""),ne(null),setTimeout(()=>{ae("")},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"),De=__name(async e=>{try{v([]),he.current=null,F(e),N(!1),z(!0),await new Promise(e=>setTimeout(e,100)),he.current=new on({onFeedUpdate:__name(e=>{v(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...pe.current];return pe.current=[],P([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Z(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{ee(e)},"onContextUsageUpdate"),getShareInfo:__name(()=>{const t=re.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const t=await he.current.loadSession(e);await Ae(),v(t),$n(),y(e=>e+1)}catch(e){console.error("Failed to load session:",e),N(!0),F(crypto.randomUUID())}},"handleSelectSession"),Fe=__name(async()=>{v([]),he.current=null,F(crypto.randomUUID()),N(!1),z(!1)},"handleNewSession"),je=__name(async()=>{try{await tn.initializeProject(),q(!1),e?(console.log("No conversations found to resume."),Q(!0),o()):(J(!0),me())}catch(e){console.error("Failed to initialize project:",e),q(!1),Q(!0),o()}},"handleTrust"),Me=__name(()=>{o()},"handleNoTrust");if(K)return null;if(W)return R.createElement(R.Fragment,null,R.createElement(Dn,{staticKey:f}),R.createElement(Sn,{onTrust:je,onExit:Me}));if(V)return null;if(L)return R.createElement(vn,{onSelectSession:De,onNewSession:Fe});if(!G)return null;if(ge){if("shell_command"===ge.toolName){const e=ge.params;return R.createElement($,{flexDirection:"column",width:"100%"},R.createElement(ln,{staticKey:f,feed:x,showHeader:!0}),R.createElement($,{marginY:1},R.createElement(An,{request:e,onResponse:e=>{be(e);const t="no"!==e.value;ge.resolve(t),fe(null),c(t?"Shell command allowed":"Shell command denied")}})))}{const e={action:ge.toolName.includes("edit")?"edit":ge.toolName.includes("write")?"create":ge.toolName.includes("delete")?"delete":"edit",filePath:ge.params.filePath||ge.params.file_path||ge.params.path||ge.params.absolutePath||ge.params.notebook_path||"unknown",description:`Allow ${ge.toolName} operation`,newContent:ge.params.new_content||ge.params.content};return R.createElement($,{flexDirection:"column",width:"100%"},R.createElement(ln,{staticKey:f,feed:x,showHeader:!0}),R.createElement($,{marginY:1},R.createElement(Pn,{request:e,onResponse:e=>{be(e);const t="no"!==e.value;ge.resolve(t),fe(null),c(t?"File operation allowed":"File operation denied")}})))}}return h?R.createElement(R.Fragment,null,R.createElement(Dn,{staticKey:f}),R.createElement($,{flexDirection:"column",width:"100%"},R.createElement($,{marginBottom:1},R.createElement(I,{dimColor:!0},"Press Esc to return to conversation")),R.createElement(In,{onClose:()=>g(!1),onSettingsChange:me,staticKey:f}))):R.createElement($,{flexDirection:"column",width:"100%"},R.createElement(ln,{staticKey:f,feed:x,showHeader:!0}),R.createElement(xn,{queuedMessages:T,isProcessing:S,executionState:b,status:a,input:s,setInput:i,onSubmit:Se,showFileList:m,setShowFileList:p,fileSearchQuery:E,setFileSearchQuery:C,onCommand:Pe,outputTokens:Y,contextUsage:X,tasteLearning:ce,tasteUsage:ue,shareInfo:te,showShareNotification:oe,unshareNotificationMessage:ie,updateStatus:l,updateFailedInfo:r}))},"InteractiveCLI");function getPackageJson(){const e=import.meta.url,t=me(e),n=u(t);return JSON.parse(G(d(n,"./../package.json"),"utf8"))}__name(getPackageJson,"getPackageJson");var Mn=getPackageJson(),Rn=c.join(g.homedir(),".command-code"),Un=c.join(Rn,"update-status.json"),On=c.join(Rn,"update-failed.json");function ensureCommandCodeDir(){q.existsSync(Rn)||q.mkdirSync(Rn,{recursive:!0})}async function checkForUpdateAvailable(){try{const e=B("npm view command-code versions --json",{encoding:"utf-8"}),t=JSON.parse(e),n=Mn.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(de.rcompare)[0];de.gt(e,n)&&(i=e,a=!0)}if(!a&&r&&s.length>0){const e=s.sort(de.rcompare)[0];de.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{B(`npm update -g command-code@${e.latestVersion}`,{stdio:"inherit"}),ensureCommandCodeDir();const t={updatedFrom:e.currentVersion,updatedTo:e.latestVersion,updatedAt:Date.now()};return q.writeFileSync(Un,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 q.writeFileSync(On,JSON.stringify(n,null,2)),{success:!1,updateInfo:e}}}function getUpdateStatus(){try{if(ensureCommandCodeDir(),q.existsSync(Un)){const e=JSON.parse(q.readFileSync(Un,"utf-8"));return q.unlinkSync(Un),e}}catch(e){}return null}function getFailedUpdateInfo(){try{if(ensureCommandCodeDir(),q.existsSync(On)){const e=JSON.parse(q.readFileSync(On,"utf-8"));return q.unlinkSync(On),{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 _n=__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 tn.isProjectInitialized()&&0===(await tn.listSessions()).length&&(console.log("No conversations found to resume."),process.exit(0)),F(R.createElement(jn,{resume:e.resume,continue:e.continue,updateStatus:t,updateFailedInfo:n}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})},"interactive"),{red:Ln,yellow:Nn}=he,Bn=__name((e="ERROR: ",t,n=!0,r=!0)=>{if(t){if(console.log(),n?(console.log(`${ge.error} ${Ln(e)}`),console.log(`${ge.error} ${Ln("ERROR →")} ${t.name}`),console.log(`${ge.info} ${Ln("REASON →")} ${t.message}`),console.log(`${ge.info} ${Ln("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${ge.warning} ${Nn(e)}\n`),!r)return!1;process.exit(0)}},"handleError"),zn=__name(()=>{process.on("unhandledRejection",e=>{Bn(pe`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{
|
|
2
|
+
import"dotenv/config";import{Command as e}from"commander";import t,{mainSymbols as n}from"figures";import*as r from"@clack/prompts";import{confirm as o,isCancel as s,cancel as i,note as a,password as c,select as l,outro as d}from"@clack/prompts";import u from"picocolors";import m from"open";import*as p from"path";import h,{relative as g,dirname as f,join as y,isAbsolute as w,resolve as b}from"path";import*as E from"os";import C from"os";import*as x from"fs/promises";import v,{mkdir as S,writeFile as k}from"fs/promises";import T from"crypto";import{z as P}from"zod";import{Static as A,Box as $,Text as I,useInput as D,render as F,useApp as j,useStdout as M}from"ink";import R,{useState as U,useEffect as O,useRef as _,useCallback as L,useMemo as N}from"react";import{execSync as B,spawn as z}from"child_process";import*as W from"fs";import q,{readFileSync as G,promises as J,constants as V,existsSync as H,readdirSync as K,statSync as Q}from"fs";import{minimatch as Y}from"minimatch";import{glob as Z}from"glob";import X from"@sindresorhus/slugify";import{MessageStream as ee}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import te from"@crosscopy/clipboard";import ne from"ink-gradient";import{setOptions as re,parse as oe}from"marked";import se from"marked-terminal";import*as ie from"diff";import ae from"ink-text-input";import ce from"sharp";import{EventEmitter as le}from"events";import de from"ink-select-input";import ue from"semver";import{fileURLToPath as me}from"url";import pe from"dedent";import he from"chalk";import ge from"log-symbols";import fe from"readline/promises";var ye=Object.defineProperty,__name=(e,t)=>ye(e,"name",{value:t,configurable:!0}),we=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 heading({text:e,sub:t,dim:n,green:r}){return r?`${u.bgGreen(u.black(` ${e} `))} ${t&&t}`:n?`${u.bgBlack(u.white(` ${e} `))} ${t&&t}`:`${u.bold(u.bgCyan(u.black(` ${e} `)))} ${t&&t}`}__name(heading,"heading");var be="/alpha/generate",Ee={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",DATA:"/alpha/share/data",APPEND:"/alpha/share/append",CONNECT:"/alpha/share/connect"},Ce={GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug/rules/:ruleId",LIST:"/alpha/taste/:projectSlug/rules"},xe={ALPHA:{TASTE:{GET:new RegExp("/alpha/taste/[a-z0-9-]+"),UPDATE:new RegExp("/alpha/taste/[a-z0-9-]+/update"),DELETE:new RegExp("/alpha/taste/[a-z0-9-]+/rules/[a-z0-9-]+"),LIST:new RegExp("/alpha/taste/[a-z0-9-]+/rules")}}};function getStudioAuthUrl(e){return"dev"===e?"http://localhost:3000/settings/keys":"staging"===e?"https://staging.commandcode.ai/settings/keys":"https://commandcode.ai/settings/keys"}Object.values(xe.ALPHA.TASTE),Ee.CREATE,Ee.DELETE,Ee.APPEND,Object.values(Ce),__name(getStudioAuthUrl,"getStudioAuthUrl");var ve,Se;(e=>{e.OAuth=P.object({type:P.literal("oauth"),refresh:P.string(),access:P.string(),expires:P.number()}),e.ApiKey=P.object({type:P.literal("api"),key:P.string()}),e.Info=P.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const t=__name(()=>{const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"dev":t?"staging":"prod"},"getEnv"),n=__name(()=>h.join(C.homedir(),".command-code"),"getAuthDir"),r=__name(()=>{const e=t(),r="dev"===e?"models.dev.json":"staging"===e?"models.staging.json":"models.json";return h.join(n(),r)},"getAuthFile");async function get(e){try{const t=await v.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await v.mkdir(o,{recursive:!0});let i={};try{const e=await v.readFile(s,"utf-8");i=JSON.parse(e)}catch{}i[e]=t,await v.writeFile(s,JSON.stringify(i,null,2)),await v.chmod(s,384)}async function remove(e){const t=r();try{const n=await v.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await v.unlink(t):(await v.writeFile(t,JSON.stringify(r,null,2)),await v.chmod(t,384))}catch{}}async function list(){try{const e=await v.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")})(ve||(ve={})),(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 T.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return T.createHash("sha256").update(e).digest("base64url")}function generateState(){return T.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 ve.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 ve.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 ve.remove("anthropic");const o=await r.json();return await ve.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 ve.remove("anthropic")}}}async function getValidAccessToken(){const e=await ve.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")})(Se||(Se={}));var ke=__name(()=>h.join(C.homedir(),".command-code"),"getAuthDir"),Te=__name(()=>{const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"dev":t?"staging":"prod"},"getEnv"),Pe=__name(()=>{const e=Te();return"dev"===e?"--dev":"staging"===e?"--staging":""},"getEnvFlag"),Ae=__name(e=>{const t=e??Te(),n="dev"===t?"auth.dev.json":"staging"===t?"auth.staging.json":"auth.json";return h.join(ke(),n)},"getAuthFile"),$e=__name(()=>h.join(C.homedir(),".command-code"),"getConfigDir"),Ie=__name(e=>{const t=e??Te(),n="dev"===t?"config.dev.json":"staging"===t?"config.staging.json":"config.json";return h.join($e(),n)},"getConfigFile"),De=__name(e=>{const t=e??Te(),n="dev"===t?"models.dev.json":"staging"===t?"models.staging.json":"models.json";return h.join($e(),n)},"getModelsFile");async function loginAction(){try{const e=Te(),n=getStudioAuthUrl(e);console.log("\n"),r.intro(heading({text:"Command Code Authentication",sub:""}));const p=await o({message:`Open the authentication page? ${u.dim("— copy your API key from there and paste it here.")}`});s(p)&&(i(`${t.cross} Login cancelled.`),process.exit(0)),p&&(await m(n),a(u.yellow("Please copy your API key from the opened page and paste it here.")));const h=await c({message:"Paste your API key string:",mask:"*"});s(h)&&(i(`${t.cross} No API key provided.`),process.exit(0)),h.trim()||(console.log(`${t.cross} No API key provided.`),process.exit(1));const g=ke(),f=Ae(e),y=Ie(e);await v.mkdir(g,{recursive:!0}),await v.writeFile(f,JSON.stringify({apiKey:h},null,2)),await v.chmod(f,384);const w=await l({message:"Select provider",options:[{value:"anthropic",label:"Anthropic (Claude Pro/Max)"},{value:"command-code",label:"Command Code (recommended)"}]});if(s(w))i(`${t.cross} No provider selected.`);else if("anthropic"===w){const e=await l({message:"Login method",options:[{value:"anthropic-oauth",label:"Claude Pro/Max"}]});s(e)?i(`${t.cross} No login method selected.`):"anthropic-oauth"===e&&await anthropicAuth()}const b={provider:w};await v.writeFile(y,JSON.stringify(b,null,2)),await v.chmod(y,384);let E=`You are logged in. API key is stored in ~/.command-code/${"dev"===e?"auth.dev.json":"staging"===e?"auth.staging.json":"auth.json"}. Run \`cmd\` to get started.`;d(u.green(E)),process.exit(0)}catch(e){console.error(`${t.cross} Login failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function anthropicAuth(){try{const{url:e,verifier:n,state:r}=Se.createAuthorizationUrl();await o({message:"Open the Anthropic auth page?"})&&(await m(e),a(u.yellow("Please copy your authorization code from the opened page and paste it here.")));const l=await c({message:"Paste your authorization code:",mask:"*"});s(l)&&(i(`${t.cross} No API key provided.`),process.exit(1)),l.trim()||(console.log(`${t.cross} No authorization code provided`),process.exit(1));const d=l.split("#")[0].trim();return await Se.exchangeCodeForTokens(d,n,r),!0}catch(e){i(`${t.cross} Anthropic OAuth failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function logoutAction(){try{const e=Te(),t=Ae(e),n=Ie(e),r=De(e);try{await v.unlink(t)}catch(e){}try{await v.unlink(n)}catch(e){}try{await v.unlink(r)}catch(e){}d(u.green("Successfully logged out from Command Code")),process.exit(0)}catch(e){i(`${t.cross} Logout failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function getAuthKey(e){try{const t=Ae(e),n=await v.readFile(t,"utf-8");return JSON.parse(n).apiKey||null}catch{return null}}async function statusAction(){try{const e=Te();await getAuthKey(e)||(i(`${t.cross} Not authenticated. Please login using "cmd auth login".`),process.exit(1)),d(u.green(`${t.tick} Authenticated with Command Code`)),process.exit(0)}catch(e){i(`${t.cross} Status check failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}__name(loginAction,"loginAction"),__name(anthropicAuth,"anthropicAuth"),__name(logoutAction,"logoutAction"),__name(getAuthKey,"getAuthKey"),__name(statusAction,"statusAction");var Fe=new e("auth").description("Manage authentication with Command Code");Fe.command("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),Fe.command("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Fe.command("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);var je=new e("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),Me=new e("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Re=new e("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);function formatDate(e=new Date){return e.toISOString().split("T")[0]}function parseJSON(e){try{return JSON.parse(e)}catch{return null}}async function getConfiguredProvider(){try{const e=Ie(),t=await v.readFile(e,"utf-8");return JSON.parse(t).provider||null}catch{return null}}__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider");var Ue=new we("Config"),Oe=p.join(E.homedir(),".command-code-config.json");async function loadConfig(){try{return parseJSON(await x.readFile(Oe,"utf-8"))||{}}catch{return{}}}async function saveConfig(e){await x.writeFile(Oe,JSON.stringify(e,null,2))}__name(loadConfig,"loadConfig"),__name(saveConfig,"saveConfig");var _e=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?Ue.info(`${e}: ${JSON.stringify(t)}`):Ue.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),Ue.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?Ue.info("No configuration values set"):(Ue.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({}),Ue.success("Configuration reset successfully")})),Le=new we("Info"),Ne=new e("info").description("Display system information").option("-v, --verbose","Show verbose output").action(e=>{if(Le.info("System Information:"),console.log("-------------------"),console.log(`${t.info} Date: ${formatDate()}`),console.log(`${t.info} Platform: ${E.platform()}`),console.log(`${t.info} Architecture: ${E.arch()}`),console.log(`${t.info} CPUs: ${E.cpus().length}`),console.log(`${t.info} Memory: ${Math.round(E.totalmem()/1024/1024/1024)} GB`),console.log(`${t.info} Home Directory: ${E.homedir()}`),e.verbose){console.log("\nDetailed CPU Information:"),E.cpus().forEach((e,t)=>{console.log(` CPU ${t}: ${e.model} @ ${e.speed} MHz`)}),console.log("\nNetwork Interfaces:");const e=E.networkInterfaces();Object.keys(e).forEach(t=>{const n=e[t];n&&n.forEach(e=>{"IPv4"!==e.family||e.internal||console.log(` ${t}: ${e.address}`)})})}Le.success("Information displayed successfully!")}),Be=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{const s=z("/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"),ze=__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"),We="read_file",qe="edit_file",Ge="write_file",Je="read_directory",Ve="read_multiple_files",He="grep",Ke="shell_command",Qe="think",Ye="todo_write",Ze="web_search",Xe="web_fetch",et=__name(e=>e===Ze,"isWebSearchTool"),tt=P.object({id:P.string(),timestamp:P.number(),type:P.literal("image"),source:P.object({type:P.enum(["base64","url"]),media_type:P.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:P.string()})}),nt=P.object({id:P.string(),timestamp:P.number(),input:P.string(),output:P.string().optional(),metadata:P.record(P.string(),P.any()).optional(),images:P.array(tt).optional().default([])}),rt=nt.extend({role:P.literal("user")}),ot=nt.extend({role:P.literal("assistant")}),st=nt.extend({role:P.literal("tool"),name:P.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),it=nt.extend({role:P.literal("bash"),command:P.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),at=nt.extend({role:P.literal("system")}),ct=P.discriminatedUnion("role",[rt,ot,st,it,at]),lt=__name((e,t)=>ct.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),dt=__name(e=>ct.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),ut=__name((e,t,n)=>ct.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),mt=__name(e=>ct.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),pt=__name(e=>ct.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),ht=__name((e,t)=>{const n={...e,output:t};return ct.parse(n)},"updateEntryWithOutput"),gt=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),ft=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),yt=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),wt=["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…"],bt=__name(()=>wt[Math.floor(Math.random()*wt.length)],"getRandomLLMStatus"),Et=__name(e=>{switch(e){case We:return"Read";case qe:return"Edit";case Ge:return"Write";case Je:return"List";case Ve:return"Read Multiple";case He:return"Search";case Ke:return"Shell";case Ye:return"Todos";case Qe:return"Thinking…";case Ze:return"Web Search";case Xe:return"Web Fetch";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),Ct=__name((e,t)=>{try{switch(e){case We:case Ge:case qe:return t.absolutePath||t.file_path||t.filePath||t.path||"file";case Je:return t.path||"directory";case He:return`"${t.pattern}" in ${t.path||"files"}`;case Ke:return t.command&&t.args&&t.args.length>0?`${t.command} ${t.args.join(" ")}`:t.command||"";case Ye:return`${t.todos?t.todos.length:0} items`;case Qe:return t.content||"planning";case Ve:const e=t.include||[];return Array.isArray(e)?e.join(", "):"multiple files";case Ze:return t.query||"search";case Xe:return t.url||"fetch";default:return JSON.stringify(t||{})}}catch{return"parameters"}},"getToolInputContent"),xt=__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"),vt=__name(()=>{const[e,t]=U({isExecuting:!1,currentCommand:null});return{executeBash:L(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Be(e,{timeout:3e4,cwd:process.cwd()}),o=ze(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]=ht(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]=ht(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution"),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 $t(e,o,n,r);case 409:return new It(e,o,n,r);case 422:return new Dt(e,o,n,r);case 429:return new Ft(e,o,n,r);default:return e>=500?new jt(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},$t=class extends St{static{__name(this,"NotFoundError")}status=404},It=class extends St{static{__name(this,"ConflictError")}status=409},Dt=class extends St{static{__name(this,"UnprocessableEntityError")}status=422},Ft=class extends St{static{__name(this,"RateLimitError")}status=429},jt=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=await 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}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...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,{headers:n,method:t.method,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"})}};function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var Rt=P.object({absolutePath:P.string().describe("The absolute path to the file to read"),offset:P.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:P.number().optional().describe("Optional number of lines to read")});P.object({content:P.union([P.string(),P.instanceof(Buffer)]),contentType:P.enum(["text","binary"]),fileType:P.string(),size:P.number(),linesRead:P.number().optional()});var Ut=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:r}=e;if(!p.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw new Ut("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=p.normalize(t);try{await x.access(o,W.constants.F_OK|W.constants.R_OK)}catch{throw new Ut(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await x.stat(o)).isFile())throw new Ut("Path does not point to a file","NOT_A_FILE");const s=getFileType(o),i=isBinaryFile(s);if(void 0!==n&&void 0===r||void 0===n&&void 0!==r)throw new Ut("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new Ut("Offset must be >= 0","INVALID_OFFSET");if(void 0!==r&&r<=0)throw new Ut("Limit must be > 0","INVALID_LIMIT");try{if(i){const e=await x.readFile(o);return{fileType:s,content:e,size:e.length,contentType:"binary"}}if(void 0!==n&&void 0!==r){const e=await readTextFileLines(o,n,r);return{fileType:s,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await x.readFile(o,"utf8");return{content:e,fileType:s,contentType:"text",size:e.length}}}catch(e){if(e instanceof Ut)throw e;throw new Ut(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var Ot={".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=p.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",...Ot}[t]||"unknown"}function isBinaryFile(e){return Object.values(Ot).includes(e)}async function readTextFileLines(e,t,n){const r=(await x.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),i=r.slice(o,s);return{content:i.join("\n"),linesRead:i.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=p.isAbsolute(o)?o:p.resolve(process.cwd(),o),s=await readFileContent({absolutePath:e});if("binary"===s.contentType)continue;const i=String(s.content),a=p.relative(process.cwd(),e);t.push({token:r,resolvedPath:e,content:i});const c=`{${a}: ${i}}`;n=n.replace(r,c)}catch(e){continue}}return{displayContent:e,processedContent:n,fileReferences:t}}function reconstructContent(e,t){let n=e;for(const e of t){const t=`{${p.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 _t={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=Rt.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")},Lt=P.object({filePath:P.string().describe("The absolute path to the file to edit"),oldValue:P.string().describe("The text to replace"),newValue:P.string().describe("The new text to insert"),replacementCount:P.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:P.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(!p.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 J.access(t,V.F_OK|V.R_OK|V.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 a=(i.match(new RegExp(escapeRegExp(n),"g"))||[]).length;if(0===a)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let c,l;if(o)c=a;else if(c=s,c>a)throw createFileEditError(`Expected ${c} replacements, but only found ${a} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||c===a)l=i.split(n).join(r),d=a;else{l=i;for(let e=0;e<c;e++){const e=l.indexOf(n);-1!==e&&(l=l.substring(0,e)+r+l.substring(e+n.length),d++)}}if(0===d)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await J.writeFile(t,l,"utf-8"),console.log(`Made ${d} replacement${1!==d?"s":""} in ${p.basename(t)}\n`),{path:t,replacementsCount:d,oldContent:i,newContent:l}}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}P.object({path:P.string(),replacementsCount:P.number(),oldContent:P.string(),newContent:P.string()}),P.object({name:P.string(),message:P.string(),code:P.string().optional()}),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),__name(formatOutput2,"formatOutput");var Nt={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=Lt.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")},Bt=P.object({path:P.string().describe("The absolute path to the directory to read"),exclude:P.array(P.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:P.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});P.object({files:P.array(P.string()),directories:P.array(P.string())});var zt=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:r=!1}=e;if(!p.isAbsolute(t))throw new zt("Path must be absolute, not relative","INVALID_PATH");try{if(!(await x.stat(t)).isDirectory())throw new zt("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof zt)throw e;throw new zt(`Directory does not exist or is not accessible: ${t}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await x.readdir(t);let o=[];r&&(o=await loadGitIgnorePatterns(t));const s=[...n,...o],i=[],a=[];for(const n of e){if(shouldIgnoreEntry(n,s))continue;const e=p.join(t,n);try{const t=await x.stat(e);t.isDirectory()?a.push(n):t.isFile()&&i.push(n)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:i.sort(),directories:a.sort()}}catch(e){if(e instanceof zt)throw e;throw new zt(`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=p.resolve(e);const r=await findGitRoot(e);for(;n&&isWithinGitRoot(n,r);){const e=p.join(n,".gitignore");try{const n=(await x.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));t.push(...n)}catch(e){}const r=p.dirname(n);if(r===n)break;n=r}}catch(e){}return t}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(e){let t=p.resolve(e);for(;;){try{const e=p.join(t,".git");if((await x.stat(e)).isDirectory())return t}catch{}const e=p.dirname(t);if(e===t)throw new Error("Not in a git repository");t=e}}function isWithinGitRoot(e,t){const n=p.resolve(e),r=p.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(Y(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 Wt={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=Bt.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")},qt=P.object({filePath:P.string().describe("The absolute path where the file should be written"),content:P.string().describe("The content to write to the file")});async function writeFile2({filePath:e,content:t}){if(!w(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=f(e);return H(n)||await S(n,{recursive:!0}),await k(e,t,"utf-8"),{path:e,bytesWritten:Buffer.byteLength(t,"utf-8")}}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}`}P.object({success:P.boolean(),message:P.string(),path:P.string().optional()}),__name(writeFile2,"writeFile"),__name(formatOutput4,"formatOutput");var Gt={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=qt.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")},Jt=P.object({include:P.array(P.string()).describe("Array of glob patterns to include files"),exclude:P.array(P.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:P.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:P.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:P.string().optional().describe("Base directory for relative paths. Default: current working directory")}),Vt=P.object({filePath:P.string(),content:P.string(),fileType:P.string(),size:P.number()});P.object({content:P.string(),filesRead:P.array(P.string()),errors:P.array(P.object({file:P.string(),error:P.string()})),fileDetails:P.array(Vt)});var Ht=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},Kt=["**/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 Z(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 Ht("At least one include pattern must be provided","NO_PATTERNS");const i=h.resolve(s),a={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(...Kt);const s=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:i});for(const e of s)try{const t=h.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 Ht)throw e;throw new Ht(`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 Qt={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=Jt.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")},Yt=P.object({pattern:P.string().min(1,"Pattern is required"),include:P.array(P.string()).optional(),directory:P.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=z(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 Zt={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=Yt.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")},Xt=P.object({command:P.string().min(1,"Command cannot be empty"),args:P.array(P.string()).optional(),directory:P.string().optional(),timeout:P.number().optional()}),en=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:o=3e4}=e,s=Date.now();if(!t.trim())throw new en("Command cannot be empty","EMPTY_COMMAND");let i;if(r){if(p.isAbsolute(r))throw new en("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=p.resolve(process.cwd(),r)}else i=process.cwd();try{if(!(await v.stat(i)).isDirectory())throw new en(`Path is not a directory: ${r}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof en)throw e;throw new en(`Directory does not exist or is not accessible: ${r||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:i,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((r,i)=>{let a="",c="",l=!1;const d=setTimeout(()=>{if(!l){u.kill("SIGTERM");const e=Date.now()-s;i(new en(`Command timed out after ${o}ms`,"TIMEOUT",null,"SIGTERM",a,c,e))}},o),u=z(t,n,e);u.stdout?.on("data",e=>{a+=e.toString()}),u.stderr?.on("data",e=>{c+=e.toString()}),u.on("close",(e,t)=>{l=!0,clearTimeout(d);const n=Date.now()-s;0===e?r({stdout:a.trim(),stderr:c.trim(),exitCode:e,signal:t,duration:n}):i(new en(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,a.trim(),c.trim(),n))}),u.on("error",e=>{l=!0,clearTimeout(d);const t=Date.now()-s;i(new en(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),c.trim(),t))})})}catch(e){if(e instanceof en)throw e;throw new en(`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 tn={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=Xt.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 nn={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 rn=[_t,Nt,Wt,Gt,Qt,Zt,tn,nn,{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}],on=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],sn=new Map(rn.map(e=>[e.name,e]));async function executeTool(e,t){const n=sn.get(e);if(!n)throw new Error(`Tool "${e}" not found. Available tools: ${Array.from(sn.keys()).join(", ")}`);try{return await n.execute(t)}catch(e){return e instanceof Error?`Error: ${e.message}`:"Error: Unknown error occurred"}}function getToolSchemas(){return[...rn.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...on]}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 an=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return h.join(C.homedir(),".command-code","projects")}static getCurrentProjectDirName(){return X(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=h.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=h.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=B("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await v.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),!1}}async isProjectInitialized(){try{return(await v.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 v.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=h.join(this.projectPath,`${t}.jsonl`);try{const e=(await v.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)t.push({id:o,timestamp:r,role:"assistant",input:e.content,images:[]});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){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=Ct(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}else if("server_tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=Ct(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}n.trim()&&t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]})}}}return t}async loadSession(e){const t=e||this.sessionId,n=h.join(this.projectPath,`${t}.jsonl`);try{const e=(await v.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=h.join(e,t);try{return(await v.stat(n)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=h.join(e,t);try{return await v.mkdir(n,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=h.join(_SessionManager.getProjectsBasePath(),e);try{try{await v.access(t)}catch{return[]}const e=(await v.readdir(t)).filter(e=>e.endsWith(".jsonl")),n=[];for(const r of e){const e=r.replace(".jsonl",""),o=h.join(t,r);try{const r=await v.stat(o),s=(await v.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(s.length>0){let o="",i="";const a=JSON.parse(s[0]);a.gitBranch&&(i=a.gitBranch);for(const e of s){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:s.length,projectPath:t,gitBranch:i||"-"})}}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=h.join(this.projectPath,`${this.sessionId}.share.json`);try{await v.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=h.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await v.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=h.join(this.projectPath,`${this.sessionId}.share.json`);try{await v.unlink(e)}catch(e){}}};function getApiBaseUrl(){const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(getApiBaseUrl,"getApiBaseUrl");var cn=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(!h.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=h.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=h.basename(e);return h.dirname(e),this.isUserPath(e)?`<user-home>/${h.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`${C.platform()}-${C.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 q.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 B("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return B("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=B("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=B("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=B("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():[]}}function getProjectConfigPath(){const e=an.getProjectsBasePath(),t=an.getCurrentProjectDirName();return p.join(e,t,"config.json")}async function loadProjectConfig(){try{const e=getProjectConfigPath();return parseJSON(await x.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveProjectConfig(e){try{const t=getProjectConfigPath();await an.initializeProject(),await x.writeFile(t,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save project config: ${e}`)}}async function isTasteLearningEnabled(){return(await loadProjectConfig()).tasteLearning??!1}async function isTasteUsageEnabled(){return(await loadProjectConfig()).tasteUsage??!1}async function setTasteConfig(e,t){const n=await loadProjectConfig();n.tasteLearning=e,n.tasteUsage=t,await saveProjectConfig(n)}__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"),__name(getProjectConfigPath,"getProjectConfigPath"),__name(loadProjectConfig,"loadProjectConfig"),__name(saveProjectConfig,"saveProjectConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(isTasteUsageEnabled,"isTasteUsageEnabled"),__name(setTasteConfig,"setTasteConfig");var ln=new we("ContextEngine"),dn=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 an(t)}async interrupt(e=!1){if(this.abortController){this.abortController.abort(),this.abortController=null,ln.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(),ln.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=lt("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>ln.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=lt(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=>ln.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();let r;"anthropic"===await getConfiguredProvider()&&(r=await Se.getValidAccessToken());const o={tools:n,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:"anthropic:claude-sonnet-4-20250514"},s={config:getEnvironmentContext(),params:o};ln.debug(`🔍 API Call: ${o.model}, ${this.messages.length} messages, ${n.length} tools, streaming: true`);const i=await isTasteLearningEnabled(),a=await isTasteUsageEnabled(),c={"x-project-slug":an.getCurrentProjectDirName(),"x-taste-learning":i.toString(),"x-taste-usage":a.toString()};r&&(c["x-oauth-token"]=`Bearer ${r}`);const l=await this.request.post({body:s,stream:!0,endpoint:be,signal:this.abortController?.signal,headers:c}),d=ee.fromReadableStream(l);d.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let u,m=null;d.on("error",e=>{m="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});try{u=await d.finalMessage()}catch(e){if(m)throw m;if("AbortError"===e.name||e.message?.includes("aborted")||this.abortController?.signal.aborted)throw new Error("Interrupted by user");if(e instanceof Tt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))throw new Error("Insufficient credits");let t="API Error: ";throw e.message?t+=e.message:e.toString?t+=e.toString():t+="Unknown error occurred",new Error(t)}if(m)throw m;if("usage"in u){const e=u.usage;if(e?.input_tokens){const t=calculateUsageFromResponse(e);this.contextTokensUsed=t,this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:2e5})}}let p="";const h=u.content.filter(e=>"tool_use"===e.type),g=u.content.filter(e=>"server_tool_use"===e.type);if(g.length>0){for(const e of u.content)if("text"===e.type)p+=e.text;else if("server_tool_use"===e.type){if(p.trim()){const e=dt(p.trim());this.callbacks.onFeedUpdate(e),p=""}const t=Ct(e.name,e.input),n=ut(e.name,t),r=et(e.name)?"Found 10 results":"Content fetched",o=ht(n,r);this.callbacks.onFeedUpdate(o)}if(p.trim()){const e=dt(p.trim());this.callbacks.onFeedUpdate(e)}}if(e=u.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===h.length){const t=u.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===g.length){const t=dt(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>ln.error(`Failed to save messages: ${e}`))}if(0!==g.length&&this.sessionManager.saveMessages(this.messages).catch(e=>ln.error(`Failed to save messages: ${e}`)),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=lt(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>ln.error(`Failed to save messages: ${e}`));continue}}break}const f=u.content.filter(e=>"text"!==e.type||e.text.trim().length>0);f.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:f}));const y=[],w=new Set;let b=!1;for(const e of h){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=Ct(e.name,e.input),n="edit_file"===e.name?e.input:void 0,r=ut(e.name,t,n),o=ht(r,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o),b=!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),y.push({type:"tool_result",tool_use_id:e.id,content:n}),w.add(e.id);const o=Ct(e.name,e.input),s="edit_file"===e.name?e.input:void 0,i=ut(e.name,o,s),a=ht(i,n);this.callbacks.onFeedUpdate(a)}catch(t){const n=t instanceof Error?t.message:"Unknown error";y.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}),w.add(e.id);const r=Ct(e.name,e.input),o="edit_file"===e.name?e.input:void 0,s=ut(e.name,r,o),i=ht(s,gt(n));this.callbacks.onFeedUpdate(i)}}if(b){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?w.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const E=[...y];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){E.push({type:"text",text:t});const e=lt(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:E})),this.sessionManager.saveMessages(this.messages).catch(e=>ln.error(`Failed to save messages: ${e}`))}catch(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||this.abortController?.signal.aborted)throw ln.debug("Request interrupted by user"),new Error("Interrupted by user");if(e instanceof Tt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))throw new Error("Insufficient credits");if(e?.message?.startsWith("API Error:"))throw e;let t="API Error: ";throw e.message?t+=e.message:e.toString?t+=e.toString():t+="Unknown error occurred",new Error(t)}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 ln.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){ln.error(`Failed to sync message to share: ${e}`)}}))}async syncMessageToShare(e,t){try{const n=cn.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:Ee.APPEND})}catch(e){throw e}}};function Markdown({children:e,...t}){const n={...t};re({renderer:new se(n),breaks:!0,gfm:!0});const r=oe(e);return R.createElement(I,null,r.toString().trim())}function AssistantMessage({content:e}){return R.createElement($,null,R.createElement(I,null,n.nodejs),R.createElement($,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},R.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage");var un={"Interrupted by user":"Interrupted by user","Insufficient credits":"You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: https://commandcode.ai/settings/billing"};function UserMessage({content:e}){const t="Interrupted by user"===e,r="Insufficient credits"===e,o=e.startsWith("API Error:"),s=t||r||o;let i=s&&un[e]||e;return R.createElement($,null,R.createElement(I,{color:s?"red":"dim"},n.pointer),R.createElement($,{marginLeft:1},R.createElement(I,{color:s?"red":void 0,dimColor:!s,wrap:"wrap"},i)))}__name(UserMessage,"UserMessage");var mn="#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=ie.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)}),R.createElement($,{flexDirection:"column"},R.createElement(I,{color:"gray"},"Updated ",R.createElement(I,{color:"white",bold:!0},n)," with ",R.createElement(I,{color:"#22C55E"},o)," addition",1!==o?"s":""," and ",R.createElement(I,{color:"#EF4444"},s)," removal",1!==s?"s":""),R.createElement($,{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++,R.createElement($,{key:`${t}-${r}-removed`,width:"100%"},R.createElement(I,{color:"gray"},i.toString().padStart(3)," "),R.createElement($,{backgroundColor:"#712F37"},R.createElement(I,null,"-"),R.createElement(I,null," ",n.replace(/\s/g," "))))):e.added?(i++,R.createElement($,{key:`${t}-${r}-added`,width:"100%"},R.createElement(I,{color:"gray"},i.toString().padStart(3)," "),R.createElement($,{backgroundColor:"#325B30"},R.createElement(I,null,"+"),R.createElement(I,null," ",n.replace(/\s/g," "))))):null):(i+=n.length,null)})))}function formatTodosForDisplay(e){const t=xt(e);return t?R.createElement($,{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 R.createElement($,{key:e.id||t,flexDirection:"row"},R.createElement($,{width:2},R.createElement(I,{color:r},n)),R.createElement(I,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):R.createElement(I,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,d=!a&&t,u=!a&&!c;let m,p;if(o)m="yellow",p="→";else if(s)m="red",p=n.nodejs;else if(a)m=mn,p="✻";else if(c&&r){const e=xt(r),t=e?.every(e=>"completed"===e.status);m=t?"#22C55E":"#D4A017",p=n.nodejs}else m="#22C55E",p=n.nodejs;return R.createElement($,null,R.createElement(I,{color:m,italic:a},p),R.createElement($,{flexDirection:"column",marginLeft:1},R.createElement($,null,R.createElement(I,{bold:!a,color:a?mn:void 0,italic:a},`${e} `),d&&R.createElement(I,null,R.createElement(Markdown,null,`(${t})`))),r&&R.createElement($,{columnGap:1},u&&R.createElement(I,null,"⎿"," "),c?formatTodosForDisplay(r):a?R.createElement($,{width:"100%",flexDirection:"column"},R.createElement(I,null," "),R.createElement(I,{color:mn,wrap:"wrap",italic:!0},r)):l&&i?.oldValue&&i?.newValue?generateDiff(i.oldValue,i.newValue,t):R.createElement($,{width:"100%"},R.createElement(I,{color:s?"red":"",wrap:"wrap"},truncateToolOutputForDisplay(r)))),o&&R.createElement($,{columnGap:1},R.createElement(I,null,"⎿"," "),R.createElement(I,{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="✓"),R.createElement($,null,R.createElement(I,{color:o},s),R.createElement($,{flexDirection:"column",marginLeft:1},R.createElement($,null,R.createElement(I,{color:"gray"},"$ "),R.createElement(I,{color:o,bold:!0},e)),R.createElement($,{columnGap:1},R.createElement(I,null,"⎿"," "),R.createElement(I,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}function SystemMessage({content:e}){return R.createElement($,{flexDirection:"column"},R.createElement(I,{wrap:"wrap"},R.createElement(Markdown,null,e)))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage"),__name(SystemMessage,"SystemMessage");var pn="\n ██████╗ ██████╗ ███╗ ███╗███╗ ███╗ █████╗ ███╗ ██╗██████╗\n██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔══██╗████╗ ██║██╔══██╗\n██║ ██║ ██║██╔████╔██║██╔████╔██║███████║██╔██╗ ██║██║ ██║\n██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║\n╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝\n ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝\n",hn=R.memo(({feed:e,showHeader:t=!1,staticKey:n})=>{const r=t?["header",...e]:e;return R.createElement(A,{items:r,key:n},e=>{if("header"===e)return R.createElement($,{key:"header",marginBottom:1},R.createElement(ne,{name:"vice"},R.createElement(I,null,pn),R.createElement(I,null,"Welcome to Command by Langbase. Agentic coding agent.")));const t=e,n=(()=>{switch(t.role){case"user":return R.createElement(UserMessage,{content:t.input});case"assistant":return R.createElement(AssistantMessage,{content:t.input});case"tool":return R.createElement(ToolMessage,{name:Et(t.name||""),input:t.input,output:t.output||"",isPending:yt(t),hasError:ft(t),metadata:t.metadata});case"bash":return R.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:yt(t),hasError:ft(t)});case"system":return R.createElement(SystemMessage,{content:t.input});default:return R.createElement(R.Fragment,null)}})();return R.createElement($,{key:t.id,marginBottom:1},n)})}),gn=__name(({messages:e})=>0===e.length?null:R.createElement($,{borderStyle:"round",borderColor:"#D97706",padding:1,marginBottom:1},R.createElement($,{flexDirection:"column"},R.createElement($,{marginBottom:1},R.createElement(I,{color:"#D97706",bold:!0},"Queued Messages (",e.length,")")),e.map((t,n)=>R.createElement($,{key:n,marginBottom:n===e.length-1?0:1},R.createElement(I,{color:"gray"},"•"),R.createElement($,{marginLeft:1},R.createElement(I,{dimColor:!0},t.length>60?`${t.substring(0,60)}...`:t)))))),"QueuedMessages"),fn=["dim","dim2","normal","normal2","bright","bright2","brighter","brighter2","brightest","brightest","brighter2","brighter","bright2","bright","normal2","normal","dim2","dim"],yn=__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"),wn=__name(({status:e,timeElapsed:n,tokens:r})=>{const[o,s]=U(0),[i,a]=U(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 O(()=>{const e=setInterval(()=>{s(e=>(e+1)%fn.length)},120);return()=>clearInterval(e)},[]),O(()=>{if(i===r)return;const e=r-i,t=Math.max(1,Math.ceil(Math.abs(e)/20)),n=e>0?t:-t,o=setInterval(()=>{a(e=>{const t=e+n;return n>0&&t>=r||n<0&&t<=r?r:t})},100);return()=>clearInterval(o)},[r,i]),__name(formatToken,"formatToken"),__name(formatTime,"formatTime"),R.createElement($,{columnGap:1},R.createElement($,{paddingLeft:1,paddingRight:0},R.createElement(I,{color:yn(fn[o]),bold:!0},"⌘")),R.createElement($,null,R.createElement(I,{color:"#E4CCFF",wrap:"wrap"},e)),R.createElement($,{columnGap:1},R.createElement(I,{dimColor:!0},`(${formatTime(n)}`),R.createElement(I,{dimColor:!0},"•"),R.createElement(I,{color:"gray"},t.arrowDown),R.createElement(I,{dimColor:!0},`${formatToken(Math.round(i))}`),R.createElement(I,{dimColor:!0},"•"),R.createElement($,{columnGap:1},R.createElement(I,{bold:!0,color:"gray"},"esc"),R.createElement(I,{dimColor:!0},"to interrupt)"))))},"Status"),bn=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=U(process.cwd()),[s,i]=U([]),[a,c]=U(0),[l,d]=U(0),u=n.trim()?15:10,m=L((e,t=process.cwd())=>{if(!e.trim())return[];const n=[],r=e.toLowerCase(),o=__name((e,s=0)=>{if(!(s>8))try{K(e).forEach(i=>{const a=y(e,i);try{const e=Q(a),c=g(t,a),l=c.toLowerCase();(i.toLowerCase().includes(r)||l.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),d=c.includes(r);if(l&&!d)return-1;if(!l&&d)return 1;const u=e.name.split("/").length,m=t.name.split("/").length;return u!==m?u-m:e.name.localeCompare(t.name)}),n.slice(0,50)},[]),p=L(e=>{try{const t=K(e),n=[];"/"!==e&&n.push({name:"..",path:f(e),isDirectory:!0}),t.forEach(t=>{const r=y(e,t);try{const e=Q(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),d(0)}catch{}},[]);O(()=>{if(n.trim()){const e=m(n);i(e),c(0),d(0)}else p(r)},[r,p,n,m]),D((r,i)=>{if(i.escape)t();else if(i.upArrow)c(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t});else if(i.downArrow)c(e=>{const t=Math.min(s.length-1,e+1);return t>=l+u&&d(t-u+1),t});else if(i.return){const t=s[a];if(!t)return;return void(t.isDirectory&&!n.trim()?o(b(t.path)):e(t.path))}});const h=s.slice(l,l+u);return R.createElement($,{flexDirection:"column",paddingLeft:1},R.createElement($,{marginBottom:1,flexDirection:"column"},R.createElement(I,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),R.createElement(I,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • Enter to select/open • Esc to close")),0===h.length?R.createElement(I,{color:"dim"},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):h.map((e,t)=>{const n=l+t,r=e.name;return R.createElement(I,{key:e.path,color:n===a?"white":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList"),En=[{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:"/taste",description:"Manage Taste learning and usage"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"}],Cn=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=U(0),s=N(()=>{if(!n)return En;const e=n.toLowerCase();return En.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 O(()=>{o(0)},[n]),D((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?R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement(I,{color:"dim"},"No commands found")):R.createElement($,{flexDirection:"column",paddingLeft:1},R.createElement($,{columnGap:4},R.createElement($,{flexDirection:"column"},s.map((e,t)=>R.createElement(I,{key:e.command,color:r===t?"white":"dim"},e.command))),R.createElement($,{flexDirection:"column"},s.map((e,t)=>R.createElement(I,{key:e.command,color:r===t?"white":"dim"},e.description)))))},"CommandMenu"),xn=__name(({onSelectSession:e,onClose:t})=>{const[r,o]=U([]),[s,i]=U(0),[a,c]=U(!0);O(()=>{l()},[]);const l=__name(async()=>{c(!0);const e=await an.listSessions();o(e.slice(0,30)),c(!1)},"loadSessions");if(D((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 R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement(I,{color:"gray"},"Loading sessions..."));if(0===r.length)return R.createElement($,{flexDirection:"column",paddingLeft:2},R.createElement(I,{color:"gray"},"No previous sessions found"),R.createElement(I,{color:"dim",dimColor:!0},"Press ESC to go back"));const d=__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 R.createElement($,{flexDirection:"column",paddingLeft:1},R.createElement(I,{color:"cyan",bold:!0},"Resume Session"),R.createElement(I,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),R.createElement($,{marginTop:1}),R.createElement($,{columnGap:2,marginBottom:1},R.createElement($,{width:5},R.createElement(I,{color:"gray"}," ")),R.createElement($,{width:13},R.createElement(I,{color:"gray"},"Modified")),R.createElement($,{width:20},R.createElement(I,{color:"gray"},"Git Branch")),R.createElement($,{width:11},R.createElement(I,{color:"gray"},"# Messages")),R.createElement($,null,R.createElement(I,{color:"gray"},"Summary"))),R.createElement($,{columnGap:2},R.createElement($,{flexDirection:"column",width:5},r.map((e,t)=>R.createElement(I,{key:`sel-${t}`,color:s===t?"cyan":"gray"},s===t?`${n.pointer} ${t+1}.`:` ${t+1}.`))),R.createElement($,{flexDirection:"column",width:13},r.map((e,t)=>R.createElement(I,{key:`mod-${e.id}`,color:s===t?"white":"gray"},d(e.lastModified)))),R.createElement($,{flexDirection:"column",width:20},r.map((e,t)=>R.createElement(I,{key:`branch-${e.id}`,color:s===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),R.createElement($,{flexDirection:"column",width:11},r.map((e,t)=>R.createElement(I,{key:`msg-${e.id}`,color:s===t?"white":"gray"},e.messageCount))),R.createElement($,{flexDirection:"column"},r.map((e,t)=>R.createElement(I,{key:`summary-${e.id}`,color:s===t?"white":"gray"},u(e.firstMessage))))))},"SessionsResumeTable"),vn=__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 R.createElement($,{paddingRight:1},R.createElement(I,{color:r(n),dimColor:!0},n.toFixed(1),"% context used (",t(e.current),"/",t(e.limit),")"))},"ContextUsage"),Sn=__name(({tasteLearning:e,tasteUsage:t,showSeparator:n=!1})=>{if(!e&&!t)return null;const r=[];return e&&r.push("learn"),t&&r.push("use"),R.createElement($,null,R.createElement(I,{color:"green",dimColor:!0},"● taste ",r.join(" & ")),n&&R.createElement(I,{color:"gray",dimColor:!0}," • "))},"TasteStatus");async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=ce(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:d}=s;(l>i||d>i)&&(l>d?(d=Math.round(d*i/l),l=i):(l=Math.round(l*i/d),d=i)),t.includes("png")&&s.hasAlpha?(a=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(a=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=a.length;return{compressedBase64:a.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:u,compressionRatio:r/u}}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 kn=__name(()=>R.createElement($,{flexDirection:"column",paddingLeft:1},R.createElement(I,{color:"dim",bold:!0},"Available Shortcuts:"),R.createElement($,{columnGap:4},R.createElement($,{flexDirection:"column"},R.createElement(I,{color:"dim"},"! for bash mode"),R.createElement(I,{color:"dim"},"/ for commands"),R.createElement(I,{color:"dim"},"@ for file paths")),R.createElement($,{flexDirection:"column"},R.createElement(I,{color:"dim"},"double tap esc to clear input"),R.createElement(I,{color:"dim"},"shift + ⏎ for newline"),R.createElement(I,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Tn=__name(({input:e,onSubmit:t,setInput:r,showCursor:o=!0,placeholder:s="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:c,setFileSearchQuery:l,onCommand:d,contextUsage:u,tasteLearning:m=!1,tasteUsage:p=!1,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w,updateStatus:b,updateFailedInfo:E})=>{const[C,x]=U(0),[v,S]=U(!1),[k,T]=U(!1),[P,A]=U(!1),[F,j]=U(!1),[M,O]=U(""),[B,z]=U(!1),[W,q]=U(null),[G,J]=U([]),[V,H]=U([]),[K,Q]=U(""),Y=_(!1),[Z,X]=U(!1),ee=L(()=>{r(""),T(!1),j(!1),O(""),z(!1),J([]),H([]),Q(""),X(!1),x(e=>e+1)},[r]),te=L(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)},[]),ne=L(()=>{const t=te(e);r(t),x(e=>e+1)},[e,te,r]);function handlePastedContent(t){if(t.length>200){const n=`[Text#${G.length+1}]`;J(e=>[...e,t]),r(e+n),x(e=>e+1)}else r(e+t),x(e=>e+1)}D(async(t,n)=>{if(!n.ctrl&&!n.meta&&!n.shift){if(""===t)return void ee();if(""===t)return void ne()}if(n.meta&&n.delete)return Y.current=!0,void ne();if(n.meta&&n.backspace)ee();else if(n.alt&&n.backspace)ne();else{if(n.ctrl&&"w"===t)return Y.current=!0,void ne();if(n.meta&&"w"===t)return Y.current=!0,void ee();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#${V.length+1}]`;H(e=>[...e,n]),r(t+e),x(e=>e+1)}else{const e=await detectClipboardText();e&&handlePastedContent(e)}return void(Y.current=!0)}}else{if((n.ctrl||n.meta)&&"u"===t)return Y.current=!0,void ee();if(n.ctrl&&t)switch(t.toLowerCase()){case"k":case"a":return void ee();case"z":return A(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100)}if(n.escape){if(B)return z(!1),r(K),void x(e=>e+1);const e=Date.now(),t=500;return W&&e-W<t?(ee(),q(null)):(q(e),setTimeout(()=>q(null),t)),S(!1),void T(!1)}v&&(n.backspace||n.delete)&&0===e.length&&S(!1)}}}),__name(handlePastedContent,"handlePastedContent");const re=L(async t=>{const n=processBracketedPaste(t);if(n.isPasteStart&&!Z){if(X(!0),n.isPasteEnd){X(!1);const t=await detectClipboardImage();if(t){const n=`[Image#${V.length+1}]`;H(e=>[...e,t]),r(e+n),x(e=>e+1)}else if(n.cleanedContent)handlePastedContent(n.cleanedContent);else{const e=await detectClipboardText();e&&handlePastedContent(e)}return}return}if(Z&&!n.isPasteEnd)return;if(Z&&n.isPasteEnd){X(!1);const e=await detectClipboardImage();if(e){const t=`[Image#${V.length+1}]`;H(t=>[...t,e]),r(n.cleanedContent+t),x(e=>e+1)}else{const e=await detectClipboardText();e?handlePastedContent(e):n.cleanedContent&&handlePastedContent(n.cleanedContent)}return}if(n.isPasteEnd&&!n.isPasteStart)return;if(Y.current)return void(Y.current=!1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!v)return S(!0),r(""),void x(e=>e+1);if("!"===s&&!k)return S(!1),T(!0),r(""),void x(e=>e+1);"/"!==s||F||(j(!0),O(""))}if(F){const e=t.lastIndexOf("/");if(-1!==e){const n=t.substring(e+1);O(n)}}if("@"!==s||i||(a(!0),l("")),i)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!1),l("");else{const n=t.substring(e+1);n.includes("/")||n.includes(".")?(a(!1),l("")):l(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);l(e),a(!1)}else l(n)}}v&&(t!==e||t.length<e.length)&&S(!1),0===t.length&&(T(!1),j(!1),O(""),z(!1),H([]),J([]),l(""),Q(""),X(!1)),r(t)},[v,e,r,i,a,k,Z,V]),oe=L(async()=>{if(v)return void S(!1);let n=e.trim(),r=[];const o=V.length>0,s=G.length>0;if(!k&&o){const e=[];V.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;G.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),O(""),H([]),J([])},[t,v,e,k,V]),se=L(t=>{const n=g(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),l(""),x(e=>e+1)},[r,a,e,i,c,l]),ie=L(()=>{a(!1),l("")},[a,l]),ce=L(t=>{"/resume"===t?(Q(e),j(!1),O(""),z(!0),r(""),x(e=>e+1)):(j(!1),O(""),r(""),x(e=>e+1),d&&d(t))},[d,r,e]),le=L(()=>{j(!1),O(""),r(""),x(e=>e+1)},[r]),de=L(e=>{z(!1),r(""),Q(""),x(e=>e+1),d&&d(`/resume:${e}`)},[d]),ue=L(()=>{z(!1),r(K),x(e=>e+1)},[K]),me=N(()=>!v&&0===e.length&&!k&&!B,[v,e,k,F,B]),pe=__name(()=>v||i||F||B||P?0:me||k?3:4,"getBottomMargin");return R.createElement($,{width:"100%",flexDirection:"column",marginBottom:pe()},!B&&R.createElement($,{borderStyle:"round",borderRight:!1,borderLeft:!1,borderColor:k?"green":"gray",paddingY:0,width:"100%"},R.createElement(I,{color:k?"green":"dim"},k?"!":n.pointer),R.createElement($,{flexGrow:1,paddingLeft:1},R.createElement(ae,{key:C,value:e,placeholder:s,onChange:re,onSubmit:()=>{i||F||B||oe()},showCursor:o}))),v&&R.createElement(kn,null),P&&R.createElement($,{paddingTop:1},R.createElement(I,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&R.createElement(bn,{onSelectFile:se,onClose:ie,searchQuery:c}),F&&R.createElement(Cn,{onSelectCommand:ce,onClose:le,searchQuery:M}),B&&R.createElement(xn,{onSelectSession:de,onClose:ue}),me&&R.createElement($,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:2},R.createElement(I,{color:"dim"},"? for shortcuts"),R.createElement($,{flexDirection:"row"},b&&R.createElement($,{marginRight:2},R.createElement(I,{color:"green",dimColor:!0},`${n.tick} Command Code updated: v${b.updatedFrom} ${n.arrowRight} v${b.updatedTo}`)),E&&R.createElement($,{marginRight:2},R.createElement(I,{color:"yellow",dimColor:!0},n.info," Update available:"," ",E.currentVersion," ",n.arrowRight," ",E.latestVersion)),R.createElement(Sn,{tasteLearning:m,tasteUsage:p,showSeparator:!!u}),R.createElement(vn,{usage:u||null}))),k&&R.createElement($,{paddingLeft:1},R.createElement(I,{color:"green"},"! for bash mode")),f&&h&&R.createElement($,{paddingLeft:1},R.createElement(I,{color:"#E4CCFF"},"SHARED: ",h.url," (copied to clipboard)")),y&&R.createElement($,{paddingLeft:1},R.createElement(I,{color:y.includes("NOT SHARED")?"red":"#E4CCFF"},y)),w&&R.createElement($,{paddingLeft:1},R.createElement(I,{color:"#E4CCFF"},w)))},"InputBox"),Pn=R.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:p,tasteLearning:h,tasteUsage:g,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C})=>{const[x,v]=U(0);return O(()=>{if(!t)return void v(0);const e=setInterval(()=>{v(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),R.createElement($,{flexDirection:"column"},R.createElement(gn,{messages:e}),(t||n.isExecuting)&&R.createElement(wn,{tokens:m,timeElapsed:x,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),R.createElement(Tn,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:p,tasteLearning:h,tasteUsage:g,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C}))}),An=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:r}=j(),[o,s]=U([]),[i,a]=U(0),[c,l]=U(!0),[d,u]=U(0),m=30;O(()=>{p()},[]);const p=__name(async()=>{l(!0);const e=await an.listSessions();s(e),l(!1)},"loadSessions");if(D((t,n)=>{n.upArrow?a(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t}):n.downArrow?a(e=>{const t=Math.min(o.length-1,e+1);return t>=d+m&&u(t-m+1),t}):n.return?o.length>0&&e(o[i].id):(n.escape||n.ctrl&&"c"===t)&&r()}),c)return R.createElement($,{flexDirection:"column",paddingLeft:2,paddingTop:1},R.createElement(I,{color:"gray"},"Loading sessions..."));const h=__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 R.createElement($,{flexDirection:"column"},R.createElement(I,{color:"gray"},"No sessions available"));const f=o.slice(d,d+m),y=d;return R.createElement($,{flexDirection:"column",paddingLeft:1},o.length>m&&R.createElement($,{marginBottom:1},R.createElement(I,{color:"dim"},"Showing ",d+1,"-",Math.min(d+m,o.length)," ","of ",o.length," sessions",d>0&&" (↑ for more)",d+m<o.length&&" (↓ for more)")),R.createElement($,{columnGap:2,marginBottom:1},R.createElement($,{width:7},R.createElement(I,{color:"gray"}," ")),R.createElement($,{width:13},R.createElement(I,{color:"gray"},"Modified")),R.createElement($,{width:11},R.createElement(I,{color:"gray"},"# Messages")),R.createElement($,{width:20},R.createElement(I,{color:"gray"},"Git Branch")),R.createElement($,null,R.createElement(I,{color:"gray"},"Summary"))),R.createElement($,{columnGap:2},R.createElement($,{flexDirection:"column",width:7},f.map((e,t)=>{const r=y+t;return R.createElement(I,{key:`sel-${r}`,color:i===r?"cyan":"gray"},i===r?`${n.pointer} ${r+1}.`:` ${r+1}.`)})),R.createElement($,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return R.createElement(I,{key:`mod-${e.id}`,color:i===n?"white":"gray"},h(e.lastModified))})),R.createElement($,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return R.createElement(I,{key:`msg-${e.id}`,color:i===n?"white":"gray"},e.messageCount)})),R.createElement($,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return R.createElement(I,{key:`branch-${e.id}`,color:i===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),R.createElement($,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return R.createElement(I,{key:`summary-${e.id}`,color:i===n?"white":"gray"},g(e.firstMessage))}))))},"SessionTable"),$n=__name(({onTrust:e,onExit:t})=>{const{exit:r}=j(),[o,s]=U(1),i=process.cwd().replace(process.env.HOME||"","~");return D((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())}),R.createElement($,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1},R.createElement(I,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),R.createElement($,{marginTop:1},R.createElement(I,{color:"gray"},i)),R.createElement($,{marginTop:1,flexDirection:"column"},R.createElement(I,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),R.createElement($,{marginTop:1},R.createElement(I,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),R.createElement($,{marginTop:1,flexDirection:"column"},R.createElement($,null,R.createElement(I,{color:1===o?"cyan":"gray"},1===o?n.pointer:" "," 1. Yes, proceed")),R.createElement($,null,R.createElement(I,{color:2===o?"cyan":"gray"},2===o?n.pointer:" "," 2. No, exit"))))},"TrustPrompt"),In=class extends le{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||h.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 v.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=h.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=h.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=h.join(this.projectRoot,".command-code"),t=h.join(e,"settings.local.json");try{await v.mkdir(e,{recursive:!0});let n={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await v.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 v.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=h.join(this.projectRoot,".command-code"),n=h.join(t,"settings.local.json"),r=`Bash(${e.split(" ")[0]}:*)`;try{let e;await v.mkdir(t,{recursive:!0});try{const t=await v.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 v.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .command-code settings:",e)}}},Dn=__name((e={})=>{const[t,n]=U(null),[r,o]=U(null),[s,i]=U(!1);return O(()=>{const t=e.projectRoot||process.cwd(),r=new In(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:L(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:L(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:L(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:L(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:L(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:L((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:L(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions"),Fn=__name(({request:e,onResponse:t})=>{const[r]=U(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=h.basename(e.filePath),n=h.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 R.createElement($,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},R.createElement($,{marginBottom:1},R.createElement(I,{bold:!0,color:"yellow"},c())),R.createElement($,{marginBottom:1},R.createElement(I,{bold:!0},"Do you want to ",i()," ",R.createElement(I,{color:"cyan"},a()),"?")),R.createElement(de,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>R.createElement(I,{color:"cyan"},e?n.pointer:" "),itemComponent:({label:e,isSelected:t})=>R.createElement(I,{color:t?"cyan":"white"},e.includes("(")?R.createElement(R.Fragment,null,e.split("(")[0],R.createElement(I,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),jn=__name(({request:e,onResponse:t})=>{const[r]=U(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 R.createElement($,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},R.createElement($,{marginBottom:1},R.createElement(I,{bold:!0,color:"yellow"},"Execute Shell Command")),R.createElement($,{marginBottom:1},R.createElement(I,{bold:!0},"Command Code needs to execute ",R.createElement(I,{color:"cyan"},c()),".")),e.workingDirectory&&R.createElement($,{marginBottom:1},R.createElement(I,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&R.createElement($,{marginBottom:1},R.createElement(I,{color:"gray",italic:!0},e.description)),R.createElement(de,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:r,indicatorComponent:({isSelected:e})=>R.createElement(I,{color:"cyan"},e?n.pointer:" "),itemComponent:({label:e,isSelected:t})=>R.createElement(I,{color:t?"cyan":"white"},e)}))},"ShellPermissionPrompt"),Mn=__name(()=>process.stdout.write("win32"===process.platform?"[2J[0f":"[2J[3J[H"),"clearConsole"),Rn=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const{exit:r}=j(),[o,s]=U(0),[i,a]=U(!1),[c,l]=U(!1),[d,u]=U(!0),[m,p]=U(""),[h,g]=U(!1);O(()=>{__name(async()=>{try{const[e,t]=await Promise.all([isTasteLearningEnabled(),isTasteUsageEnabled()]);a(e),l(t)}catch(e){}finally{u(!1)}},"loadSettings")()},[]),D((t,n)=>{if(n.upArrow&&o>0)s(o-1);else if(n.downArrow&&o<3)s(o+1);else{if(!n.return&&" "!==t)return n.escape?h?(p(""),void g(!1)):(Mn(),void e()):void 0;0===o?f():1===o?y():2===o?w():3===o&&b()}});const f=__name(async()=>{const e=!i;a(e);try{await setTasteConfig(e,c),t?.()}catch(t){a(!e)}},"toggleTasteLearning"),y=__name(async()=>{const e=!c;l(e);try{await setTasteConfig(i,e),t?.()}catch(t){l(!e)}},"toggleTasteUsage"),w=__name(async()=>{try{p("Fetching taste learnings...");const e=new Mt({baseUrl:getApiBaseUrl()}),t=an.getCurrentProjectDirName(),n=await e.get({endpoint:`/alpha/taste/${t}/rules`});if(0===n.total)p("No taste learnings yet. Chat more to help agent learn!"),g(!1);else{const e=n.rules.map((e,t)=>`${t+1}. ${e.instruction} (${e.scope})`).join("\n");p(`Found ${n.total} taste learning${1===n.total?"":"s"}:\n${e}`),g(!0)}}catch(e){p("Failed to get taste learnings")}setTimeout(()=>p(""),8e3)},"handleListLearnings"),b=__name(async()=>{try{p("Clearing all taste learnings...");const e=new Mt({baseUrl:getApiBaseUrl()}),t=an.getCurrentProjectDirName();await e.delete({endpoint:`/alpha/taste/${t}`}),p("All taste learnings cleared successfully")}catch(e){p("Failed to clear taste learnings")}setTimeout(()=>p(""),3e3)},"handleClearLearnings");return d?R.createElement($,{key:n,borderStyle:"round",borderColor:"blue",padding:1,flexDirection:"column"},R.createElement(I,{color:"blue",bold:!0},"Taste Settings"),R.createElement(I,{dimColor:!0},"Loading configuration...")):R.createElement($,{key:n,borderStyle:"round",borderColor:"gray",padding:1,flexDirection:"column"},R.createElement(I,{bold:!0},"Taste Management"),R.createElement(I,{dimColor:!0},"Configure learning preferences and manage data"),R.createElement($,{marginTop:1}),R.createElement($,{justifyContent:"space-between"},R.createElement(I,{color:0===o?"white":"gray"},0===o?"▶ ":" ","Taste learning",R.createElement(I,{dimColor:!0}," - Learn taste from your interactions")),R.createElement(I,{color:i?"white":"gray"},i?"true":"false")),R.createElement($,{justifyContent:"space-between"},R.createElement(I,{color:1===o?"white":"gray"},1===o?"▶ ":" ","Taste usage",R.createElement(I,{dimColor:!0}," ","- Use learned taste to improve responses")),R.createElement(I,{color:c?"white":"gray"},c?"true":"false")),R.createElement($,{marginTop:1}),R.createElement($,null,R.createElement(I,{color:2===o?"white":"gray"},2===o?"▶ ":" ","List learnings",R.createElement(I,{dimColor:!0}," - View all learned taste preferences"))),R.createElement($,null,R.createElement(I,{color:3===o?"white":"gray"},3===o?"▶ ":" ","Clear all learnings",R.createElement(I,{dimColor:!0}," - Delete learned taste preferences"))),m&&R.createElement($,{marginTop:1},R.createElement(I,{dimColor:!0},m)),R.createElement($,{marginTop:1}),R.createElement(I,{dimColor:!0},"↑/↓ to select • Enter/Space to toggle/action •"," ",h?"Esc to clear list":"Esc to close"))},"TasteConfig"),Un=__name(({staticKey:e})=>R.createElement(A,{items:[{staticKey:e}],key:e},()=>R.createElement(I,{key:e},"\0")),"Responsive"),{setText:On}=te,_n=__name(({resume:e=!1,continue:t=!1,updateStatus:n,updateFailedInfo:r})=>{const{exit:o}=j(),[s,i]=U(""),[a,c]=U("Ready..."),[l,d]=U(n),{stdout:u}=M(),[m,p]=U(!1),[h,g]=U(!1),[f,y]=U(0),{executeBash:w,executionState:b}=vt(),[E,C]=U(""),[x,v]=U([]),[S,k]=U(!1),[T,P]=U([]),[A,F]=U(crypto.randomUUID()),[L,N]=U(!1),[B,z]=U(!1),[W,q]=U(!1),[G,J]=U(!1),[V,H]=U(!0),[K,Q]=U(!1),[Y,Z]=U(0),[X,ee]=U(null),[te,ne]=U(null),re=_(te);O(()=>{re.current=te},[te]);const[oe,se]=U(!1),[ie,ae]=U(""),[ce,le]=U(!1),[de,ue]=U(!1),me=__name(async()=>{try{const[e,t]=await Promise.all([isTasteLearningEnabled(),isTasteUsageEnabled()]);le(e),ue(t)}catch(e){}},"loadTasteStatus"),pe=_([]),he=_(null),[ge,fe]=U(null),{requestShellPermission:ye,service:we,respondToPrompt:be,clearSessionPermissions:Ce,setEnabled:xe}=Dn({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{fe({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),he.current&&c("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{fe({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),he.current&&c("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?c("Permission granted"):c("Permission denied")},"onPermissionResponse")});O(()=>{(async()=>{if(await an.isProjectInitialized())if(J(!0),H(!1),me(),t){const e=await an.listSessions();if(e.length>0){const t=e[0];De(t.id)}}else e&&N(!0);else q(!0),H(!1)})()},[e,t,o]),O(()=>{pe.current=T},[T]),O(()=>{if(!S)return;const e=setInterval(()=>{c(bt())},7e3);return()=>clearInterval(e)},[S]),D((e,t)=>{if(!h){if(t.ctrl&&"c"===e&&o(),t.escape)if(ge)be({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),ge.resolve(!1),fe(null),c("Permission denied");else if(S&&he.current){he.current.interrupt(!0),k(!1),c("Interrupted by user");const e=lt("Interrupted by user");v(t=>[...t,e])}t.meta||t.ctrl}}),O(()=>{const e=__name(()=>{Mn(),y(e=>e+1)},"handleResize");if(u)return u.on("resize",e),()=>{u.off("resize",e)}},[u]),O(()=>{he.current||!G||L||B||(he.current=new dn({onFeedUpdate:__name(e=>{v(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...pe.current];return pe.current=[],P([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Z(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{ee(e)},"onContextUsageUpdate"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&we){const e={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${t.args?.join(" ")||""}`};return we.requestShellPermission(e).then(e=>e.allowed)}if(we){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 we.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=re.current;return e?{sessionId:A,secret:e.secret}:null},"getShareInfo")},A),(async()=>{await Ae()})())},[A,L,B,G]);const ve=_(!1),Se=__name(async({role:e,input:t,images:n})=>{if(t.length)if(l&&d(null),Z(0),"bash"===e){if(ve.current)return;ve.current=!0;const e=mt(t);v([...x,e]),i(""),await w(t,e=>{v(e)},()=>{Mn(),y(e=>e+1)}),ve.current=!1}else{if(S)return P(e=>[...e,t]),void i("");if(ve.current)return;ve.current=!0,k(!0),c(bt()),i("");try{he.current&&await he.current.sendMessage(t,n)}catch(e){if("Interrupted by user"===e.message||"InterruptedError"===e.name||"AbortError"===e.name);else if("Insufficient credits"===e.message){c("Insufficient credits");const e=lt("Insufficient credits");v(t=>[...t,e])}else if(e.message?.startsWith("API Error:")){c("API Error");const t=lt(e.message);v(e=>[...e,t])}else{c("API Error");const t=e.message||"An unexpected error occurred",n=lt(`API Error: ${t}`);v(e=>[...e,n])}}finally{k(!1),"Interrupted by user"!==a&&"Permission denied"!==a&&"Insufficient credits"!==a&&c("Ready..."),ve.current=!1}}},"handleSubmit"),ke=__name(()=>{const e=`**Command Code v0.0.4-alpha.7**\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${En.filter(e=>"/help"!==e.command).map(e=>`**${e.command}** - ${e.description}`).join("\n")}`;v(t=>[...t,pt(e)])},"handleHelpCommand"),Te=__name(()=>{if(v([]),Mn(),he.current){he.current=null;const e=crypto.randomUUID();F(e),he.current=new dn({onFeedUpdate:__name(e=>{v(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...pe.current];return pe.current=[],P([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Z(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{ee(e)},"onContextUsageUpdate"),getShareInfo:__name(()=>{const t=re.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e),Ae().catch(console.error)}y(e=>e+1),ee(null),Z(0)},"handleClearCommand"),Pe=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await De(t)}switch(e){case"/exit":o();break;case"/clear":Te();break;case"/help":ke();break;case"/permissions":c("Permissions are enabled");break;case"/permissions:enable":xe(!0),c("File edit permissions enabled");break;case"/permissions:disable":xe(!1),c("File edit permissions disabled");break;case"/permissions:clear":Ce(),c("Session permissions cleared");break;case"/share":$e();break;case"/unshare":Ie();break;case"/taste":g(!0)}},"handleCommand"),Ae=__name(async()=>{const e=he.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&ne({url:t.url,secret:t.secret})}},"loadShareInfo"),$e=__name(async()=>{if(A){if(te)return await On(te.url),c(""),se(!0),void setTimeout(()=>{se(!1)},3e3);try{c("Creating share link...");const e=he.current?.getMessages()||[],t=cn.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new Mt({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:Ee.CREATE,body:{sessionId:A,messages:t}}),o={url:r.url,secret:r.secret};ne(o);const s=he.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await On(r.url),c(""),se(!0),setTimeout(()=>{se(!1)},5e3)}catch(e){c(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else c("No active session to share")},"handleShareCommand"),Ie=__name(async()=>{if(A){if(!te)return ae("NOT SHARED: Session is not currently shared"),void setTimeout(()=>ae(""),5e3);try{c("Removing share link...");const e=new Mt({baseUrl:getApiBaseUrl()});await e.delete({endpoint:Ee.DELETE,body:{sessionId:A,secret:te.secret}});const t=he.current?.getSessionManager();t&&await t.deleteShareInfo(),ae("UNSHARED: Sharing has stopped"),c(""),ne(null),setTimeout(()=>{ae("")},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"),De=__name(async e=>{try{v([]),he.current=null,F(e),N(!1),z(!0),await new Promise(e=>setTimeout(e,100)),he.current=new dn({onFeedUpdate:__name(e=>{v(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...pe.current];return pe.current=[],P([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Z(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{ee(e)},"onContextUsageUpdate"),getShareInfo:__name(()=>{const t=re.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const t=await he.current.loadSession(e);await Ae(),v(t),Mn(),y(e=>e+1)}catch(e){console.error("Failed to load session:",e),N(!0),F(crypto.randomUUID())}},"handleSelectSession"),Fe=__name(async()=>{v([]),he.current=null,F(crypto.randomUUID()),N(!1),z(!1)},"handleNewSession"),je=__name(async()=>{try{await an.initializeProject(),q(!1),e?(console.log("No conversations found to resume."),Q(!0),o()):(J(!0),me())}catch(e){console.error("Failed to initialize project:",e),q(!1),Q(!0),o()}},"handleTrust"),Me=__name(()=>{o()},"handleNoTrust");if(K)return null;if(W)return R.createElement(R.Fragment,null,R.createElement(Un,{staticKey:f}),R.createElement($n,{onTrust:je,onExit:Me}));if(V)return null;if(L)return R.createElement(An,{onSelectSession:De,onNewSession:Fe});if(!G)return null;if(ge){if("shell_command"===ge.toolName){const e=ge.params;return R.createElement($,{flexDirection:"column",width:"100%"},R.createElement(hn,{staticKey:f,feed:x,showHeader:!0}),R.createElement($,{marginY:1},R.createElement(jn,{request:e,onResponse:e=>{be(e);const t="no"!==e.value;ge.resolve(t),fe(null),c(t?"Shell command allowed":"Shell command denied")}})))}{const e={action:ge.toolName.includes("edit")?"edit":ge.toolName.includes("write")?"create":ge.toolName.includes("delete")?"delete":"edit",filePath:ge.params.filePath||ge.params.file_path||ge.params.path||ge.params.absolutePath||ge.params.notebook_path||"unknown",description:`Allow ${ge.toolName} operation`,newContent:ge.params.new_content||ge.params.content};return R.createElement($,{flexDirection:"column",width:"100%"},R.createElement(hn,{staticKey:f,feed:x,showHeader:!0}),R.createElement($,{marginY:1},R.createElement(Fn,{request:e,onResponse:e=>{be(e);const t="no"!==e.value;ge.resolve(t),fe(null),c(t?"File operation allowed":"File operation denied")}})))}}return h?R.createElement(R.Fragment,null,R.createElement(Un,{staticKey:f}),R.createElement($,{flexDirection:"column",width:"100%"},R.createElement($,{marginBottom:1},R.createElement(I,{dimColor:!0},"Press Esc to return to conversation")),R.createElement(Rn,{onClose:()=>g(!1),onSettingsChange:me,staticKey:f}))):R.createElement($,{flexDirection:"column",width:"100%"},R.createElement(hn,{staticKey:f,feed:x,showHeader:!0}),R.createElement(Pn,{queuedMessages:T,isProcessing:S,executionState:b,status:a,input:s,setInput:i,onSubmit:Se,showFileList:m,setShowFileList:p,fileSearchQuery:E,setFileSearchQuery:C,onCommand:Pe,outputTokens:Y,contextUsage:X,tasteLearning:ce,tasteUsage:de,shareInfo:te,showShareNotification:oe,unshareNotificationMessage:ie,updateStatus:l,updateFailedInfo:r}))},"InteractiveCLI");function getPackageJson(){const e=import.meta.url,t=me(e),n=f(t);return JSON.parse(G(y(n,"./../package.json"),"utf8"))}__name(getPackageJson,"getPackageJson");var Ln=getPackageJson(),Nn=h.join(C.homedir(),".command-code"),Bn=h.join(Nn,"update-status.json"),zn=h.join(Nn,"update-failed.json");function ensureCommandCodeDir(){q.existsSync(Nn)||q.mkdirSync(Nn,{recursive:!0})}async function checkForUpdateAvailable(){try{const e=B("npm view command-code versions --json",{encoding:"utf-8"}),t=JSON.parse(e),n=Ln.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(ue.rcompare)[0];ue.gt(e,n)&&(i=e,a=!0)}if(!a&&r&&s.length>0){const e=s.sort(ue.rcompare)[0];ue.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{B(`npm i -g command-code@${e.latestVersion}`,{stdio:"ignore"}),ensureCommandCodeDir();const t={updatedFrom:e.currentVersion,updatedTo:e.latestVersion,updatedAt:Date.now()};return q.writeFileSync(Bn,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 i -g command-code"),ensureCommandCodeDir();const n={currentVersion:e.currentVersion,latestVersion:e.latestVersion,failedAt:Date.now()};return q.writeFileSync(zn,JSON.stringify(n,null,2)),{success:!1,updateInfo:e}}}function getUpdateStatus(){try{if(ensureCommandCodeDir(),q.existsSync(Bn)){const e=JSON.parse(q.readFileSync(Bn,"utf-8"));return q.unlinkSync(Bn),e}}catch(e){}return null}function getFailedUpdateInfo(){try{if(ensureCommandCodeDir(),q.existsSync(zn)){const e=JSON.parse(q.readFileSync(zn,"utf-8"));return q.unlinkSync(zn),{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 Wn=__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 an.isProjectInitialized()&&0===(await an.listSessions()).length&&(console.log("No conversations found to resume."),process.exit(0)),F(R.createElement(_n,{resume:e.resume,continue:e.continue,updateStatus:t,updateFailedInfo:n}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})},"interactive"),{red:qn,yellow:Gn}=he,Jn=__name((e="ERROR: ",t,n=!0,r=!0)=>{if(t){if(console.log(),n?(console.log(`${ge.error} ${qn(e)}`),console.log(`${ge.error} ${qn("ERROR →")} ${t.name}`),console.log(`${ge.info} ${qn("REASON →")} ${t.message}`),console.log(`${ge.info} ${qn("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${ge.warning} ${Gn(e)}\n`),!r)return!1;process.exit(0)}},"handleError"),Vn=__name(()=>{process.on("unhandledRejection",e=>{Jn(pe`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{const e=await getAuthKey(),n=Pe();if(!e){console.log(he.white(pn)),console.log(he.dim("Welcome to Command by Langbase. Agentic coding agent. "+(n?`env: (${n.replace("--","")})`:""))),console.log(""),console.log(`${t.warning} Authentication required to use Command Code.`),console.log("");const e=fe.createInterface({input:process.stdin,output:process.stdout}),r=await e.question(`Would you like to sign in now? ${he.dim("(y/n)")}: `);e.close();const o=r.trim().toLowerCase();if(""!==o&&"y"!==o&&"yes"!==o)return console.log(""),console.log(`${t.info} You can authenticate later by running: cmd login`),!1;console.log(""),console.log(`${t.arrowUp} Running: cmd login`),console.log("");try{return B(`cmd login ${n}`,{stdio:"inherit",cwd:process.cwd()}),await getAuthKey()?(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 login`),!1)}catch(e){return console.log(""),console.log(`${t.cross} Login command failed. Please run: cmd login`),!1}}return!0}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var Hn=getPackageJson(),Kn=process.cwd();global.COMMAND_CODE_CWD=Kn;var Qn=new we("CommandCode");Vn(),(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:Wn({resume:!0});break;case e.continue:Wn({continue:!0});break;default:Wn()}}__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).allowUnknownOption().allowExcessArguments(),t.addCommand(Ne),t.addCommand(_e),t.addCommand(Fe),t.addCommand(je),t.addCommand(Me),t.addCommand(Re),t.hook("preAction",()=>{Qn.debug("Command starting...")}),t.hook("postAction",()=>{Qn.debug("Command completed.")}),t.parse()})();
|