command-code 0.0.4-beta.6 → 0.0.4-beta.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.
Files changed (2) hide show
  1. package/dist/index.mjs +2 -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,Option as t}from"commander";import{execSync as n,spawn as r}from"child_process";import o,{mainSymbols as a}from"figures";import*as s from"@clack/prompts";import{confirm as i,isCancel as c,cancel as l,note as d,password as u,select as m,outro as g}from"@clack/prompts";import p from"picocolors";import h from"open";import*as f from"path";import y,{dirname as w,join as E,relative as b,isAbsolute as v,resolve as C}from"path";import*as T from"os";import k from"os";import*as A from"fs/promises";import P,{mkdir as S,writeFile as x}from"fs/promises";import $ from"crypto";import I,{z as D}from"zod";import R,{useState as F,useEffect as M,useRef as j,useCallback as N,useMemo as _}from"react";import{Static as O,Box as U,Text as L,useInput as B,render as W,useApp as z,useStdout as G}from"ink";import V from"ink-text-input";import q from"sharp";import*as H from"fs";import J,{existsSync as K,readFileSync as Y,promises as Q,constants as Z,readdirSync as X,statSync as ee}from"fs";import te from"chalk";import ne from"open-editor";import*as re from"process";import oe from"semver";import{fileURLToPath as ae}from"url";import{minimatch as se}from"minimatch";import{glob as ie}from"glob";import{quote as ce}from"shell-quote";import le from"gray-matter";import{MessageStream as de}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import ue from"@sindresorhus/slugify";import{EventEmitter as me}from"events";import ge from"@crosscopy/clipboard";import pe from"ink-gradient";import{setOptions as he,parse as fe}from"marked";import ye from"marked-terminal";import*as we from"diff";import Ee from"ink-select-input";import be from"dedent";import ve from"log-symbols";import Ce from"readline/promises";var Te=Object.defineProperty,__name=(e,t)=>Te(e,"name",{value:t,configurable:!0}),ke=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${o.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${o.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${o.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${o.warning} ${e}`)}debug(e){process.env.DEBUG&&console.log(`[${this.prefix}] ${o.bullet} ${e}`)}};function heading({text:e,sub:t,dim:n,green:r}){return r?`${p.bgGreen(p.black(` ${e} `))} ${t&&t}`:n?`${p.bgBlack(p.white(` ${e} `))} ${t&&t}`:`${p.bold(p.bgCyan(p.black(` ${e} `)))} ${t&&t}`}__name(heading,"heading");var Ae="--co",Pe="--xco",Se=`x-${Ae.replace("--","")}-flag`,xe="x-oauth-token",$e="x-project-slug",Ie="x-taste-learning",De={ALPHA:{GENERATE:"/alpha/generate",WHOAMI:"/alpha/whoami",NAMESPACES:"/alpha/namespaces",AGENT:{GENERATE:"/alpha/agent/generate"},SHARE:{CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",DATA:"/alpha/share/data",APPEND:"/alpha/share/append",CONNECT:"/alpha/share/connect"},TASTE:{GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"}},BETA:{TASTE:{PACKAGES:{UPLOAD:"/beta/taste/packages/:namespace",LIST:"/beta/taste/packages",GET:"/beta/taste/packages/:namespace/:packageName",FILES:"/beta/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/beta/taste/packages/:namespace/:packageName/download"}}},INTERNAL:{ADMIN:{USERS:"/internal/admin/users",GRANT_CREDITS:"/internal/admin/grant-credits",ORGS:"/internal/admin/orgs",GRANT_ORG_CREDITS:"/internal/admin/grant-org-credits",ENTITY_TYPE:"/internal/admin/entity-type"},API_KEYS:{CREATE:"/internal/api-keys/create",LIST:"/internal/api-keys/list",DELETE:"/internal/api-keys/delete"},BILLING:{CREDITS:{GET:"/internal/billing/credits"},CUSTOMERS:{GET:"/internal/billing/customers",UPSERT:"/internal/billing/customers",SETUP_INTENT:"/internal/billing/customers/setup-intent",PAYMENT_METHOD:"/internal/billing/customers/payment-method",SET_DEFAULT_PAYMENT_METHOD:"/internal/billing/customers/payment-method/set-default",INVOICES:"/internal/billing/customers/invoices"},SUBSCRIPTIONS:{GET:"/internal/billing/subscriptions"},WEBHOOK:"/internal/billing/webhook"},ORGS:{LIST:"/internal/orgs",GET:"/internal/orgs/:login",CREATE:"/internal/orgs",UPDATE:"/internal/orgs/:id",DELETE:"/internal/orgs/:id",AVATAR:"/internal/orgs/:id/avatar",MEMBERS:{LIST:"/internal/orgs/:id/members",ADD:"/internal/orgs/:id/members",UPDATE:"/internal/orgs/:id/members/:userId",REMOVE:"/internal/orgs/:id/members/:userId"},INVITATIONS:{LIST:"/internal/orgs/:id/invitations",SEND:"/internal/orgs/:id/invitations",ACCEPT:"/internal/invitations/:token/accept",CANCEL:"/internal/invitations/:id"}},USER:{SETTINGS:"/internal/user/settings",AVATAR:"/internal/user/avatar"},USAGE:{LIST:"/internal/usage",SUMMARY:"/internal/usage/summary"},TASTE:{PACKAGES:{LIST:"/internal/taste/packages",GET:"/internal/taste/packages/:namespace/:packageName",FILES:"/internal/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/internal/taste/packages/:namespace/:packageName/download"}}}},Re={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")}},BETA:{TASTE_PACKAGES:{UPLOAD:new RegExp("^/beta/taste/packages/[a-zA-Z0-9_-]+$"),FILES:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download")}},INTERNAL:{ORGS:{GET:new RegExp("/internal/orgs/[a-zA-Z0-9_-]+")},TASTE:{PACKAGES:{GET:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),FILES:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),DOWNLOAD:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download")}}}};function getStudioAuthUrl(e){return"dev"===e?"http://localhost:3000/settings/api":"staging"===e?"https://staging.commandcode.ai/settings/api":"https://commandcode.ai/settings/api"}Object.values(Re.ALPHA.TASTE),Object.values(Re.BETA.TASTE_PACKAGES),De.ALPHA.GENERATE,De.ALPHA.AGENT.GENERATE,De.ALPHA.WHOAMI,De.ALPHA.NAMESPACES,De.ALPHA.SHARE.CREATE,De.ALPHA.SHARE.DELETE,De.ALPHA.SHARE.APPEND,De.ALPHA.TASTE.LEARN,De.ALPHA.TASTE.DELETE,De.ALPHA.TASTE.GET,De.ALPHA.TASTE.UPDATE,Object.values(De.BETA.TASTE.PACKAGES),Object.values(Re.INTERNAL.ORGS),Object.values(Re.INTERNAL.TASTE.PACKAGES),__name(getStudioAuthUrl,"getStudioAuthUrl");var Fe,Me="anthropic";I.enum(["owner","admin","member"]),(e=>{e.OAuth=D.object({type:D.literal("oauth"),refresh:D.string(),access:D.string(),expires:D.number()}),e.ApiKey=D.object({type:D.literal("api"),key:D.string()}),e.Info=D.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(()=>y.join(k.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=t(),r="dev"===e?"models.dev.json":"staging"===e?"models.staging.json":"models.json";return y.join(n(),r)},"getAuthFile");async function get(e){try{const t=await P.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),a=r();await P.mkdir(o,{recursive:!0});let s={};try{const e=await P.readFile(a,"utf-8");s=JSON.parse(e)}catch{}s[e]=t,await P.writeFile(a,JSON.stringify(s,null,2)),await P.chmod(a,384)}async function remove(e){const t=r();try{const n=await P.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await P.unlink(t):(await P.writeFile(t,JSON.stringify(r,null,2)),await P.chmod(t,384))}catch{}}async function list2(){try{const e=await P.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=list2,__name(list2,"list")})(Fe||(Fe={}));var je,Ne="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing";async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=q(n),a=await o.metadata();if(!a.width||!a.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const s=1200;let i,c,{width:l,height:d}=a;(l>s||d>s)&&(l>d?(d=Math.round(d*s/l),l=s):(l=Math.round(l*s/d),d=s)),t.includes("png")&&a.hasAlpha?(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=i.length;return{compressedBase64:i.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")}(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 $.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return $.createHash("sha256").update(e).digest("base64url")}function generateState(){return $.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,a){const s=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:a})});if(!s.ok){const e=await s.text();throw new Error(`Token exchange failed: ${e}`)}const i=await s.json();await Fe.set("anthropic",{type:"oauth",refresh:i.refresh_token,access:i.access_token,expires:Date.now()+1e3*i.expires_in})}async function refreshAccessToken(){const e=await Fe.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 Fe.remove("anthropic");const o=await r.json();return await Fe.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 Fe.remove("anthropic")}}}async function getValidAccessToken(){const e=await Fe.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")})(je||(je={})),__name(compressImageForSharing,"compressImageForSharing"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode");var _e={"command-code":{id:"command-code",displayName:"Command Code",description:"recommended",requiresAuth:!1},anthropic:{id:"anthropic",displayName:"Anthropic",description:"Claude Pro/Max",requiresAuth:!0,hidden:!0,authComponent:__name(({onSuccess:e,onCancel:t})=>{const[n,r]=F(""),[o,a]=F(null),[s,i]=F(!1),[c,l]=F(null),[d,u]=F(!0),[m,g]=F(!1),[p,f]=F(!1);M(()=>{const{url:e,verifier:t,state:n}=je.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=N(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||p){if(!p||t.isPasteEnd){if(p&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();r(t)}else if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();r(e)}return}r(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();r(t)}else if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();r(e)}return}},[p]);B((e,n)=>{n.escape&&t(),d&&!m&&("y"===e||"Y"===e?o&&(h(o.url).catch(console.error),g(!0),u(!1)):"n"!==e&&"N"!==e||t())});const w=__name(async()=>{if(n.trim()&&o&&!s){i(!0),l(null);try{const t=n.split("#")[0].trim();await je.exchangeCodeForTokens(t,o.verifier,o.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){l(e instanceof Error?e.message:"Authentication failed"),i(!1)}}},"handleSubmit");return d&&!m?R.createElement(U,{flexDirection:"column"},R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0,color:"cyan"},"Anthropic Authentication")),R.createElement(U,{marginBottom:1},R.createElement(L,null,"Open the Anthropic auth page?",R.createElement(L,{dimColor:!0}," (Y/n)")))):R.createElement(U,{flexDirection:"column"},R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0,color:"cyan"},"Anthropic Authentication")),R.createElement(U,{marginBottom:1},R.createElement(L,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),R.createElement(U,{marginBottom:1},R.createElement(L,{dimColor:!0},"After authorizing, copy the code and paste it below:")),c&&R.createElement(U,{marginBottom:1},R.createElement(L,{color:"red"},"Error: ",c)),R.createElement(U,null,R.createElement(L,null,"Authorization code: "),R.createElement(V,{mask:"*",focus:!0,value:n,onChange:y,onSubmit:w,placeholder:"Paste code here..."})),R.createElement(U,{marginTop:1},R.createElement(L,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth"),checkAuth:__name(async()=>!!await je.getValidAccessToken(),"checkAuth")}};function getProviderDisplayName(e){if(!e)return"None";const t=_e[e];return t?.displayName||e}function getProviderConfig(e){return _e[e]}function isInternalFlagPresent(){return process.argv.includes(Ae)}function getProviderOptions(){const e=isInternalFlagPresent();return Object.values(_e).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}async function loadUserConfig(){try{const e=ze();return parseJSON(await A.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=ze();await A.writeFile(t,JSON.stringify(e,null,2)),await A.chmod(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t={...await loadUserConfig(),...e};await saveUserConfig(t)}async function isTasteLearningEnabled(){return(await loadUserConfig()).tasteLearning??!0}async function setTasteLearning(e){const{tasteLearning:t}=e;await updateUserConfig({tasteLearning:t})}async function isOAuthEnforced(){return isInternalFlagPresent()?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),!0):(await loadUserConfig()).forceOAuth??!1}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error('OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.')}__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalFlagPresent,"isInternalFlagPresent"),__name(getProviderOptions,"getProviderOptions"),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken");var Oe=__name(()=>y.join(k.homedir(),".commandcode"),"getAuthDir"),Ue=__name(()=>{const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"dev":t?"staging":"prod"},"getEnv"),Le=__name(()=>{const e=Ue();return"dev"===e?"--dev":"staging"===e?"--staging":""},"getEnvFlag"),Be=__name(e=>{const t=e??Ue(),n="dev"===t?"auth.dev.json":"staging"===t?"auth.staging.json":"auth.json";return y.join(Oe(),n)},"getAuthFile"),We=__name(()=>y.join(k.homedir(),".commandcode"),"getConfigDir"),ze=__name(e=>{const t=e??Ue(),n="dev"===t?"config.dev.json":"staging"===t?"config.staging.json":"config.json";return y.join(We(),n)},"getConfigFile"),Ge=__name(e=>{const t=e??Ue(),n="dev"===t?"models.dev.json":"staging"===t?"models.staging.json":"models.json";return y.join(We(),n)},"getModelsFile");async function loginAction(){try{const e=Ue(),t=getStudioAuthUrl(e);console.log("\n"),s.intro(heading({text:"Command Code Authentication",sub:""}));const n=await i({message:`Open the authentication page? ${p.dim("— copy your API key from there and paste it here.")}`});c(n)&&(l(`${o.cross} Login cancelled.`),process.exit(0)),n&&(await h(t),d(p.yellow("Please copy your API key from the opened page and paste it here.")));const r=await u({message:"Paste your API key:",mask:"*"});c(r)&&(l(`${o.cross} No API key provided.`),process.exit(0)),r.trim()||(console.log(`${o.cross} No API key provided.`),process.exit(1));const a=Oe(),f=Be(e);await P.mkdir(a,{recursive:!0}),await P.writeFile(f,JSON.stringify({apiKey:r},null,2)),await P.chmod(f,384);const y=await m({message:"Select provider",options:getProviderOptions()});if(c(y))l(`${o.cross} No provider selected.`);else if("anthropic"===y){const e=await m({message:"Login method",options:[{value:"anthropic-oauth",label:"Claude Pro/Max"}]});c(e)?l(`${o.cross} No login method selected.`):"anthropic-oauth"===e&&await anthropicAuth()}await updateUserConfig({provider:y});let w=`You are logged in. API key is stored in ~/.commandcode/${"dev"===e?"auth.dev.json":"staging"===e?"auth.staging.json":"auth.json"}. Run \`cmd\` to get started.`;g(p.green(w)),process.exit(0)}catch(e){console.error(`${o.cross} Login failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function anthropicAuth(){try{const{url:e,verifier:t,state:n}=je.createAuthorizationUrl();await i({message:"Open the Anthropic auth page?"})&&(await h(e),d(p.yellow("Please copy your authorization code from the opened page and paste it here.")));const r=await u({message:"Paste your authorization code:",mask:"*"});c(r)&&(l(`${o.cross} No API key provided.`),process.exit(1)),r.trim()||(console.log(`${o.cross} No authorization code provided`),process.exit(1));const a=r.split("#")[0].trim();return await je.exchangeCodeForTokens(a,t,n),!0}catch(e){l(`${o.cross} Anthropic OAuth failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function logoutAction(){try{const e=Ue(),t=Be(e),n=Ge(e);try{await P.unlink(t)}catch(e){}try{const e=await loadUserConfig(),{provider:t,...n}=e;await saveUserConfig(n)}catch(e){}try{await P.unlink(n)}catch(e){}g(p.green("Successfully logged out from Command Code")),process.exit(0)}catch(e){l(`${o.cross} Logout failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function getAuthKey(e){try{const t=Be(e),n=await P.readFile(t,"utf-8");return JSON.parse(n).apiKey||null}catch{return null}}async function statusAction(){try{const e=Ue();await getAuthKey(e)||(l(`${o.cross} Not authenticated. Please login using "cmd auth login".`),process.exit(1)),g(p.green(`${o.tick} Authenticated with Command Code`)),process.exit(0)}catch(e){l(`${o.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 Ve=new e("auth").description("Manage authentication with Command Code");Ve.command("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),Ve.command("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Ve.command("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);var qe=new e("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),He=new e("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Je=new e("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${k.platform()}-${k.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return J.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!e.name.startsWith(".")).filter(e=>!t.has(e.name)).map(e=>e.name).sort()}catch{return[]}}function isGitRepository(){try{return n("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return n("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=n("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=n("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),r=t.filter(e=>e.startsWith(" M")).length,o=t.filter(e=>e.startsWith("A ")).length,a=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,i=[];return r>0&&i.push(`M ${r}`),o>0&&i.push(`A ${o}`),a>0&&i.push(`D ${a}`),s>0&&i.push(`?? ${s}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=n("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 detectTerminal(){const e=process.env;if(e.TERM_PROGRAM){const t=e.TERM_PROGRAM;if("vscode"===t)return{name:"Visual Studio Code",type:"vscode",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("iTerm.app"===t)return{name:"iTerm2",type:"iterm2",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION,iterm2Profile:e.ITERM_PROFILE}};if("Apple_Terminal"===t)return{name:"macOS Terminal",type:"terminal",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("WarpTerminal"===t)return{name:"Warp",type:"warp",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("Hyper"===t)return{name:"Hyper",type:"hyper",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}}}if(e.WT_SESSION||e.WT_PROFILE_ID)return{name:"Windows Terminal",type:"windows-terminal",details:{wtSession:e.WT_SESSION,wtProfileId:e.WT_PROFILE_ID}};if(e.ALACRITTY_SOCKET||e.ALACRITTY_WINDOW_ID)return{name:"Alacritty",type:"alacritty",details:{alacrittySocket:e.ALACRITTY_SOCKET,alacrittyWindowId:e.ALACRITTY_WINDOW_ID}};if(e.KITTY_WINDOW_ID||e.KITTY_PID)return{name:"Kitty",type:"kitty",details:{kittyWindowId:e.KITTY_WINDOW_ID,kittyPid:e.KITTY_PID}};if(e.GNOME_TERMINAL_SERVICE||e.VTE_VERSION)return{name:"GNOME Terminal",type:"gnome-terminal",details:{gnomeTerminalService:e.GNOME_TERMINAL_SERVICE,vteVersion:e.VTE_VERSION}};if(e.KONSOLE_VERSION||e.KONSOLE_PROFILE_NAME)return{name:"Konsole",type:"konsole",details:{konsoleVersion:e.KONSOLE_VERSION,konsoleProfile:e.KONSOLE_PROFILE_NAME}};if(e.TMUX)return{name:"tmux",type:"tmux",details:{tmux:e.TMUX,tmuxPane:e.TMUX_PANE}};if(e.ConEmuPID||e.ConEmuBuild)return{name:"ConEmu",type:"conemu",details:{conEmuPid:e.ConEmuPID,conEmuBuild:e.ConEmuBuild}};if(e.SSH_CLIENT||e.SSH_TTY)return{name:"SSH",type:"ssh",details:{sshClient:e.SSH_CLIENT,sshTty:e.SSH_TTY}};if(e.CI){const t=e.GITHUB_ACTIONS?"GitHub Actions":e.GITLAB_CI?"GitLab CI":e.JENKINS_URL?"Jenkins":e.CIRCLECI?"CircleCI":"Unknown CI";return{name:t,type:"ci",details:{ci:e.CI,ciName:t}}}const t=e.TERM||"unknown";return{name:`Unknown Terminal (${t})`,type:"unknown",details:{term:t,colorterm:e.COLORTERM,shell:e.SHELL}}}function getIsTerminalIterm2(){return"iTerm2"===detectTerminal().name}function isDisableOAuthFlagPresent(){return process.argv.includes(Pe)}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=ze(),t=await P.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,a=isInternalFlagPresent();return isDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):a||o?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),"anthropic"):r}catch{return null}}function getIsExpandToolShortcut(e,t){const n=getIsTerminalIterm2();return!(!n||!e.shift||"O"!==t)||!(n||!e.ctrl||"o"!==t)}__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(detectTerminal,"detectTerminal"),__name(getIsTerminalIterm2,"getIsTerminalIterm2"),__name(isDisableOAuthFlagPresent,"isDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut");var Ke=new ke("Config"),Ye=f.join(T.homedir(),".commandcode-config.json");async function loadConfig(){try{return parseJSON(await A.readFile(Ye,"utf-8"))||{}}catch{return{}}}async function saveConfig(e){await A.writeFile(Ye,JSON.stringify(e,null,2))}__name(loadConfig,"loadConfig"),__name(saveConfig,"saveConfig");var Qe=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?Ke.info(`${e}: ${JSON.stringify(t)}`):Ke.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)=>{"provider"===e&&"anthropic"===t&&(Ke.error('Invalid provider "anthropic". Available provider: command-code'),process.exit(1));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),Ke.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?Ke.info("No configuration values set"):(Ke.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({}),Ke.success("Configuration reset successfully")})),Ze=new ke("Info"),Xe=new e("info").description("Display system information").option("-v, --verbose","Show verbose output").action(e=>{if(Ze.info("System Information:"),console.log("-------------------"),console.log(`${o.info} Date: ${formatDate()}`),console.log(`${o.info} Platform: ${T.platform()}`),console.log(`${o.info} Architecture: ${T.arch()}`),console.log(`${o.info} CPUs: ${T.cpus().length}`),console.log(`${o.info} Memory: ${Math.round(T.totalmem()/1024/1024/1024)} GB`),console.log(`${o.info} Home Directory: ${T.homedir()}`),e.verbose){console.log("\nDetailed CPU Information:"),T.cpus().forEach((e,t)=>{console.log(` CPU ${t}: ${e.model} @ ${e.speed} MHz`)}),console.log("\nNetwork Interfaces:");const e=T.networkInterfaces();Object.keys(e).forEach(t=>{const n=e[t];n&&n.forEach(e=>{"IPv4"!==e.family||e.internal||console.log(` ${t}: ${e.address}`)})})}Ze.success("Information displayed successfully!")});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 et=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 tt({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new nt(e,o,n,r);case 401:return new rt(e,o,n,r);case 403:return new ot(e,o,n,r);case 404:return new at(e,o,n,r);case 409:return new st(e,o,n,r);case 422:return new it(e,o,n,r);case 429:return new ct(e,o,n,r);default:return e>=500?new lt(e,o,n,r):new _APIError(e,o,n,r)}}},tt=class extends et{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)}},nt=class extends et{static{__name(this,"BadRequestError")}status=400},rt=class extends et{static{__name(this,"AuthenticationError")}status=401},ot=class extends et{static{__name(this,"PermissionDeniedError")}status=403},at=class extends et{static{__name(this,"NotFoundError")}status=404},st=class extends et{static{__name(this,"ConflictError")}status=409},it=class extends et{static{__name(this,"UnprocessableEntityError")}status=422},ct=class extends et{static{__name(this,"RateLimitError")}status=429},lt=class extends et{static{__name(this,"InternalServerError")}},dt=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 tt({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 a=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),a}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}),et.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"})}};async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new dt({baseUrl:e});return await t.get({endpoint:De.ALPHA.WHOAMI})}async function whoamiAction(){try{await getAuthKey()||(console.log(`${o.cross} ${p.red('Not authenticated. Please login using "cmd auth login"')}`),process.exit(1));const e=await getAuthenticatedEntity();e.success&&e.user||(console.log(`${o.cross} ${p.red("Failed to fetch user info")}`),process.exit(1)),console.log(`\n${p.bold("User Information:")}`),console.log(`${o.info} Name: ${p.cyan(e.user.name)}`),console.log(`${o.info} Email: ${p.cyan(e.user.email)}`),console.log(`${o.info} Username: ${p.cyan(e.user.userName)}`),e.org&&(console.log(`\n${p.bold("Organization:")}`),console.log(`${o.info} Name: ${p.cyan(e.org.name)}`),console.log(`${o.info} Login: ${p.cyan(e.org.login)}`)),console.log("")}catch(e){console.log(`${o.cross} ${p.red(`Error: ${e instanceof Error?e.message:"Unknown error"}`)}`),process.exit(1)}}__name(getAuthenticatedEntity,"getAuthenticatedEntity"),__name(whoamiAction,"whoamiAction");var ut=new e("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function getTastePath(e){const{target:t}=e;switch(t){case"local-project":return f.join(process.cwd(),".commandcode","taste");case"local-global":return f.join(T.homedir(),".commandcode","taste");case"remote-project":case"remote-user":throw new Error(`Remote storage not yet implemented: ${t}`);default:throw new Error(`Unknown storage target: ${t}`)}}function getRootTasteFile(e){const{target:t}=e;return f.join(getTastePath({target:t}),"taste.md")}function getCategoryPath(e){const{target:t,category:n}=e;return f.join(getTastePath({target:t}),n)}function getCategoryTasteFile(e){const{target:t,category:n}=e;return f.join(getCategoryPath({target:t,category:n}),"taste.md")}function parseTasteBuckets(e){const{content:t,sourcePath:n}=e,r=[],o=t.split(/^# /gm).filter(e=>e.trim());for(const e of o){const t=e.split("\n"),o=t[0].trim();if(e.includes("See ["))continue;const a=[];for(const e of t){const t=parseLearning({line:e});t&&a.push(t)}a.length>0&&r.push({category:normalizeCategory({category:o}),learnings:a,sourcePath:n})}return r}function parseLearning(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)[\.:,]?\s*confidence:\s*(\d*\.?\d+)/i);if(!n)return null;const r=parseFloat(n[2]);return isNaN(r)||r<0||r>1?null:{text:n[1].trim(),confidence:r}}function normalizeCategory(e){const{category:t}=e;return t.toLowerCase().replace(/\s+/g,"-")}function denormalizeCategory(e){const{slug:t}=e;return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function formatBucket(e){const{bucket:t}=e;let n=`# ${denormalizeCategory({slug:t.category})}\n`;for(const e of t.learnings)n+=`- ${e.text}. Confidence: ${e.confidence.toFixed(2)}\n`;return n}__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),__name(parseTasteBuckets,"parseTasteBuckets"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),__name(formatBucket,"formatBucket");var mt="# Taste (Continuously Learned by CommandCode)",gt=class{static{__name(this,"LocalProjectStorage")}target="local-project";async getAllBuckets(){const e=getTastePath({target:this.target});if(!K(e))return[];const t=[],n=getRootTasteFile({target:this.target});if(K(n)){const e=parseTasteBuckets({content:await A.readFile(n,"utf-8"),sourcePath:n});t.push(...e)}const r=await A.readdir(e,{withFileTypes:!0});for(const e of r)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(K(n)){const r=parseTasteBuckets({content:await A.readFile(n,"utf-8"),sourcePath:n});for(const t of r)t.category=e.name;t.push(...r)}}return t}async getBucket(e){const{category:t}=e;return(await this.getAllBuckets()).find(e=>e.category===t)||null}async writeBucket(e){const{bucket:t}=e,n=getTastePath({target:this.target});await A.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:this.target}),o=t.learnings.length,a=await this.removeBucket({category:t.category});o<=5?await this.writeToRoot({bucket:t,rootFile:r,categoryPosition:a}):await this.writeToSubdirectory({bucket:t,rootFile:r,categoryPosition:a})}async removeBucket(e){const{category:t}=e,n=getRootTasteFile({target:this.target});let r=null;if(K(n)){const e=(await A.readFile(n,"utf-8")).split("\n");let o=-1,a=-1;const s=new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i");for(let t=0;t<e.length;t++)if(s.test(e[t])){o=t;for(let n=t+1;n<e.length;n++)if(e[n].startsWith("# ")){let r=n-1;for(;r>t&&""===e[r].trim();)r--;a=r;break}-1===a&&(a=e.length-1);break}if(-1!==o){const t=e.slice(0,o),s=a<e.length-1?e.slice(a+1):[];r={before:t.join("\n").trim(),after:s.join("\n").trim()};const i=[...t,...s].join("\n").trim();""===i?await A.rm(n,{force:!0}):await A.writeFile(n,i+"\n","utf-8")}}const o=getCategoryTasteFile({target:this.target,category:t}),a=f.dirname(o);return K(a)&&await A.rm(a,{recursive:!0,force:!0}),r}async writeToRoot(e){const{bucket:t,rootFile:n,categoryPosition:r}=e,o=formatBucket({bucket:t});if(r){let e=r.before;e&&!e.trim().startsWith(mt)&&(e=mt+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o.trim(),r.after&&(e+="\n\n"+r.after),await A.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";K(n)&&(e=await A.readFile(n,"utf-8")),e?e.trim().startsWith(mt)||(e=mt+"\n\n"+e):e=mt+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o,await A.writeFile(n,e.trim()+"\n","utf-8")}}async writeToSubdirectory(e){const{bucket:t,rootFile:n,categoryPosition:r}=e,o=getCategoryTasteFile({target:this.target,category:t.category}),a=f.dirname(o);await A.mkdir(a,{recursive:!0});const s=formatBucket({bucket:t});await A.writeFile(o,s,"utf-8");const i=`# ${t.category}\nSee [${t.category}/taste.md](${t.category}/taste.md)\n`;if(r){let e=r.before;e&&!e.trim().startsWith(mt)&&(e=mt+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i.trim(),r.after&&(e+="\n\n"+r.after),await A.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";K(n)&&(e=await A.readFile(n,"utf-8")),e?e.trim().startsWith(mt)||(e=mt+"\n\n"+e):e=mt+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i,await A.writeFile(n,e.trim()+"\n","utf-8")}}exists(){const e=getTastePath({target:this.target});return K(e)}},pt=class{static{__name(this,"LocalGlobalStorage")}target="local-global";async getAllBuckets(){const e=getTastePath({target:this.target});if(!K(e))return[];const t=[],n=await A.readdir(e,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(K(n)){const r=parseTasteBuckets({content:await A.readFile(n,"utf-8"),sourcePath:n});for(const t of r)t.category=e.name;t.push(...r)}}return t}async getBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t});return K(n)&&parseTasteBuckets({content:await A.readFile(n,"utf-8"),sourcePath:n})[0]||null}async writeBucket(e){const{bucket:t}=e,n=getTastePath({target:this.target});await A.mkdir(n,{recursive:!0});const r=getCategoryTasteFile({target:this.target,category:t.category}),o=f.dirname(r);await A.mkdir(o,{recursive:!0});const a=formatBucket({bucket:t});await A.writeFile(r,a,"utf-8")}async deleteBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t}),r=f.dirname(n);K(r)&&await A.rm(r,{recursive:!0,force:!0})}async listBuckets(){const e=await this.getAllBuckets(),t=[];for(const n of e){let e;try{e=(await A.stat(n.sourcePath)).mtime}catch{e=new Date}t.push({category:n.category,learningCount:n.learnings.length,lastUpdated:e,filePath:n.sourcePath})}return t}exists(){const e=getTastePath({target:this.target});return K(e)}};async function prepareUploadFormData(e){const{packageName:t,bucket:n,description:r,type:o="category"}=e,a=new FormData;if(a.append("name",t),r&&a.append("description",r),a.append("type",o),"category"===o){const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});a.append("files[taste.md]",r)}else{const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});a.append("files[taste.md]",r);const o=getTastePath({target:"local-project"}),s=f.join(o,n.category);if(K(s)){const e=getCategoryTasteFile({target:"local-project",category:n.category});if(K(e)){const t=await A.readFile(e,"utf-8"),r=new Blob([t],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});a.append(`files[${n.category}/taste.md]`,o)}}}return a}async function prepareMultiplePackagesUpload(e){const{buckets:t,projectName:n,description:r}=e,o=new FormData;o.append("name",n),r&&o.append("description",r),o.append("type","project");const a=getRootTasteFile({target:"local-project"});if(K(a)){const e=await A.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});o.append("files[taste.md]",n)}for(const e of t){const t=getCategoryTasteFile({target:"local-project",category:e.category});if(K(t)){const n=await A.readFile(t,"utf-8"),r=new Blob([n],{type:"text/markdown"}),a=new File([r],"taste.md",{type:"text/markdown"});o.append(`files[${e.category}/taste.md]`,a)}}return o}function parseTasteContent(e){const t=[],n=e.split("\n");for(const e of n){const n=e.trim();if(!n||n.startsWith("#")||!n.startsWith("-"))continue;const r=n.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(r){const e=r[1].trim(),n=parseFloat(r[2]);e&&!isNaN(n)&&t.push({text:e,confidence:n})}}return t}__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),__name(parseTasteContent,"parseTasteContent");var ht=class{static{__name(this,"RemoteStorage")}async getAllBuckets(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");const t=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let e="Failed to list taste packages";try{const t=await n.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const a=[];for(const e of o)try{const t=await this.getBucket({category:e.name});t&&a.push(t)}catch(t){console.warn(`Warning: Failed to download package '${e.name}': ${t instanceof Error?t.message:String(t)}`)}return a}async downloadPackage(e){const{namespace:t,packageName:n}=e,r=await getAuthKey();if(!r)throw new Error("No API key found. Please authenticate with: cmd login");const o=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",t).replace(":packageName",n)}`,a=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!a.ok){if(404===a.status)return null;let e="Failed to download taste package";try{const t=await a.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:s}=await a.json();return{type:s.type||"category",files:s.files||[]}}async getBucket(e){const{category:t}=e;if(!await getAuthKey())throw new Error("No API key found. Please authenticate with: cmd login");const n=await getAuthenticatedEntity();if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");const r=n.user.userName;return this.downloadPackageToBucket({namespace:r,packageName:t})}async downloadPackageToBucket(e){const{namespace:t,packageName:n}=e,r=await this.downloadPackage({namespace:t,packageName:n});if(!r)return null;const o=r.files||[];if(0===o.length)return null;const a=o.find(e=>"taste.md"===e.file);if(!a)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`}}async writeBucket(e){const{bucket:t,namespace:n}=e,r=await getAuthKey();if(!r)throw new Error("No API key found. Please authenticate with: cmd login");const o=await prepareUploadFormData({packageName:t.category,bucket:t,type:"category"}),a=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,s=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:o});if(!s.ok){let e="Failed to upload taste package";try{const t=await s.json();console.log("Error data from API:",t),e=t.error?.message||t.message||e}catch{}throw new Error(e)}await s.json()}async writeBuckets(e){const{buckets:t,projectName:n,namespace:r}=e,o=await getAuthKey();if(!o)throw new Error("No API key found. Please authenticate with: cmd login");const a=await prepareMultiplePackagesUpload({buckets:t,projectName:n}),s=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:a});if(!i.ok){let e="Failed to upload taste packages";try{const t=await i.json();console.log("Error data from API:",t),e=t.error?.message||t.message||e}catch{}throw new Error(e)}await i.json()}async deleteBucket(e){throw new Error("Remote storage not yet implemented")}async listBuckets(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");const t=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let e="Failed to list taste packages";try{const t=await n.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:r}=await n.json();return(r.packages||[]).map(e=>({category:e.name,learningCount:e.learningCount||0,lastUpdated:e.createdAt?new Date(e.createdAt):new Date,filePath:""}))}async importBucket(e){throw new Error("Remote storage not yet implemented")}};function mergeLearnings(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},o=new Map;for(const e of n)o.set(e.text,e);const a=new Map(o);for(const e of t){const t=o.get(e.text);t?e.confidence>t.confidence?(a.set(e.text,e),r.updated++):(e.confidence,t.confidence,r.unchanged++):(a.set(e.text,e),r.added++)}for(const e of n)t.some(t=>t.text===e.text)||r.unchanged++;return{merged:Array.from(a.values()),details:r}}__name(mergeLearnings,"mergeLearnings");var ft=/confidence:/i;function validateTasteFile(e){const{content:t,filePath:n}=e,r=[];if(!t.trim())return r.push({severity:"error",message:"File is empty",suggestion:"Add at least one category with learnings"}),buildResult({issues:r,filePath:n});const o=t.split("\n");let a=null,s=null,i=0;for(let e=0;e<o.length;e++){const t=o[e],n=e+1;if(!t.trim())continue;if(t.trim().startsWith("# ")){if("# Taste (Continuously Learned by CommandCode)"===t.trim())continue;a&&0===i&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:s-1})||r.push({line:s,severity:"warning",message:`Category '${a}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),a=t.trim().substring(2).trim(),s=n,i=0;continue}if(t.trim().startsWith("-")){if(!a){r.push({line:n,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'});continue}i++;const e=validateLearningLine({line:t.trim(),lineNum:n});r.push(...e);continue}const c=t.trim();/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i.test(c)||r.push({line:n,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"})}return a&&0===i&&s&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:s-1})||r.push({line:s,severity:"warning",message:`Category '${a}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),buildResult({issues:r,filePath:n})}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=n+3;for(let e=n+1;e<t.length&&e<r;e++){const n=t[e];if(n.trim().startsWith("# "))break;if(n.includes("See [")&&n.includes("taste.md"))return!0}return!1}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!ft.test(o))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const a=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),s=a.length>0?a[a.length-1]:null;if(!s)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const i=s[1],c=parseFloat(i);if(isNaN(c))return r.push({line:n,severity:"error",message:`Confidence value "${i}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;c<0||c>1?r.push({line:n,severity:"error",message:`Confidence value ${c} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}):0===c&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});let l="";return l=s&&void 0!==s.index?o.substring(0,s.index).trim():o.trim(),l&&0!==l.length?l.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}):r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),o=t.filter(e=>"warning"===e.severity),a=0===r.length;let s;if(0===t.length)s=`✓ ${n} is valid`;else{const e=[];r.length>0&&e.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&e.push(`${o.length} warning${o.length>1?"s":""}`),s=`${r.length>0?"✗":"⚠"} ${n} has ${e.join(", ")}`}return{valid:a,issues:t,summary:s}}function formatValidationIssues(e){const{result:t,verbose:n=!0}=e;if(0===t.issues.length){const e=t.summary.charAt(0),n=t.summary.substring(2);return`${te.green(e)} ${te.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity),a=[r.length>0?te.red(t.summary):te.yellow(t.summary),""];if(r.length>0){a.push(te.bold(te.red("Errors:")));for(const e of r){const t=e.line?te.dim(` Line ${e.line}: `):" ";a.push(`${t}${te.red(e.message)}`),e.suggestion&&a.push(te.dim(` → ${e.suggestion}`))}a.push("")}if(o.length>0){a.push(te.bold(te.yellow("Warnings:")));for(const e of o){const t=e.line?te.dim(` Line ${e.line}: `):" ";a.push(`${t}${te.yellow(e.message)}`),e.suggestion&&a.push(te.dim(` → ${e.suggestion}`))}a.push("")}return a.join("\n").trim()}async function promptMergeStrategy(e){const{packageName:t,namespace:n,localBucket:r,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${r.learnings.length} learnings`),console.log(`Remote: ${a} learnings (from ${n})\n`);const i=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${r.learnings.length} → ${a} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});return s.isCancel(i)&&(s.cancel("Operation cancelled"),process.exit(0)),i}async function promptPushStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteBucket:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${a.learnings.length} learnings (in ${n})\n`);const i=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${a.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"}],initialValue:"merge"});return s.isCancel(i)&&(s.cancel("Operation cancelled"),process.exit(0)),i}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalBucket:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in global storage\n`)),console.log(`Local: ${n} learnings`),console.log(`Global: ${r.learnings.length} learnings\n`);const a=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${r.learnings.length} → ${n} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});return s.isCancel(a)&&(s.cancel("Operation cancelled"),process.exit(0)),a}async function promptGlobalPullStrategy(e){const{packageName:t,localBucket:n,globalLearningsCount:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${n.learnings.length} learnings`),console.log(`Global: ${r} learnings\n`);const a=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${n.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});return s.isCancel(a)&&(s.cancel("Operation cancelled"),process.exit(0)),a}async function push(e){const{buckets:t,target:n,overwrite:r=!1}=e,o=new gt,a={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!o.exists())return a.success=!1,a.errors.push({bucket:"all",error:"No taste directory found in project"}),a;const s=await o.getAllBuckets();if(0===s.length)return a.success=!1,a.errors.push({bucket:"all",error:"No taste packages found in project"}),a;for(const e of s){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){a.success=!1;const n=formatValidationIssues({result:t,verbose:!0});a.errors.push({bucket:e.category,error:`Validation failed for taste package in project:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in project has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(a.errors.length>0)return a;const i=t.length>0?s.filter(e=>t.includes(e.category)):s;if(t.length>0&&0===i.length){a.success=!1;for(const e of t)a.errors.push({bucket:e,error:"Taste package not found in project"});return a}let c,l;if("remote-project"===n||"remote-user"===n)try{const e=await getAuthenticatedEntity();e.success&&e.user?.userName&&(c=e.user.userName)}catch{}if("remote-project"===n&&0===t.length){const e=f.basename(process.cwd()),t=new ht;if(!c)return a.success=!1,a.errors.push({bucket:"all",error:"Failed to get user namespace for remote push"}),a;try{await t.writeBuckets({buckets:i,projectName:e,namespace:c,type:"project"}),a.bucketsPushed=i.map(e=>e.category);for(const e of i)a.filePaths[e.category]=`${c}/${e.category}`;return a}catch(e){return a.success=!1,a.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),a}}switch(n){case"local-global":l=new pt;break;case"remote-project":case"remote-user":l=new ht;break;default:return a.success=!1,a.errors.push({bucket:"all",error:`Invalid target: ${n}`}),a}for(const e of i)try{const t=await l.getBucket({category:e.category});let o;if(o=r?"overwrite":t&&"local-global"===n?await promptGlobalPushStrategy({packageName:e.category,localLearningsCount:e.learnings.length,globalBucket:t}):"merge","skip"===o)continue;if("overwrite"===o){if("local-global"===n)await l.writeBucket({bucket:e});else{if(!c)throw new Error("Failed to get user namespace for remote push");await l.writeBucket({bucket:e,namespace:c})}a.bucketsPushed.push(e.category),a.overwritten.push(e.category)}else{let r;if(t){const n=mergeLearnings({source:e.learnings,target:t.learnings});r={...e,learnings:n.merged},a.mergeDetails[e.category]=n.details}else r=e,a.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if("local-global"===n)await l.writeBucket({bucket:r});else{if(!c)throw new Error("Failed to get user namespace for remote push");await l.writeBucket({bucket:r,namespace:c})}a.bucketsPushed.push(e.category)}if("local-global"===n){const t=getCategoryTasteFile({target:"local-global",category:e.category});a.filePaths[e.category]=t}else"remote-project"!==n&&"remote-user"!==n||!c||(a.filePaths[e.category]=`${c}/${e.category}`)}catch(t){a.success=!1,a.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return a}async function pull(e){const{buckets:t,source:n,overwrite:r=!1}=e,o=new gt,a={success:!0,bucketsPulled:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},s=__name(()=>{switch(n){case"local-global":return"global";case"remote-project":return"remote project";case"remote-user":return"remote";default:return"source"}},"getSourceName")();let i,c;switch(n){case"local-global":i=new pt;break;case"remote-project":case"remote-user":i=new ht;break;default:return a.success=!1,a.errors.push({bucket:"all",error:`Invalid source: ${n}`}),a}try{c=await i.getAllBuckets()}catch(e){return a.success=!1,a.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),a}if(0===c.length)return a.success=!1,a.errors.push({bucket:"all",error:`No taste packages found in ${s}`}),a;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){a.success=!1;const n=formatValidationIssues({result:t,verbose:!0});a.errors.push({bucket:e.category,error:`Validation failed for taste package in ${s}:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in ${s} has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(a.errors.length>0)return a;const l=t.length>0?c.filter(e=>t.includes(e.category)):c;if(t.length>0&&0===l.length){a.success=!1;for(const e of t)a.errors.push({bucket:e,error:`Taste package not found in ${s}`});return a}for(const e of l)try{const t=await o.getBucket({category:e.category});let s;if(s=r?"overwrite":t&&"local-global"===n?await promptGlobalPullStrategy({packageName:e.category,localBucket:t,globalLearningsCount:e.learnings.length}):"merge","skip"===s)continue;if("overwrite"===s)await o.writeBucket({bucket:e}),a.bucketsPulled.push(e.category),a.overwritten.push(e.category);else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},a.mergeDetails[e.category]=r.details}else n=e,a.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),a.bucketsPulled.push(e.category)}const i=getCategoryTasteFile({target:"local-project",category:e.category});a.filePaths[e.category]=i}catch(t){a.success=!1,a.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return a}async function pullRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new gt,a=new ht,s={success:!0,bucketsPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};try{const e=await a.downloadPackage({namespace:t,packageName:n});if(!e)return s.success=!1,s.errors.push({bucket:n,error:"Taste package not found in remote"}),s;const{type:i,files:c}=e;for(const e of c){const t=validateTasteFile({content:e.content,filePath:e.file});if(!t.valid){s.success=!1;const r=formatValidationIssues({result:t,verbose:!0});s.errors.push({bucket:n,error:`Validation failed for ${e.file}:\n${r}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(s.errors.length>0)return s;"project"===i?await pullProjectPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:s}):await pullCategoryPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:s})}catch(e){s.success=!1,s.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return s}async function pullProjectPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:a,result:s}=e,i=t.find(e=>"taste.md"===e.file);if(i){const e=parseTasteBuckets({content:i.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processBucket({bucket:t,namespace:r,overwrite:o,targetStorage:a,result:s})}for(const e of t){if("taste.md"===e.file)continue;const t=e.file.replace("/taste.md",""),i={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processBucket({bucket:i,namespace:r,overwrite:o,targetStorage:a,result:s})}}async function processBucket(e){const{bucket:t,namespace:n,overwrite:r,targetStorage:o,result:a}=e;try{const e=await o.getBucket({category:t.category});let s;if(s=r?"overwrite":e?await promptMergeStrategy({packageName:t.category,namespace:n,localBucket:e,remoteLearningsCount:t.learnings.length}):"merge","skip"===s)return void a.skipped.push(t.category);if("overwrite"===s)await o.writeBucket({bucket:t}),a.bucketsPulled.push(t.category),a.overwritten.push(t.category);else{let n;if(e){const r=mergeLearnings({source:t.learnings,target:e.learnings});n={...t,learnings:r.merged},a.mergeDetails[t.category]=r.details}else n=t,a.mergeDetails[t.category]={added:t.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),a.bucketsPulled.push(t.category)}const i=getCategoryTasteFile({target:"local-project",category:t.category});a.filePaths[t.category]=i}catch(e){a.success=!1,a.errors.push({bucket:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullCategoryPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:a,result:s}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return s.success=!1,void s.errors.push({bucket:n,error:"No taste.md file found in category package"});const c={category:n,learnings:parseTasteContent(i.content),sourcePath:`remote:${n}`};await processBucket({bucket:c,namespace:r,overwrite:o,targetStorage:a,result:s})}async function pushRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new gt,a=new ht,s={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!o.exists())return s.success=!1,s.errors.push({bucket:n,error:"No taste directory found in project"}),s;try{const e=await o.getBucket({category:n});if(!e)return s.success=!1,s.errors.push({bucket:n,error:`Taste package '${n}' not found in local project`}),s;const i=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!i.valid){s.success=!1;const e=formatValidationIssues({result:i,verbose:!0});return s.errors.push({bucket:n,error:`Validation failed:\n${e}`}),s}if(i.issues.filter(e=>"warning"===e.severity).length>0){console.warn(`\nWarning: Taste package '${n}' has validation warnings:\n`);const e=formatValidationIssues({result:i,verbose:!0});console.warn(e+"\n")}const c=await a.downloadPackageToBucket({namespace:t,packageName:n});let l;if(l=r?"overwrite":c?await promptPushStrategy({packageName:n,namespace:t,localLearningsCount:e.learnings.length,remoteBucket:c}):"merge","skip"===l)return s;if("overwrite"===l)await a.writeBucket({bucket:e,namespace:t}),s.bucketsPushed.push(n),s.overwritten.push(n);else{let r;if(c){const t=mergeLearnings({source:e.learnings,target:c.learnings});r={...e,learnings:t.merged},s.mergeDetails[n]=t.details}else r=e,s.mergeDetails[n]={added:e.learnings.length,updated:0,unchanged:0};await a.writeBucket({bucket:r,namespace:t}),s.bucketsPushed.push(n)}s.filePaths[n]=`${t}/${n}`}catch(e){s.success=!1,s.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return s}async function list(e){const{location:t}=e;let n;switch(t){case"local-project":n=new gt;break;case"local-global":n=new pt;break;case"remote-project":case"remote-user":n=new ht;break;default:throw new Error(`Invalid location: ${t}`)}return n instanceof pt||n instanceof ht?await n.listBuckets():(await n.getAllBuckets()).map(e=>({category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}))}async function deleteBuckets(e){const{buckets:t,location:n}=e,r={success:!0,bucketsDeleted:[],errors:[]};let o;switch(n){case"local-global":o=new pt;break;case"remote-project":case"remote-user":o=new ht;break;case"local-project":return r.success=!1,r.errors.push({bucket:"all",error:"Cannot delete from local project via sync. Use taste clear instead."}),r;default:return r.success=!1,r.errors.push({bucket:"all",error:`Invalid location: ${n}`}),r}if(0===t.length)return r.success=!1,r.errors.push({bucket:"all",error:"No taste packages specified for deletion"}),r;for(const e of t)try{await o.deleteBucket({category:e}),r.bucketsDeleted.push(e)}catch(t){r.success=!1,r.errors.push({bucket:e,error:t instanceof Error?t.message:String(t)})}return r}async function lint(e){const{packages:t,target:n}=e,r={success:!0,filesLinted:[],errors:[],totalErrors:0,totalWarnings:0},o=getTastePath({target:n});if(!K(o))return r.success=!1,r.errors.push({file:"all",error:"No taste directory found in "+("local-global"===n?"global":"project")}),r;const a=[];if(t.length>0)for(const e of t){const t=getCategoryTasteFile({target:n,category:e});K(t)?a.push({path:t,displayName:`${e}/taste.md`}):(r.success=!1,r.errors.push({file:e,error:`Taste package '${e}' not found in ${"local-global"===n?"global":"project"}`}))}else{const e=getRootTasteFile({target:n});K(e)&&a.push({path:e,displayName:"taste.md"});const t=await A.readdir(o,{withFileTypes:!0});for(const e of t)if(e.isDirectory()){const t=getCategoryTasteFile({target:n,category:e.name});K(t)&&a.push({path:t,displayName:`${e.name}/taste.md`})}}if(0===a.length&&r.errors.length>0)return r;if(0===a.length)return r.success=!1,r.errors.push({file:"all",error:"No taste files found in "+("local-global"===n?"global":"project")}),r;for(const e of a){const t=validateTasteFile({content:await A.readFile(e.path,"utf-8"),filePath:e.displayName}),n=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);r.totalErrors+=n.length,r.totalWarnings+=o.length,t.valid||(r.success=!1);const a=formatValidationIssues({result:t});r.filesLinted.push({file:e.displayName,valid:t.valid,errors:n.length,warnings:o.length,formatted:a})}return r}async function open3(e){const{package:t,target:n}=e;try{let e;switch(n){case"local-project":e=new gt;break;case"local-global":e=new pt;break;case"remote-project":case"remote-user":e=new ht;break;default:throw new Error(`Invalid target: ${n}`)}const r=(await e.getAllBuckets()).find(e=>e.category===t);if(!r)return{success:!1,error:`Taste package '${t}' not found in ${"local-global"===n?"global":"project"}`};const o=r.sourcePath,a=await findCategoryLineNumber({filePath:o,category:t});return await ne([{file:o,line:a}]),{success:!0,filePath:o,lineNumber:a}}catch(e){return e instanceof Error&&e.message.includes("$EDITOR environment variable")?{success:!1,error:getEditorSetupInstructions()}:{success:!1,error:e instanceof Error?e.message:String(e)}}}async function findCategoryLineNumber(e){const{filePath:t,category:n}=e;try{const e=await A.readFile(t,"utf-8");if("taste.md"===f.basename(t)&&f.basename(f.dirname(t))===n)return 1;const r=e.split("\n");for(let e=0;e<r.length;e++)if(r[e].trim().toLowerCase()===`# ${n.toLowerCase()}`)return e+1;return 1}catch{return 1}}function getEditorSetupInstructions(){const e=re.platform;if("win32"===e)return'Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n\nCommand Prompt (as Administrator):\n setx EDITOR "code" # VS Code\n setx EDITOR "notepad" # Notepad\n setx EDITOR "vim" # Vim (if installed via WSL/Git Bash)\n\nPowerShell:\n [Environment]::SetEnvironmentVariable("EDITOR", "code", "User")\n\nThen restart your terminal.';const t="darwin"===e?"~/.zshrc":"~/.bashrc";return`Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n echo 'export EDITOR="code"' >> ${t} # VS Code\n echo 'export EDITOR="vim"' >> ${t} # Vim\n echo 'export EDITOR="nano"' >> ${t} # Nano\n echo 'export EDITOR="subl"' >> ${t} # Sublime Text\n\nFor bash users ${"darwin"===e?"(or ~/.bash_profile for bash)":"(or ~/.zshrc for zsh)"}, replace ${t} with the appropriate file.\n\nThen restart your terminal or run: source ${t}`}async function runMigrations(){await removeMetadataFile()}async function removeMetadataFile(){const e=f.join(T.homedir(),".commandcode","taste",".metadata.json");if(K(e))try{await A.unlink(e)}catch{}}__name(validateTasteFile,"validateTasteFile"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(validateLearningLine,"validateLearningLine"),__name(buildResult,"buildResult"),__name(formatValidationIssues,"formatValidationIssues"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptPushStrategy,"promptPushStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(push,"push"),__name(pull,"pull"),__name(pullRemote,"pullRemote"),__name(pullProjectPackage,"pullProjectPackage"),__name(processBucket,"processBucket"),__name(pullCategoryPackage,"pullCategoryPackage"),__name(pushRemote,"pushRemote"),__name(list,"list"),__name(deleteBuckets,"deleteBuckets"),__name(lint,"lint"),__name(open3,"open"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(runMigrations,"runMigrations"),__name(removeMetadataFile,"removeMetadataFile");var yt=class{static{__name(this,"TasteSyncManager")}constructor(){runMigrations().catch(()=>{})}async push(e){return await push(e)}async pull(e){return await pull(e)}async pullRemote(e){return await pullRemote(e)}async pushRemote(e){return await pushRemote(e)}async list(e){return await list(e)}async delete(e){return await deleteBuckets(e)}async lint(e){return await lint(e)}async open(e){return await open3(e)}};async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new dt({baseUrl:e}),n=await t.get({endpoint:De.ALPHA.NAMESPACES});if(!n.success)throw new Error("Failed to fetch namespaces");if("org"===n.type)return{userName:n.org.login,orgs:[]};const r=n.orgs.map(e=>({id:e.id,login:e.login,name:e.name}));return{userName:n.user.userName,orgs:r}}async function promptNamespaceSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const r=[{value:t,label:t,hint:"Personal"},...n.map(e=>({value:e.login,label:e.name||e.login,hint:"Organization"}))],o=await s.select({message:"Select namespace to push to\n",options:r,initialValue:t});return s.isCancel(o)&&(s.cancel("Operation cancelled"),process.exit(0)),o}function createTasteCommand(){const n=new e("taste");n.description("Manage taste learning packages");const r=new yt;return n.command("push").argument("[package]","Package name (optional if using --all)").option("-g, --global","Push to global storage").option("--remote","Push to remote (default)").option("--all","Push all packages").option("--overwrite","Overwrite target without prompting (default: interactive merge)").addOption(new t("--dev","Push to dev environment").hideHelp()).addOption(new t("--staging","Push to staging environment").hideHelp()).description("Push packages from project to remote or global storage (prompts on conflicts)").action(async(e,t)=>{try{let n;if(t.global||t.remote||(t.remote=!0),t.global&&t.remote&&(console.error(te.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste push <package> (pushes to remote by default)")),console.error(te.gray(" cmd taste push --all")),console.error(te.gray(" cmd taste push <package> -g (for global)")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1)),t.remote){let o,a;if(e&&e.includes("/")){const[t,n]=e.split("/");t&&n||(console.error(te.red("Error: Invalid namespace/package format")),console.error(te.gray("Usage: cmd taste push --remote username/packageName")),console.error(te.gray(" cmd taste push --remote org-name/packageName")),process.exit(1)),o=t,a=n}else{e||(console.error(te.red("Error: Please specify a package name")),console.error(te.gray("Usage: cmd taste push <namespace>/<package>")),console.error(te.gray(" or: cmd taste push <package> (interactive namespace selection)")),process.exit(1)),a=e;let t;(await r.list({location:"local-project"})).some(e=>e.category===a)||(console.error(te.red(`Error: Taste package '${a}' not found in local project`)),process.exit(1));try{t=await fetchUserNamespaces()}catch(e){throw e}o=t.orgs.length>0?await promptNamespaceSelection(t):t.userName}n=await r.pushRemote({namespace:o,packageName:a,overwrite:t.overwrite})}else{const o="local-global",a=t.all?[]:[e];n=await r.push({buckets:a,target:o,overwrite:t.overwrite})}if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}let o=!1;if(1===n.bucketsPushed.length){const e=n.bucketsPushed[0],r=n.filePaths?.[e];if(t.overwrite)t.remote&&r?console.log(te.green(`✓ Replaced '${e}' taste package in ${r}`)):(console.log(te.green(`✓ Replaced '${e}' taste package in global`)),r&&console.log(te.gray(` Path: ${r}`)));else if(n.mergeDetails?.[e]){const a=n.mergeDetails[e],s=[];a.added>0&&s.push(`${a.added} ${1===a.added?"learning":"learnings"} added`),a.updated>0&&s.push(`${a.updated} ${1===a.updated?"learning":"learnings"} updated`),a.unchanged>0&&s.push(`${a.unchanged} ${1===a.unchanged?"learning":"learnings"} unchanged`),t.remote&&r?console.log(te.green(`✓ Pushed '${e}' taste package to ${r} (${s.join(", ")})`)):(console.log(te.green(`✓ Pushed '${e}' taste package to global (${s.join(", ")})`)),r&&console.log(te.gray(` Path: ${r}`))),(a.added>0||a.updated>0)&&a.unchanged>0&&(o=!0)}else t.remote&&r?console.log(te.green(`✓ Pushed '${e}' taste package to ${r}`)):(console.log(te.green(`✓ Pushed '${e}' taste package to global`)),r&&console.log(te.gray(` Path: ${r}`)))}else if(n.bucketsPushed.length>0){const e=t.remote?"remote":"global";if(console.log(te.green(`✓ Pushed ${n.bucketsPushed.length} taste packages (${n.bucketsPushed.join(", ")}) to ${e}`)),!t.overwrite&&n.mergeDetails)for(const e of Object.values(n.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){o=!0;break}}o&&console.log(te.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("pull").argument("[package]","Package name (optional if using --all)").option("-g, --global","Pull from global").option("--remote","Pull from remote").option("--all","Pull all packages").option("--overwrite","Overwrite local without prompting (default: interactive merge)").addOption(new t("--dev","Use dev environment").hideHelp()).addOption(new t("--staging","Use staging environment").hideHelp()).description("Pull packages from storage to project (prompts on conflicts)").action(async(e,t)=>{try{let n,o;if(t.global||t.remote||(t.remote=!0),t.global&&t.remote&&(console.error(te.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),t.remote&&t.all&&(console.error(te.red("Error: The --all flag is not supported for remote pull")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),t.remote&&!e&&(console.error(te.red("Error: Please provide both namespace and package name")),process.exit(1)),t.remote&&e&&!e.includes("/")&&(console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package> (remote by default)")),console.error(te.gray(" cmd taste pull <package> -g (from global)")),console.error(te.gray(" cmd taste pull --all -g (all from global)")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1)),t.remote){e.includes("/")||(console.error(te.red("Error: Package name must include namespace")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1));const[a,s]=e.split("/");a&&s||(console.error(te.red("Error: Invalid namespace/package format")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),o=a,n=await r.pullRemote({namespace:o,packageName:s,overwrite:t.overwrite})}else{const o="local-global",a=t.all?[]:[e];n=await r.pull({buckets:a,source:o,overwrite:t.overwrite})}const a=t.remote?o?`${o}`:"remote":"global";if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}if(n.skipped&&n.skipped.length>0)for(const e of n.skipped)console.log(te.yellow(`⊘ Skipped '${e}' - kept local version`));let s=!1;if(1===n.bucketsPulled.length){const e=n.bucketsPulled[0],r=n.filePaths?.[e];if(t.overwrite)console.log(te.green(`✓ Replaced '${e}' taste package in project`)),r&&console.log(te.gray(` Saved to: ${r}`));else if(n.mergeDetails?.[e]){const t=n.mergeDetails[e],o=[];t.added>0&&o.push(`${t.added} ${1===t.added?"learning":"learnings"} added`),t.updated>0&&o.push(`${t.updated} ${1===t.updated?"learning":"learnings"} updated`),t.unchanged>0&&o.push(`${t.unchanged} ${1===t.unchanged?"learning":"learnings"} unchanged`),console.log(te.green(`✓ Pulled '${e}' taste package from ${a} (${o.join(", ")})`)),r&&console.log(te.gray(` Saved to: ${r}`)),(t.added>0||t.updated>0)&&t.unchanged>0&&(s=!0)}else console.log(te.green(`✓ Pulled '${e}' taste package from ${a}`)),r&&console.log(te.gray(` Saved to: ${r}`))}else if(n.bucketsPulled.length>0){const e=` (${n.bucketsPulled.join(", ")})`;if(console.log(te.green(`✓ Pulled ${n.bucketsPulled.length} taste packages${e} from ${a}`)),!t.overwrite&&n.mergeDetails)for(const e of Object.values(n.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){s=!0;break}}s&&console.log(te.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("list").option("-g, --global","List global packages").option("--remote","List remote packages").addOption(new t("--dev","Use dev environment").hideHelp()).addOption(new t("--staging","Use staging environment").hideHelp()).description("List available packages").action(async e=>{try{let t,n;e.global&&e.remote&&(console.error(te.red("Error: Cannot specify both --global and --remote flags")),process.exit(1)),e.remote?(t="remote-project",n="remote"):e.global?(t="local-global",n="global"):(t="local-project",n="project");const o=await r.list({location:t});if(0===o.length)return void console.log(te.yellow(`No taste packages found in ${n}`));console.log(te.bold(`\n${n.charAt(0).toUpperCase()+n.slice(1)} Taste Packages:\n`));let a=0;for(const e of o){a+=e.learningCount;const t=getTimeAgo(e.lastUpdated);console.log(`${te.cyan(e.category)} (${e.learningCount} learnings, updated ${t})`)}console.log(te.gray(`\nTotal: ${o.length} taste packages, ${a} learnings\n`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("delete").argument("<package>","Package name to delete").option("-g, --global","Delete from global").description("Delete a package").action(async(e,t)=>{try{t.global||(console.error(te.red("Error: Currently only global is supported. Use -g flag.")),process.exit(1));const n=await r.delete({buckets:[e],location:"local-global"});if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}console.log(te.green(`✓ Deleted '${e}' taste package from global`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("lint").argument("[package]","Package name (required unless using --all)").option("-g, --global","Lint global taste files").option("--all","Lint all packages").description("Validate taste file format and structure").action(async(e,t)=>{try{e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste lint <package>")),console.error(te.gray(" cmd taste lint --all")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1));const n=await r.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(te.red(`Error: ${e.error}`));process.exit(1)}for(const e of n.filesLinted)console.log(e.formatted);if(n.filesLinted.length>1)if(console.log(""),0===n.totalErrors&&0===n.totalWarnings)console.log(te.green(`✓ All ${n.filesLinted.length} taste files are valid`));else{const e=[];n.totalErrors>0&&e.push(te.red(`${n.totalErrors} error${n.totalErrors>1?"s":""}`)),n.totalWarnings>0&&e.push(te.yellow(`${n.totalWarnings} warning${n.totalWarnings>1?"s":""}`)),console.log(`Summary: ${e.join(", ")} across ${n.filesLinted.length} files`)}n.success||process.exit(1)}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("open").argument("<package>","Package name to open").option("-g, --global","Open from global").description("Open a package in your editor").action(async(e,t)=>{try{const n=t.global?"local-global":"local-project",o=await r.open({package:e,target:n});o.success||(console.error(te.red(o.error)),process.exit(1)),console.log(te.green(`✓ Opened '${e}' taste package from ${t.global?"global":"project"}`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n}function getTimeAgo(e){const t=(new Date).getTime()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),o=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${o} day${o>1?"s":""} ago`}function getPackageJson(){const e=import.meta.url,t=ae(e),n=w(t);return JSON.parse(Y(E(n,"./../package.json"),"utf8"))}__name(fetchUserNamespaces,"fetchUserNamespaces"),__name(promptNamespaceSelection,"promptNamespaceSelection"),__name(createTasteCommand,"createTasteCommand"),__name(getTimeAgo,"getTimeAgo"),__name(getPackageJson,"getPackageJson");var wt=getPackageJson(),Et=y.join(k.homedir(),".commandcode"),bt=y.join(Et,"update-status.json"),vt=y.join(Et,"update-failed.json");function ensureCommandCodeDir(){J.existsSync(Et)||J.mkdirSync(Et,{recursive:!0})}async function checkForUpdateAvailable(){try{const e=n("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3}),t=JSON.parse(e),r=wt.version,o=r.includes("alpha"),a=t.filter(e=>!e.includes("alpha")),s=t.filter(e=>e.includes("alpha"));let i=r,c=!1;if(a.length>0){const e=a.sort(oe.rcompare)[0];oe.gt(e,r)&&(i=e,c=!0)}if(!c&&o&&s.length>0){const e=s.sort(oe.rcompare)[0];oe.gt(e,r)&&(i=e,c=!0)}return{currentVersion:r,latestVersion:i,updateAvailable:c}}catch(e){return null}}async function performAutoUpdate(e){const{silent:t=!1,updateInfo:r}=e||{},o=r||await checkForUpdateAvailable();if(!o||!o.updateAvailable)return{success:!1};try{n(`npm i -g command-code@${o.latestVersion}`,{stdio:"ignore"}),ensureCommandCodeDir();const e={updatedFrom:o.currentVersion,updatedTo:o.latestVersion,updatedAt:Date.now()};return J.writeFileSync(bt,JSON.stringify(e,null,2)),{success:!0}}catch(e){console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code"),ensureCommandCodeDir();const t={currentVersion:o.currentVersion,latestVersion:o.latestVersion,failedAt:Date.now()};return J.writeFileSync(vt,JSON.stringify(t,null,2)),{success:!1,updateInfo:o}}}function getUpdateStatus(){try{if(ensureCommandCodeDir(),J.existsSync(bt)){const e=JSON.parse(J.readFileSync(bt,"utf-8"));return J.unlinkSync(bt),e}}catch(e){}return null}function getFailedUpdateInfo(){try{if(ensureCommandCodeDir(),J.existsSync(vt)){const e=JSON.parse(J.readFileSync(vt,"utf-8"));return J.unlinkSync(vt),{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 Ct=new e("update").description("Update Command Code to the latest version").option("--check","Check for updates without installing").action(async e=>{if(e.check){console.log(te.dim("Checking for updates..."));const e=await checkForUpdateAvailable();if(!e)return console.log(te.red("✗ Failed to check for updates")),void console.log(te.dim("Please check your internet connection or try again later."));e.updateAvailable?(console.log(te.bold("Update available!")),console.log(te.dim("Current: ")+te.white(e.currentVersion)),console.log(te.dim("Latest: ")+te.bold.green(e.latestVersion)),console.log(te.dim("Run ")+te.cyan("cmd update")+te.dim(" to install."))):console.log(te.green("✓ Already on latest version ")+te.dim(`(${e.currentVersion})`))}else{console.log(te.dim("Checking for updates..."));const e=await checkForUpdateAvailable();if(!e)return console.log(te.red("✗ Failed to check for updates")),void console.log(te.dim("Please check your internet connection or try again later."));if(!e.updateAvailable)return void console.log(te.green("✓ Already on latest version ")+te.dim(`(${e.currentVersion})`));console.log(te.dim("Current: ")+te.white(e.currentVersion)),console.log(te.dim("Latest: ")+te.bold.green(e.latestVersion)),console.log(te.dim(`\nUpdating command-code from ${e.currentVersion} → `)+te.white(e.latestVersion)+te.dim("...")),(await performAutoUpdate({silent:!0,updateInfo:e})).success?(console.log(te.green("\n✓ Successfully updated to ")+te.bold(e.latestVersion)),console.log(te.dim("Run ")+te.cyan("cmd")+te.dim(" to start using the new version."))):(console.log(te.red("✗ Update failed")),console.log(te.dim("Please try updating manually:")),console.log(te.cyan("npm i -g command-code")),process.exit(1))}}),Tt=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:o=process.cwd(),env:a=process.env}=t;return new Promise(t=>{const s=r("/bin/bash",["-c",e],{cwd:o,env:{...a},stdio:["pipe","pipe","pipe"]});let i="",c="",l=null;n>0&&(l=setTimeout(()=>{s.kill("SIGTERM"),t({stdout:i,stderr:c+(c?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),s.stdout?.on("data",e=>{i+=e.toString()}),s.stderr?.on("data",e=>{c+=e.toString()}),s.on("close",n=>{l&&clearTimeout(l),t({stdout:i.trim(),stderr:c.trim(),exitCode:n??0,command:e})}),s.on("error",n=>{l&&clearTimeout(l),t({stdout:i,stderr:c+`\n[Error: ${n.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),kt=__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"),At="read_file",Pt="edit_file",St="write_file",xt="read_directory",$t="read_multiple_files",It="grep",Dt="shell_command",Rt="think",Ft="todo_write",Mt="web_search",jt="web_fetch",Nt=__name(e=>e===Mt,"isWebSearchTool");function toRelativePath(e){const t=global.COMMAND_CODE_CWD||process.cwd(),n=process.env.HOME||process.env.USERPROFILE||"",r=f.relative(t,e);return r.startsWith("..")?n&&e.startsWith(n)?e.replace(n,"~"):e:""===r?f.basename(e):r}function replacePathsInText(e){if(!e||"string"!=typeof e)return e;let t=e;return t=t.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,e=>f.isAbsolute(e)?toRelativePath(e):e),t=t.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),t}__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText");var _t=D.object({id:D.string(),timestamp:D.number(),type:D.literal("image"),source:D.object({type:D.enum(["base64","url"]),media_type:D.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:D.string()})}),Ot=D.object({id:D.string(),timestamp:D.number(),input:D.string(),output:D.string().optional(),metadata:D.record(D.string(),D.any()).optional(),images:D.array(_t).optional().default([])}),Ut=Ot.extend({role:D.literal("user")}),Lt=Ot.extend({role:D.literal("assistant")}),Bt=Ot.extend({role:D.literal("tool"),name:D.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),Wt=Ot.extend({role:D.literal("bash"),command:D.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),zt=Ot.extend({role:D.literal("system")}),Gt=Ot.extend({role:D.literal("error")}),Vt=Ot.extend({role:D.literal("info")}),qt=D.discriminatedUnion("role",[Ut,Lt,Bt,Wt,zt,Gt,Vt]),Ht=__name((e,t)=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),Jt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e}),"createInfoEntry"),Kt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),Yt=__name((e,t,n)=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Qt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),Zt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Xt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),en=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return qt.parse(n)},"updateEntryWithOutput"),tn=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),nn=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),rn=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),on=["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…"],an=__name(()=>on[Math.floor(Math.random()*on.length)],"getRandomLLMStatus"),sn=__name(e=>{switch(e){case At:return"Read";case Pt:return"Edit";case St:return"Write";case xt:return"List";case $t:return"Read Multiple";case It:return"Search";case Dt:return"Shell";case Ft:return"Todos";case Rt:return"Thinking…";case Mt:return"Web Search";case jt:return"Web Fetch";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),cn=__name((e,t)=>{try{switch(e){case At:case St:const e=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(e);case Pt:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case xt:return toRelativePath(t.path||"directory");case It:const n=t.path||"files";return`"${t.pattern}" in ${toRelativePath(n)}`;case Dt:if(t.command){const e=Array.isArray(t.args)&&t.args.length>0?` ${t.args.join(" ")}`:"string"==typeof t.args&&t.args?` ${t.args}`:"";return`${t.command}${e}`}return t.command||"";case Ft:return`${t.todos?t.todos.length:0} items`;case Rt:return t.content||"planning";case $t:const r=t.include||[];return Array.isArray(r)?r.join(", "):"multiple files";case Mt:return t.query||"search";case jt:return t.url||"fetch";default:const o=t?.messages||[];if(Array.isArray(o)&&o.length>0&&o[0]&&"object"==typeof o[0]&&"content"in o[0]){const e=o[0].content;if("string"==typeof e)return e.slice(0,50)+(e.length>50?"...":"")}return JSON.stringify(t||{})}}catch{return"parameters"}},"getToolInputContent"),ln=__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"),dn=__name(()=>{const[e,t]=F({isExecuting:!1,currentCommand:null});return{executeBash:N(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Tt(e,{timeout:3e4,cwd:process.cwd()}),o=kt(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]=en(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]=en(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var un=D.object({absolutePath:D.string().describe("The absolute path to the file to read"),offset:D.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:D.number().optional().describe("Optional number of lines to read")});D.object({content:D.union([D.string(),D.instanceof(Buffer)]),contentType:D.enum(["text","binary"]),fileType:D.string(),size:D.number(),linesRead:D.number().optional()});var mn=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(!f.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw new mn("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=f.normalize(t);try{await A.access(o,H.constants.F_OK|H.constants.R_OK)}catch{throw new mn(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await A.stat(o)).isFile())throw new mn("Path does not point to a file","NOT_A_FILE");const a=getFileType(o),s=isBinaryFile(a);if(void 0!==n&&void 0===r||void 0===n&&void 0!==r)throw new mn("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new mn("Offset must be >= 0","INVALID_OFFSET");if(void 0!==r&&r<=0)throw new mn("Limit must be > 0","INVALID_LIMIT");try{if(s){const e=await A.readFile(o);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==n&&void 0!==r){const e=await readTextFileLines(o,n,r);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await A.readFile(o,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof mn)throw e;throw new mn(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var gn={".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=f.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",...gn}[t]||"unknown"}function isBinaryFile(e){return Object.values(gn).includes(e)}async function readTextFileLines(e,t,n){const r=(await A.readFile(e,"utf8")).split(/\r?\n/),o=t,a=Math.min(o+n,r.length),s=r.slice(o,a);return{content:s.join("\n"),linesRead:s.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=f.isAbsolute(o)?o:f.resolve(process.cwd(),o),a=await readFileContent({absolutePath:e});if("binary"===a.contentType)continue;const s=String(a.content),i=f.relative(process.cwd(),e),c=1e5;if(s.length>c){t.push({token:r,resolvedPath:e,content:"",tooLarge:!0});const o=`${i}`;n=n.replace(r,o);continue}t.push({token:r,resolvedPath:e,content:s});const l=`{${i}: ${s}}`;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=`{${f.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 pn={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=un.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading file`}},"execute")},hn=D.object({filePath:D.string().describe("The absolute path to the file to edit"),oldValue:D.string().describe("The text to replace"),newValue:D.string().describe("The new text to insert"),replacementCount:D.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:D.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:a=1}=e;if(!t)throw createFileEditError("filePath is required","INVALID_PATH");if(!f.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&&a<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await Q.access(t,Z.F_OK|Z.R_OK|Z.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${t}`,"FILE_ACCESS_ERROR")}let s;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");s=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 i=(s.match(new RegExp(escapeRegExp(n),"g"))||[]).length;if(0===i)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let c,l;if(o)c=i;else if(c=a,c>i)throw createFileEditError(`Expected ${c} replacements, but only found ${i} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||c===i)l=s.split(n).join(r),d=i;else{l=s;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 Q.writeFile(t,l,"utf-8"),{path:t,replacementsCount:d,oldContent:s,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}D.object({path:D.string(),replacementsCount:D.number(),oldContent:D.string(),newContent:D.string()}),D.object({name:D.string(),message:D.string(),code:D.string().optional()}),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),__name(formatOutput2,"formatOutput");var fn={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=hn.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while editing file`}},"execute")},yn=D.object({path:D.string().describe("The absolute path to the directory to read"),exclude:D.array(D.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:D.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});D.object({files:D.array(D.string()),directories:D.array(D.string())});var wn=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(!f.isAbsolute(t))throw new wn("Path must be absolute, not relative","INVALID_PATH");try{if(!(await A.stat(t)).isDirectory())throw new wn("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof wn)throw e;throw new wn(`Directory does not exist or is not accessible: ${t}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await A.readdir(t);let o=[];r&&(o=await loadGitIgnorePatterns(t));const a=[...n,...o],s=[],i=[];for(const n of e){if(shouldIgnoreEntry(n,a))continue;const e=f.join(t,n);try{const t=await A.stat(e);t.isDirectory()?i.push(n):t.isFile()&&s.push(n)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:s.sort(),directories:i.sort()}}catch(e){if(e instanceof wn)throw e;throw new wn(`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=f.resolve(e);const r=await findGitRoot(e);for(;n&&isWithinGitRoot(n,r);){const e=f.join(n,".gitignore");try{const n=(await A.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));t.push(...n)}catch(e){}const r=f.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=f.resolve(e);for(;;){try{const e=f.join(t,".git");if((await A.stat(e)).isDirectory())return t}catch{}const e=f.dirname(t);if(e===t)throw new Error("Not in a git repository");t=e}}function isWithinGitRoot(e,t){const n=f.resolve(e),r=f.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(se(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 En={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=yn.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading directory`}},"execute")},bn=D.object({filePath:D.string().describe("The absolute path where the file should be written"),content:D.string().describe("The content to write to the file")});async function writeFile5({filePath:e,content:t}){if(!v(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=w(e);return K(n)||await S(n,{recursive:!0}),await x(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}`}D.object({success:D.boolean(),message:D.string(),path:D.string().optional()}),__name(writeFile5,"writeFile"),__name(formatOutput4,"formatOutput");var vn={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=bn.parse(e),n=await writeFile5(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")},Cn=D.object({include:D.array(D.string()).describe("Array of glob patterns to include files"),exclude:D.array(D.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:D.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:D.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:D.string().optional().describe("Base directory for relative paths. Default: current working directory")}),Tn=D.object({filePath:D.string(),content:D.string(),fileType:D.string(),size:D.number()});D.object({content:D.string(),filesRead:D.array(D.string()),errors:D.array(D.object({file:D.string(),error:D.string()})),fileDetails:D.array(Tn)});var kn=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},An=["**/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 a of e)try{(await ie(a,{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 "${a}": ${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:a=process.cwd()}=e;if(!t||0===t.length)throw new kn("At least one include pattern must be provided","NO_PATTERNS");const s=y.resolve(a),i={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(...An);const a=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:s});for(const e of a)try{const t=y.resolve(s,e),n=await readFileContent({absolutePath:t}),r=processFileResult({content:n,filePath:e});i.fileDetails.push(r),i.content+=`\n// File: ${e} (${n.fileType})\n`,i.content+=r.content,i.content+="\n",i.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);i.errors.push({file:e,error:n}),i.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return i}catch(e){if(e instanceof kn)throw e;throw new kn(`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 Pn={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=Cn.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading multiple files`}},"execute")},Sn=D.object({pattern:D.string().min(1,"Pattern is required"),include:D.array(D.string()).optional(),directory:D.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,o)=>{const a=r(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",i="";a.stdout?.on("data",e=>{s+=e.toString()}),a.stderr?.on("data",e=>{i+=e.toString()}),a.on("close",e=>{0===e?n(s):1!==e||i?o(new Error(i||`Command failed with exit code ${e}`)):n("")}),a.on("error",e=>{o(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(a){if(!(a instanceof Error&&a.message.includes("ENOENT")))throw a;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 a=e.trim().split("\n"),s=[];for(const e of a){const t=parseGrepLine(e);t&&s.push(t)}return s}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 xn={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=Sn.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while searching files`}},"execute")},$n=D.object({command:D.string().min(1,"Command cannot be empty"),args:D.array(D.string()).optional(),directory:D.string().optional(),timeout:D.number().optional()}),In=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,a,s){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=a,this.duration=s}};async function executeShellCommand(e){const{command:t,args:n=[],directory:o,timeout:a=3e4}=e,s=Date.now();if(!t.trim())throw new In("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(f.isAbsolute(o))throw new In("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=f.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await P.stat(i)).isDirectory())throw new In(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof In)throw e;throw new In(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:i,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((o,i)=>{let c="",l="",d=!1;const u=n.length>0?ce([t,...n]):t,m=setTimeout(()=>{if(!d){g.kill("SIGTERM");const e=Date.now()-s;i(new In(`Command timed out after ${a}ms`,"TIMEOUT",null,"SIGTERM",c,l,e))}},a),g=r(u,[],e);g.stdout?.on("data",e=>{c+=e.toString()}),g.stderr?.on("data",e=>{l+=e.toString()}),g.on("close",(e,t)=>{d=!0,clearTimeout(m);const n=Date.now()-s;0===e?o({stdout:c.trim(),stderr:l.trim(),exitCode:e,signal:t,duration:n}):i(new In(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,c.trim(),l.trim(),n))}),g.on("error",e=>{d=!0,clearTimeout(m);const t=Date.now()-s;i(new In(`Failed to start command: ${e.message}`,"START_FAILED",null,null,c.trim(),l.trim(),t))})})}catch(e){if(e instanceof In)throw e;throw new In(`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 Dn={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=$n.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${o.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${o.cross} Error: ${e.message}`}return`${o.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}__name(think,"think");var Rn={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 Fn={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};function getRootAgentDir(){return y.join(k.homedir(),".commandcode","agents")}function getLocalAgentDir(){return y.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,t){try{const n=(await P.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=y.join(e,n),o=await P.readFile(r,"utf-8"),{data:a,content:s}=le(o);let i=a.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:a.name||n.replace(".md",""),description:a.description||"",tools:i,systemPrompt:s.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}}async function loadAllAgents(){const[e,t]=await Promise.all([loadAgentsFromDirectory(getRootAgentDir(),"personal"),loadAgentsFromDirectory(getLocalAgentDir(),"project")]);return{personal:e,project:t}}__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents");var Mn=2e5;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)}function getEnterpriseMemoryPath(){switch(T.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return f.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const e=T.homedir();return f.join(e,".commandcode","AGENTS.md")}function getProjectMemoryPaths(e){return[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:K(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(K(n)){t.push({type:"project",path:n,exists:!0,description:"Team-shared project instructions"});break}t.find(e=>"project"===e.type)||t.push({type:"project",path:e[0],exists:!1,description:"Team-shared project instructions"})}const o=getUserMemoryPath();return t.push({type:"user",path:o,exists:K(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return K(e)?await A.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}async function processImports(e,t,n=0,r=5){if(n>=r)return e;const o=[],a=e.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),s=Array.from(a.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let i=a;for(const e of s){const o=e[1];let a=o;o.startsWith("~/")?a=f.join(T.homedir(),o.slice(2)):f.isAbsolute(o)||(a=f.resolve(f.dirname(t),o));const s=await loadMemoryFile(a);if(s){const t=await processImports(s,a,n+1,r);i=i.replace(e[0],`\n# Imported from ${o}\n${t}\n`)}}return i=i.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>o[parseInt(t)]),i}async function loadAllMemories(e,t){const n=new Map,r=getEnterpriseMemoryPath();if(K(r)){const e=await loadMemoryFile(r);if(e){const t=await processImports(e,r);n.set(r,t)}}const o=getUserMemoryPath();if(K(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);n.set(o,t)}}const a=[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")];for(const e of a)if(K(e)){const t=await loadMemoryFile(e);if(t){const r=await processImports(t,e);n.set(e,r)}break}if(t&&t.length>0)for(const r of t){const t=f.isAbsolute(r)?f.dirname(r):f.dirname(f.resolve(e,r));if(t.startsWith(e)&&t!==e){const r=[];let o=t;for(;o.startsWith(e)&&o!==e;)r.push(o),o=f.dirname(o);for(const e of r.reverse()){const t=[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")];for(const e of t)if(K(e)&&!n.has(e)){const t=await loadMemoryFile(e);if(t){const r=await processImports(t,e);n.set(e,r)}break}}}}return n}async function openInEditor(e){const t=process.env.EDITOR||process.env.VISUAL||"code",n=f.dirname(e);return K(n)||await A.mkdir(n,{recursive:!0}),K(e)||await A.writeFile(e,"# AGENTS.md\n\n","utf-8"),new Promise((n,o)=>{const a=r(t,[e],{stdio:"inherit",shell:!0});a.on("exit",e=>{0===e?n():o(new Error(`Editor exited with code ${e}`))}),a.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),o(e)})})}async function initProjectMemory(e){const t=f.join(e,"AGENTS.md");return K(t)||await A.writeFile(t,"# Memory\n\n## Project Overview\nSee @README.md for project overview and @package.json for available npm/pnpm commands for this project.\n\n## Code Style Guidelines\n- Use descriptive variable names\n- Follow existing patterns in the codebase\n- Extract complex conditions into meaningful boolean variables\n\n## Architecture Notes\nAdd important architectural decisions and patterns here.\n\n## Common Workflows\nDocument frequently used workflows and commands here.\n","utf-8"),t}async function getMemoryContent(e){try{const t=process.cwd(),n=await loadAllMemories(t,e);if(0===n.size)return null;const r=[],o=getEnterpriseMemoryPath(),a=getUserMemoryPath(),s=[f.join(t,"AGENTS.md"),f.join(t,".commandcode","AGENTS.md")];n.has(o)&&r.push(`# Memory from: ${o}\n\n${n.get(o)}`),n.has(a)&&r.push(`# Memory from: ${a}\n\n${n.get(a)}`);for(const e of s)if(n.has(e)){r.push(`# Memory from: ${e}\n\n${n.get(e)}`);break}for(const[e,t]of n)e===o||e===a||s.includes(e)||r.push(`# Memory from: ${e}\n\n${t}`);return r.join("\n\n---\n\n")}catch(e){return null}}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),__name(getEnterpriseMemoryPath,"getEnterpriseMemoryPath"),__name(getUserMemoryPath,"getUserMemoryPath"),__name(getProjectMemoryPaths,"getProjectMemoryPaths"),__name(discoverMemoryFiles,"discoverMemoryFiles"),__name(loadMemoryFile,"loadMemoryFile"),__name(function getCodeBlockRegex(){return/```[\s\S]*?```|`[^`]+`/g},"getCodeBlockRegex"),__name(function getImportRegex(){return/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm},"getImportRegex"),__name(processImports,"processImports"),__name(loadAllMemories,"loadAllMemories"),__name(openInEditor,"openInEditor"),__name(initProjectMemory,"initProjectMemory"),__name(getMemoryContent,"getMemoryContent");var jn=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return y.join(k.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return ue(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=y.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=y.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=n("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await P.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),!1}}async isProjectInitialized(){try{return(await P.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 P.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=y.join(this.projectPath,`${t}.jsonl`);try{const e=(await P.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=cn(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=cn(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=y.join(this.projectPath,`${t}.jsonl`);try{const e=(await P.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=y.join(e,t);try{return(await P.stat(n)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=y.join(e,t);try{return await P.mkdir(n,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=y.join(_SessionManager.getProjectsBasePath(),e);try{try{await P.access(t)}catch{return[]}const e=(await P.readdir(t)).filter(e=>e.endsWith(".jsonl")),n=[];for(const r of e){const e=r.replace(".jsonl",""),o=y.join(t,r);try{const r=await P.stat(o),a=(await P.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(a.length>0){let o="",s="";const i=JSON.parse(a[0]);i.gitBranch&&(s=i.gitBranch);for(const e of a){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:a.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=y.join(this.projectPath,`${this.sessionId}.share.json`);try{await P.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=y.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await P.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=y.join(this.projectPath,`${this.sessionId}.share.json`);try{await P.unlink(e)}catch(e){}}},Nn=new ke("AgentExecutor");function agentToTool(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a}=t;return{name:e.name,description:e.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object"}}},required:["messages"]},execute:__name(async(t,s)=>{let i=getAvailableTools(e,{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a});if(s?.onFeedUpdate){const n=cn(e.name,t),r={id:`${e.name}-tool-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:"Running..."};s.onFeedUpdate(r)}const c=await getConfiguredProvider(),l=await isOAuthEnforced();let d;c===Me&&(d=await je.getValidAccessToken(),validateOAuthToken({token:d,provider:c}));const u=getApiBaseUrl(),m=new dt({baseUrl:u});let g=0;const p=[];if(Array.isArray(t?.messages)&&t?.messages.length>0)for(const e of t.messages)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&p.push({role:"user",content:t})}const h={stream:!0,messages:p,max_tokens:64e3,system:e.systemPrompt,temperature:.3,tools:i,model:"anthropic:claude-sonnet-4-20250514"},y=await isTasteLearningEnabled(),w={[$e]:jn.getCurrentProjectDirName(),[Ie]:y.toString(),[Se]:l.toString()};d&&(w[xe]=`Bearer ${d}`);const E=getEnvironmentContext(),b=await getMemoryContent([]);let v="",C=!0;for(;C;){if(s?.abortSignal?.aborted)throw new Error("Interrupted by user");if(0===g&&p.length>0){const e=p[p.length-1];g=estimateTokens(e)}const e=await callAPIWithRetry({request:m,body:{config:E,memory:b,params:{...h,messages:p}},headers:w,abortSignal:s?.abortSignal,onTextDelta:__name(e=>{g+=estimateTokens(e)},"onTextDelta")}),t=e.content.filter(e=>"tool_use"===e.type);if(v=e.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(e,s):e.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===t.length){const t=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);t.length>0&&p.push({role:"assistant",content:t}),C=!1;break}const n=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);n.length>0&&p.push({role:"assistant",content:n});const r=[],o=new Set;let a=!1;for(const e of t){if(s?.abortSignal?.aborted)throw new Error("Interrupted by user");let t=e.input;try{if(["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&s?.onPermissionRequest&&!await s.onPermissionRequest(e.name,t)){Nn.debug(`Permission denied for tool: ${e.name}`),a=!0;break}if("object"==typeof t&&null!==t){const n={...t};let r=!1;const o=["path","file_path","absolutePath","filePath","directory","folder"];for(const e of o)if(e in n&&"string"==typeof n[e]){const t=n[e];if(!f.isAbsolute(t)){const o=f.resolve(process.cwd(),t);n[e]=o,r=!0,Nn.debug(`Converted '${e}': '${t}' -> '${o}'`)}}"paths"in n&&Array.isArray(n.paths)&&(n.paths=n.paths.map(e=>"string"!=typeof e||f.isAbsolute(e)?e:(r=!0,f.resolve(process.cwd(),e)))),r?(t=n,Nn.debug(`Resolved input for ${e.name}: ${JSON.stringify(t,null,2)}`)):Nn.debug(`No path resolution needed for ${e.name}: ${JSON.stringify(t,null,2)}`)}if(s?.onFeedUpdate){const n=cn(e.name,t),r={id:`${e.name}-${e.id}-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:"Processing…"};s.onFeedUpdate(r)}const n=await executeTool(e.name,t,s),i=estimateTokens(n);if(g+=i,s?.abortSignal?.aborted)throw new Error("Interrupted by user");const c=checkToolOutputTokensLimit(n,e.name);if(r.push({type:"tool_result",tool_use_id:e.id,content:c}),o.add(e.id),s?.onFeedUpdate){const n=cn(e.name,t),r={id:`${e.name}-${e.id}-complete-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:c};s.onFeedUpdate(r)}Nn.debug(`Tool executed successfully: ${e.name}`)}catch(n){const a=n instanceof Error?n.message:"Unknown error";if(r.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${a}`,is_error:!0}),o.add(e.id),s?.onFeedUpdate){const n=cn(e.name,t),r={id:`${e.name}-${e.id}-error-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:`Error: ${a}`};s.onFeedUpdate(r)}Nn.error(`Tool execution failed: ${e.name} - ${a}`)}}if(a){const e=p[p.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?o.has(e.id):"text"===e.type);t.length>0?e.content=t:p.pop()}C=!1;break}const i=[...r];p.push({role:"user",content:i})}return v||"DONE"},"execute")}}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a}=t;let s=[];if("*"===e.tools)s=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){const t=a[e];if(t){const e=o.get(t);if(e)s.push(e);else{const e=r.find(e=>e.name===t);e&&s.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){const e=a[t];if(e){const t=o.get(e);if(t)s.push(t);else{const t=r.find(t=>t.name===e);t&&s.push(t)}}}return s}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:a}=e;let s=null;for(let e=0;e<5;e++)try{const e=await t.post({body:n,stream:!0,endpoint:De.ALPHA.GENERATE,signal:o,headers:r}),s=de.fromReadableStream(e);a&&s.on("text",a);let i=null;s.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await s.finalMessage();if(i)throw i;return c}catch(t){if(s=t,isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Nn.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await new Promise(e=>setTimeout(e,n))}throw s||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof nt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ot||403===e?.status}function isRetryableError(e){return!!e?.message&&!!['Unexpected event order, got error before "message_start"',"API Error: Unexpected event order","Body is unusable: Body has already been read"].some(t=>e.message.includes(t))}function formatAPIError(e,t){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||t?.aborted)return new Error("Interrupted by user");if(e instanceof nt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof ot||403===e?.status)return e;if(e?.message?.startsWith("Error:"))return e;let n="Error: ";return e.message?n+="Something went wrong. Please try again or contact support if the issue persists.":e.toString?n+=e.toString():n+="Unknown error occurred",new Error(n)}function processServerToolBlocks(e,t){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let n="";for(const r of e.content)if("text"===r.type)n+=r.text;else if("server_tool_use"===r.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const e=cn(r.name,r.input),n=Nt(r.name)?"Found 10 results":"Content fetched",o={id:`${r.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:r.name,input:e,output:n};t.onFeedUpdate(o)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}__name(agentToTool,"agentToTool"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks");var _n=new Map,On=null;function initializeAgentManager(e){On=e}async function loadAgentTools(){if(!On)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");const{personal:e,project:t}=await loadAllAgents();_n.clear();const n=[...e,...t];for(const e of n){const t=agentToTool(e,On);_n.set(t.name,t)}}async function getAgentTools(){return 0===_n.size&&await loadAgentTools(),Array.from(_n.values())}async function getAgentTool(e){return 0===_n.size&&await loadAgentTools(),_n.get(e)}function isPathInTasteDirectory(e){const{filePath:t,projectRoot:n}=e,r=f.join(n,".commandcode","taste"),o=f.normalize(f.resolve(n,t)),a=f.normalize(r);return o.startsWith(a)}function getTasteFileInfo(e){const t=f.normalize(f.resolve(e)),n=f.normalize(f.join(process.cwd(),".commandcode","taste")),r=f.normalize(f.join(T.homedir(),".commandcode","taste"));let o=null;if(t.startsWith(n)?o=n:t.startsWith(r)&&(o=r),!o)return{isTaste:!1};if(!t.endsWith("taste.md"))return{isTaste:!1};const a=f.relative(o,t).split(f.sep);return 1===a.length?{isTaste:!0}:2===a.length?{isTaste:!0,category:a[0]}:{isTaste:!1}}__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool"),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(function getTasteAccessError(){return"Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system."},"getTasteAccessError");var Un=[pn,fn,En,vn,Pn,xn,Dn,Rn,Fn],Ln=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],Bn=new Map(Un.map(e=>[e.name,e]));async function executeTool(e,t,n){let r=Bn.get(e);if(r||(r=await getAgentTool(e)),!r){const t=await getAgentTools(),n=[...Array.from(Bn.keys()),...t.map(e=>e.name)];throw new Error(`Tool "${e}" not found. Available tools: ${n.join(", ")}`)}if(("write_file"===e||"edit_file"===e)&&!0!==n?.allowTasteWrite){const e=t.filePath,n=isPathInTasteDirectory({filePath:e,projectRoot:process.cwd()});if(e&&n)throw new Error("Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system.".replace("Error: ",""))}try{return!Bn.has(e)&&n?await r.execute(t,n):await r.execute(t)}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message)throw e;return e instanceof Error?`Error: ${e.message}`:"Error: Unknown error occurred"}}async function getToolSchemas(){return[...Un.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...(await getAgentTools()).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...Ln]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var Wn={};Un.forEach(e=>{Wn[e.name]=toPascalCase(e.name)}),Ln.forEach(e=>{Wn[e.name]=toPascalCase(e.name)});var zn={};Object.entries(Wn).forEach(([e,t])=>{zn[t]=e}),initializeAgentManager({clientTools:Un,serverTools:Ln,toolsMap:Bn,displayNameToToolName:zn});var Gn=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(!y.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=y.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=y.basename(e);return y.dirname(e),this.isUserPath(e)?`<user-home>/${y.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))}},Vn=new class extends me{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;addEvent(e){const{type:t,message:n,details:r}=e,o={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r};this.events.unshift(o),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",o)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}};function extractLearningWithConfidence(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)\.\s+Confidence:\s*(\d+\.?\d*)/);return n?{text:n[1].trim(),confidence:parseFloat(n[2])}:null}function extractLearnings(e){const{text:t}=e;return t.split("\n").filter(e=>e.trim().startsWith("-")).map(e=>extractLearningWithConfidence({line:e})).filter(Boolean)}function compareLearnings(e){const{oldText:t,newText:n}=e,r=extractLearnings({text:t}),o=extractLearnings({text:n}),a=new Map(r.map(e=>[e.text,e.confidence])),s=[],i=[],c=[];return o.forEach(e=>{const t=a.get(e.text);void 0===t?s.push(e):e.confidence>t?i.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&c.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:s,upgraded:i,downgraded:c}}__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings");var qn=__name((e,t)=>{},"dlog"),Hn=new ke("LearningAgent"),Jn=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=5;request;projectRoot;tasteDir;constructor(e){this.request=e.request,this.projectRoot=e.projectRoot,this.tasteDir=f.join(e.projectRoot,".commandcode","taste")}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)this.pendingMessages=t;else if(0!==t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length){this.isProcessing=!0;try{for(await this.runLearningLoop({messages:t}),this.lastProcessedMessageIndex=t.length-1;null!==this.pendingMessages;){const e=this.pendingMessages;this.pendingMessages=null,e.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length>0&&(await this.runLearningLoop({messages:e}),this.lastProcessedMessageIndex=e.length-1)}}catch(e){Vn.addEvent({type:"error",message:"learning pass failed",details:e instanceof Error?e.message:String(e)}),this.lastProcessedMessageIndex=t.length-1}finally{this.isProcessing=!1}}}async runLearningLoop(e){const{messages:t}=e,n=["analyzing deltas","computing embeddings","updating weights","refining patterns","processing signals","extracting features","tuning parameters","optimizing priors"],r=n[Math.floor(Math.random()*n.length)];Vn.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),a=t.length-this.lastProcessedMessageIndex-1,s=Math.max(20,a),i=Math.max(0,t.length-s),c=t.slice(i);let l=0,d=!1;qn("New messages count",a),qn("Context window size",s),qn("Sending conversation messages",c.length);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){qn(`Starting learning turn ${l+1}/${this.maxTurns}`);const e=await this.callLearningAPI({conversation:u});qn("Received response from learning API"),qn("Response content blocks",e.content.length);const t=this.extractToolCalls({content:e.content});if(qn("Extracted tool calls",t.length),t.length>0&&qn("Tool calls",t.map(e=>({name:e.name,id:e.id}))),0===t.length){qn("No tool calls found, checking for text response");const t=e.content.filter(e=>"text"===e.type);if(t.length>0){const e=t[0].text||"";qn("Text response from LLM",e.substring(0,300))}break}qn("Executing tools");const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});qn("Tools executed, learnings found?",r),r&&(d=!0),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&Hn.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Vn.addEvent({type:"no_learnings",message:"no changes to taste"}),Vn.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{qn(`Executing tool: ${e.name}`),this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",a="";if("write_file"===e.name||"edit_file"===e.name){qn("Tool is write/edit, will track changes");const e=t;if(a=String(e.filePath||e.file_path||""),a)try{o=await H.promises.readFile(a,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const s=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&a)try{i=await H.promises.readFile(a,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=a.replace(`${this.projectRoot}/`,"");qn("Target file path",e);const t=compareLearnings({oldText:o,newText:i});qn("Diff results",{added:t.added.length,upgraded:t.upgraded.length,downgraded:t.downgraded.length}),t.added.forEach(t=>{Vn.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Vn.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Vn.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:s})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:t instanceof Error?t.message:String(t)})}return{results:n,learningsFound:r}}validateTastePath(e){const{toolName:t,input:n}=e,r={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[t];if(!r||!n[r])return;const o=String(n[r]);if(f.isAbsolute(o))throw new Error(`Security: ${t} received absolute path. Only taste-relative paths are allowed (e.g., " .commandcode/taste/cli/taste.md" or " .commandcode/taste/taste.md"). Attempted: ${o}`);const a=f.join(this.tasteDir,o);if(!f.normalize(a).startsWith(this.tasteDir))throw new Error(`Security: ${t} can only access files within .commandcode/taste/. Attempted: ${o}`)}adjustPathsForTaste(e){const{toolName:t,input:n}=e,r={...n},o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[t];if(o&&r[o]){const e=String(r[o]);let n;const a="write_file"===t||"edit_file"===t;if(f.isAbsolute(e)&&e.startsWith(this.tasteDir))if(a){if(!this.isValidTasteFilePath(e))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${e}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);n=e}else n=e;else{if(f.isAbsolute(e))throw new Error(`Invalid path: Absolute path outside taste directory: ${e}`);if(n=e.startsWith(".commandcode/taste")?e.replace(".commandcode/taste",this.tasteDir):f.join(this.tasteDir,e),a&&!this.isValidTasteFilePath(n))throw new Error(`Invalid adjusted path: ${n}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}r[o]=n}return r}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isValidTasteFilePath(e))throw new Error(`Security: Invalid taste file path. Only allowed:\n - {project}/.commandcode/taste/taste.md\n - {project}/.commandcode/taste/{category}/taste.md\nAttempted: ${e}`)}async initializeTasteDirectory(){if(!H.existsSync(this.tasteDir)){H.mkdirSync(this.tasteDir,{recursive:!0});const e=f.join(this.tasteDir,"taste.md");H.writeFileSync(e,"","utf-8")}}async reorganizeIfNeeded(){const e=f.join(this.tasteDir,"taste.md");if(!H.existsSync(e))return!1;const t=H.readFileSync(e,"utf-8"),n=this.parseCategories({content:t}).filter(e=>e.learningCount>5);if(0===n.length)return!1;let r=t;for(const e of n){const t=e.name.toLowerCase().replace(/\s+/g,"-"),n=f.join(this.tasteDir,t),o=f.join(n,"taste.md");H.mkdirSync(n,{recursive:!0}),Vn.addEvent({type:"refactored",message:`moved: ${e.name} package`,details:`moved to ${t}/taste.md`});const a=`# ${e.name}\n${e.learnings.join("\n")}\n`;H.writeFileSync(o,a,"utf-8");const s=`# ${e.name}\nSee [${t}/taste.md](${t}/taste.md)\n`;r=r.replace(e.fullSection,s)}return H.writeFileSync(e,r,"utf-8"),!0}parseCategories(e){const{content:t}=e,n=[],r=t.split(/^# /gm).filter(e=>e.trim());for(const e of r){const t=e.split("\n"),r=t[0].trim();if(e.includes("See ["))continue;const o=t.filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:"));o.length>0&&n.push({name:r,learningCount:o.length,learnings:o,fullSection:`# ${e}`})}return n}async getTasteStructure(){return H.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(e){const{dir:t,prefix:n}=e,r=H.readdirSync(t,{withFileTypes:!0});let o="";for(let e=0;e<r.length;e++){const a=r[e],s=e===r.length-1,i=s?"└── ":"├── ";if(a.isDirectory()){o+=`${n}${i}${a.name}/\n`;const e=n+(s?" ":"│ ");o+=await this.buildTree({dir:f.join(t,a.name),prefix:e})}else if("taste.md"===a.name){const e=(H.readFileSync(f.join(t,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${n}${i}${a.name} (${e} learnings)\n`}else o+=`${n}${i}${a.name}\n`}return o}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===Me&&(o=await je.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const a={[$e]:jn.getCurrentProjectDirName(),[Se]:r.toString()};o&&(a[xe]=`Bearer ${o}`);let s=0,i=null;for(;s<=this.maxApiRetries;)try{return await this.request.post({endpoint:De.ALPHA.TASTE.LEARN,body:{conversation:t,tools:await this.getTasteTools()},headers:a})}catch(e){if(i=e instanceof Error?e:new Error(String(e)),s++,s>this.maxApiRetries)throw i;const t=2e3*Math.pow(2,s);await this.sleep({ms:t})}throw i||new Error("API call failed")}sleep(e){const{ms:t}=e;return new Promise(e=>setTimeout(e,t))}static async isInitialized(e){const{projectRoot:t}=e,n=f.join(t,".commandcode","taste");return H.existsSync(n)}};async function getTasteContent(){try{const e=process.cwd(),t=f.join(e,".commandcode","taste","taste.md");if(!K(t))return null;const n=await A.readFile(t,"utf-8"),r=n.trim();return r&&"# Taste (Continuously Learned by CommandCode)"!==r?n:null}catch(e){return null}}__name(getTasteContent,"getTasteContent");var Kn=new ke("ContextEngine"),Yn=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();lastFileContexts=[];learningAgent;constructor(e,t){const n=getApiBaseUrl();this.request=new dt({baseUrl:n}),this.callbacks=e,this.sessionManager=new jn(t),this.learningAgent=new Jn({request:this.request,projectRoot:process.cwd()})}async interrupt(e=!1){if(this.abortController){this.abortController.abort(),this.abortController=null,Kn.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(),Kn.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=Ht("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>Kn.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t){let n=e,r=[];try{const t=await processFileReferences(e);if(n=t.processedContent,r=t.fileReferences,r.length>0){const e=r.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}const o=Ht(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 a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),n.trim()&&a.push({type:"text",text:n});const s={role:"user",content:a};return this.addMessageAndSync(this.createMessageWithMeta(s)),this.sessionManager.saveMessages(this.messages,o).catch(e=>Kn.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent(),await this.processMessages()}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){Kn.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}async processMessages(){let e="";this.abortController=new AbortController;let t=!1;for(;;)try{this.checkIfInterrupted(),t||(this.initializeInteractionTokens(),t=!0);const{body:n,headers:r}=await this.prepareAPICall(),o=await this.callAPIWithRetry({body:n,headers:r});this.updateContextUsage(o);const a=o.content.filter(e=>"tool_use"===e.type),s=o.content.filter(e=>"server_tool_use"===e.type);if(e=s.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===a.length){const t=o.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===s.length){const t=Kt(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>Kn.error(`Failed to save messages: ${e}`))}if(0!==s.length&&this.sessionManager.saveMessages(this.messages).catch(e=>Kn.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=Ht(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>Kn.error(`Failed to save messages: ${e}`)),this.triggerLearningAgent();continue}}break}const i=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(i.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:i})),e.trim()){const t=Kt(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:a}),{toolResults:l,executedToolIds:d,permissionDenied:u}=c;if(u){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?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const m=[...l];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){m.push({type:"text",text:t});const e=Ht(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>Kn.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&Kn.debug("Request interrupted or insufficient credits"),this.formatAPIError(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 Kn.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}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async compactConversation({preserveCurrentInteraction:e=!1}={preserveCurrentInteraction:!1}){const t=this.messages.length,n=this.contextTokensUsed;let r=-1;if(e)for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if("user"===t.message.role){const n=t.message.content;if(!Array.isArray(n)){r=e;break}if(!n.some(e=>"tool_result"===e.type)){r=e;break}}}const o=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],a=n.message.role;if(e&&t>=r&&-1!==r)o.push(n);else if("user"===a){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type))continue;o.push(n)}else o.push(n)}else if("assistant"===a){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"text"===e.type&&e.text?.trim());t.length>0&&o.push({...n,message:{...n.message,content:t}})}else"string"==typeof e&&e.trim()&&o.push(n)}}this.messages=o,await this.sessionManager.saveMessages(this.messages);const a=estimateTokens(this.getRawMessages());return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:Mn}),{messagesRemoved:t-o.length,tokensSaved:Math.max(0,n-a)}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}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){}}))}async syncMessageToShare(e,t){try{const n=Gn.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:De.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.abortController?.signal.aborted)throw new Error("Interrupted by user")}initializeInteractionTokens(){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message)}async prepareAPICall(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(t),t===Me&&(r=await je.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o={tools:e,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:"anthropic:claude-sonnet-4-5-20250929"},a={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),params:o};Kn.debug(`🔍 API Call: ${o.model}, ${this.messages.length} messages, ${e.length} tools, streaming: true`);const s=await isTasteLearningEnabled(),i={[$e]:jn.getCurrentProjectDirName(),[Ie]:s.toString(),[Se]:n.toString()};return r&&(i[xe]=`Bearer ${r}`),{body:a,headers:i}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++)try{const t=await this.request.post({body:e.body,stream:!0,endpoint:De.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers}),n=de.fromReadableStream(t);n.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let r=null;n.on("error",e=>{r="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const o=await n.finalMessage();if(r)throw r;return this.callbacks.onRetryUpdate?.(null),o}catch(e){if(t=e,this.isNonRetryableError(e))throw this.formatAPIError(e);if(9===n)throw this.callbacks.onRetryUpdate?.(null),this.formatAPIError(e);const r=Math.min(n,10),o=100*Math.pow(2,r),a=Math.max(o,1e3),s=Math.min(a,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await new Promise(e=>setTimeout(e,s))}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||this.abortController?.signal.aborted||e instanceof nt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ot||403===e?.status}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=e.message?.toLowerCase().includes("insufficient credits");if(t)return new Error("Insufficient credits");const n=e.message?.toLowerCase().includes("oauth authentication required");if(n)return e;if(e instanceof ot||403===e?.status)return e;let r="Error: ";return e.message?e.message.includes("Invalid 'Authorization' header")?r+='Authentication failed. Run "cmd login" to sign in again.':r+='Something went wrong. Type "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord.':e.toString?r+=e.toString():r+="Unknown error occurred",new Error(r)}async executeToolBlocks(e){const t=[],n=new Set;let r=!1;for(const o of e.toolBlocks){this.checkIfInterrupted();try{const e=await this.checkToolPermission(o);if(e.needsPermission&&!e.allowed){this.handlePermissionDenied(o),r=!0;break}const a=await this.executeSingleTool(o);t.push({type:"tool_result",tool_use_id:o.id,content:a}),n.add(o.id),this.showToolSuccess(o,a)}catch(e){const r=e instanceof Error?e.message:"Unknown error";t.push({type:"tool_result",tool_use_id:o.id,content:`Error: ${r}`,is_error:!0}),n.add(o.id),this.showToolError(o,r)}}return{toolResults:t,executedToolIds:n,permissionDenied:r}}async checkToolPermission(e){return["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.name,e.input)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=await executeTool(e.name,e.input,{onPermissionRequest:this.callbacks.onPermissionRequest,abortSignal:this.abortController?.signal,onFeedUpdate:this.callbacks.onFeedUpdate});this.checkIfInterrupted();const n=checkToolOutputTokensLimit(t,e.name),r=estimateTokens(n);return this.currentInteractionTokens+=r,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),n}handlePermissionDenied(e){const t=cn(e.name,e.input),n={..."edit_file"===e.name?e.input:{},permissionDenied:!0},r=Yt(e.name,t,n),o=en(r,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}showToolSuccess(e,t){let n="edit_file"===e.name?e.input:void 0;if("read_file"===e.name){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(n={...n||{},isTasteFile:!0,tasteCategory:e.category})}}const r={...e.input,...n?.isTasteFile?{isTasteFile:n.isTasteFile}:{},...n?.tasteCategory?{tasteCategory:n.tasteCategory}:{}},o=cn(e.name,r),a=Yt(e.name,o,n),s=en(a,t);this.callbacks.onFeedUpdate(s)}showToolError(e,t){const n=cn(e.name,e.input),r="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,o=Yt(e.name,n,r),a=en(o,tn(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let t="";for(const n of e.content)if("text"===n.type)t+=n.text;else if("server_tool_use"===n.type){if(t.trim()){const e=Kt(t.trim());this.callbacks.onFeedUpdate(e),t=""}const e=cn(n.name,n.input),r=Yt(n.name,e),o=Nt(n.name)?"Found 10 results":"Content fetched",a=en(r,o);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=Kt(t.trim());this.callbacks.onFeedUpdate(e)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}updateContextUsage(e){if(!("usage"in e))return;const t=e.usage;if(!t?.input_tokens)return;const n=calculateUsageFromResponse(t);this.contextTokensUsed=n,this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:Mn}),this.checkAndCompactIfNeeded()}async checkAndCompactIfNeeded(){const e=Math.floor(17e4);if(this.contextTokensUsed>e){Kn.debug(`Context tokens (${this.contextTokensUsed}) exceeded threshold (${e}), triggering automatic compaction`);try{const e=await this.compactConversation({preserveCurrentInteraction:!0});Kn.debug(`Automatic compaction completed: removed ${e.messagesRemoved} messages, saved ${e.tokensSaved} tokens`)}catch(e){Kn.error(`Failed to automatically compact conversation: ${e}`)}}}};function Markdown({children:e,...t}){const n={...t};he({renderer:new ye(n),breaks:!0,gfm:!0});const r=fe(e);return R.createElement(L,null,r.toString().trim())}function AssistantMessage({content:e}){return R.createElement(U,null,R.createElement(L,null,a.nodejs),R.createElement(U,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},R.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage");var Qn={"Interrupted by user":"Interrupted by user","Insufficient credits":Ne};function UserMessage({content:e}){const t="Interrupted by user"===e,n="Insufficient credits"===e,r=e.startsWith("Error:"),o=t||n||r;let s=o&&Qn[e]||e;return R.createElement(U,null,R.createElement(L,{color:o?"red":"dim"},a.pointer),R.createElement(U,{marginLeft:1},R.createElement(L,{color:o?"red":void 0,dimColor:!o,wrap:"wrap"},s)))}__name(UserMessage,"UserMessage");var Zn="#6B7280";function truncateToolOutputForDisplay(e){const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),n=t.split("\n");if(n.length<=1)return t;const r=n.slice(0,1).join("\n");return n.length,r}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:a=2,dimDiff:s=!1,maxLines:i}){const c=we.diffLines(e,t);let l=0,d=0,u=0,m=0;c.forEach(e=>{e.added?(l+=e.count||1,m+=e.count||1):e.removed&&(d+=e.count||1,m+=e.count||1)});const g=[];c.forEach((e,t)=>{const n=e.value.split("\n").filter(e=>e);e.added||e.removed?n.forEach((n,r)=>{e.removed?(u++,g.push(R.createElement(U,{key:`${t}-${r}-removed`,width:"100%"},R.createElement(L,{color:"gray",dimColor:s},u.toString().padStart(3)," "),R.createElement(U,{backgroundColor:"#712F37"},R.createElement(L,{dimColor:s},"-"),R.createElement(L,{dimColor:s}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(R.createElement(U,{key:`${t}-${r}-added`,width:"100%"},R.createElement(L,{color:"gray",dimColor:s},u.toString().padStart(3)," "),R.createElement(U,{backgroundColor:"#325B30"},R.createElement(L,{dimColor:s},"+"),R.createElement(L,{dimColor:s}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:R.createElement(U,{flexDirection:"column"},o&&!r&&R.createElement(L,{color:"gray"},"Updated"," ",R.createElement(L,{color:"white",bold:!0},n)," ","with ",R.createElement(L,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",R.createElement(L,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&R.createElement(L,{color:"red"},"Rejected update to",R.createElement(L,{color:"red"},` ${n}`)),R.createElement(U,{flexDirection:"column",marginLeft:a},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=ln(e);return t?R.createElement(U,{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(U,{key:e.id||t,flexDirection:"row"},R.createElement(U,{width:2},R.createElement(L,{color:r},n)),R.createElement(L,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):R.createElement(L,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:i=!1}){const c="Thinking…"===e,l="Todos"===e,d="Edit"===e,u=!0===s?.isTasteFile,m=s?.tasteCategory,g=!0===s?.permissionDenied,p=!c&&t&&!u,h=!c&&!l&&!u,{name:f}=detectTerminal(),y="iTerm2"===f?"shift":"ctrl";let w,E;if(r)w="yellow",E="→";else if(o)w="red",E=a.nodejs;else if(c)w=Zn,E="✻";else if(l&&n){const e=ln(n),t=e?.every(e=>"completed"===e.status);w=t?"#22C55E":"#D4A017",E=a.nodejs}else w="#22C55E",E=a.nodejs;return R.createElement(U,null,c&&R.createElement(L,{color:w,italic:!0},E),R.createElement(U,{flexDirection:"column",marginLeft:c?1:0},R.createElement(U,null,c?R.createElement(L,{color:Zn,italic:!0},`${e} `):u?R.createElement(R.Fragment,null,R.createElement(L,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),R.createElement(L,null," ","Using your taste ",m?"package of ":"packages",m&&R.createElement(L,{bold:!0},m))):R.createElement(L,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),p&&R.createElement(L,null," ",R.createElement(Markdown,null,`(${t})`))),n&&!u&&R.createElement(U,{columnGap:1},h&&R.createElement(L,null,"⎿"," "),l?formatTodosForDisplay(n):c?R.createElement(U,{width:"100%",flexDirection:"column"},R.createElement(L,null," "),R.createElement(L,{color:Zn,wrap:"wrap",italic:!0},n)):d&&s?.oldValue&&s?.newValue?R.createElement(U,{flexDirection:"column"},(()=>{const e=i?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:g,permissionDenied:g,maxLines:e});return R.createElement(R.Fragment,null,n,r&&R.createElement(U,{marginTop:1},R.createElement(L,{dimColor:!0},"… (",o-10," more lines) (",`${y}+o to expand`,")")))})(),g&&n&&R.createElement(U,{marginTop:1},R.createElement(L,{color:"red",wrap:"wrap"},n))):R.createElement(U,{width:"100%"},R.createElement(L,{color:o?"red":"",wrap:"wrap"},i?n:R.createElement(R.Fragment,null,truncateToolOutputForDisplay(n),n.includes("\n")&&R.createElement(L,{dimColor:!0}," ","(",`${y}+o to expand`,")"))))),r&&R.createElement(U,{columnGap:1},R.createElement(L,null,"⎿"," "),R.createElement(L,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,a;return n?(o="yellow",a="→"):r?(o="red",a="✗"):(o="green",a="✓"),R.createElement(U,null,R.createElement(L,{color:o},a),R.createElement(U,{flexDirection:"column",marginLeft:1},R.createElement(U,null,R.createElement(L,{color:"gray"},"$ "),R.createElement(L,{color:o,bold:!0},e)),R.createElement(U,{columnGap:1},R.createElement(L,null,"⎿"," "),R.createElement(L,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}function SystemMessage({content:e}){return R.createElement(U,{flexDirection:"column"},R.createElement(L,{wrap:"wrap"},R.createElement(Markdown,null,e)))}function getTerminalWidth(){return process.stdout.columns||80}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage"),__name(SystemMessage,"SystemMessage"),__name(getTerminalWidth,"getTerminalWidth");var Xn=__name(()=>{const e=getTerminalWidth();return e>=70?" \n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n":e>=50?"\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n":tr},"getResponsiveCommandLogo"),er=__name(()=>getTerminalWidth()>=70?"# Welcome to Command Code. Coding Agent with taste by Langbase":"# Welcome to Command Code","getResponsiveCommandTagline"),tr="⌘ CMD\n";function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return R.createElement(U,null,R.createElement(L,{color:"red"},t?a.pointer:a.warning),R.createElement(U,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},R.createElement(L,{color:"red"},e)))}function InfoMessage({content:e}){return R.createElement(U,null,R.createElement(L,{dimColor:!0},a.info),R.createElement(U,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},R.createElement(L,{dimColor:!0},e)))}__name(ErrorMessage,"ErrorMessage"),__name(InfoMessage,"InfoMessage");var nr=R.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1})=>{const o=t?["header",...e]:e,a=er(),s=Xn();return getTerminalWidth(),R.createElement(O,{items:o,key:n,style:{width:"100%"}},e=>{if("header"===e)return R.createElement(U,{key:"header",marginBottom:1},R.createElement(pe,{name:"vice"},R.createElement(L,null,s),R.createElement(L,null,a)));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:sn(t.name||""),input:t.input,output:t.output||"",isPending:rn(t),hasError:nn(t),metadata:t.metadata,expandedOutput:r});case"bash":return R.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:rn(t),hasError:nn(t)});case"system":return R.createElement(SystemMessage,{content:t.input});case"info":return R.createElement(InfoMessage,{content:t.input});case"error":return R.createElement(ErrorMessage,{content:t.input});default:return R.createElement(R.Fragment,null)}})();return R.createElement(U,{key:t.id,marginBottom:1,width:"90%"},n)})}),rr=__name(({messages:e})=>0===e.length?null:R.createElement(U,{flexDirection:"column",marginBottom:1},R.createElement(U,{marginBottom:0},R.createElement(L,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>R.createElement(U,{key:t},R.createElement(L,{dimColor:!0},a.pointerSmall," "),R.createElement(L,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages"),or=["dim","dim2","normal","normal2","bright","bright2","brighter","brighter2","brightest","brightest","brighter2","brighter","bright2","bright","normal2","normal","dim2","dim"],ar=__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");function GlowIcon(){const[e,t]=F(0);return M(()=>{const e=setInterval(()=>{t(e=>(e+1)%or.length)},120);return()=>clearInterval(e)},[]),R.createElement(U,{paddingLeft:1,marginRight:1},R.createElement(L,{color:ar(or[e]),bold:!0},"⌘"))}__name(GlowIcon,"GlowIcon");var sr=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,a]=F(0),s=getTerminalWidth();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`}M(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),o=e>0?t:-t,s=setInterval(()=>{a(e=>{const t=e+o;return o>0&&t>=n||o<0&&t<=n?n:t})},100);return()=>clearInterval(s)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime,"formatTime");const i=s>70,c=s>40&&s<=70;return R.createElement(U,null,R.createElement(GlowIcon,null),R.createElement(U,{marginRight:1},R.createElement(L,{color:"#E4CCFF",wrap:"wrap"},e)),i?R.createElement(R.Fragment,null,R.createElement(U,{columnGap:1},R.createElement(L,{dimColor:!0},`(${formatTime(t)}`),R.createElement(L,{dimColor:!0},"•"),R.createElement(L,{color:"gray"},o.arrowDown),R.createElement(L,{dimColor:!0},`${formatToken(Math.round(r))}`),R.createElement(L,{dimColor:!0},"•"),R.createElement(U,{columnGap:1},R.createElement(L,{bold:!0,color:"gray"},"esc"),R.createElement(L,{dimColor:!0},"to interrupt)")))):c?R.createElement(U,{columnGap:1},R.createElement(L,{dimColor:!0},`(${formatToken(Math.round(r))})`)):R.createElement(R.Fragment,null))},"Status"),ir=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=F(process.cwd()),[a,s]=F([]),[i,c]=F(0),[l,d]=F(0),u=n.trim()?15:10,m=N((e,t=process.cwd())=>{if(!e.trim())return[];if(e.endsWith("/")){const n=E(t,e);try{const e=X(n),r=[];return e.forEach(e=>{const o=E(n,e);try{const e=ee(o),n=b(t,o);r.push({name:n,path:o,isDirectory:e.isDirectory()})}catch{}}),r.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),r.slice(0,50)}catch{}}if(e.includes("/")){const n=e.split("/"),r=n.pop()||"",o=E(t,n.join("/"));try{const e=X(o),n=[],a=r.toLowerCase();return e.forEach(e=>{const s=e.toLowerCase();if(!r||s.includes(a)){const r=E(o,e);try{const e=ee(r),o=b(t,r);n.push({name:o,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)),n.slice(0,50)}catch{}}const n=[],r=e.toLowerCase(),o=__name((e,a=0)=>{if(!(a>8))try{X(e).forEach(s=>{const i=E(e,s);try{const e=ee(i),c=b(t,i),l=c.toLowerCase();(s.toLowerCase().includes(r)||l.includes(r))&&n.push({name:c,path:i,isDirectory:e.isDirectory()}),e.isDirectory()&&(["node_modules"].includes(s)||o(i,a+1))}catch(e){}})}catch(e){}},"searchRecursively");return o(t),n.sort((e,t)=>{const n=e.name.toLowerCase(),o=t.name.toLowerCase(),a=n===r,s=o===r;if(a&&!s)return-1;if(!a&&s)return 1;const i=n.split("/").pop()||"",c=o.split("/").pop()||"",l=i.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)},[]),g=N(e=>{try{const t=X(e),n=[];"/"!==e&&n.push({name:"..",path:w(e),isDirectory:!0}),t.forEach(t=>{const r=E(e,t);try{const e=ee(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)),s(n),c(0),d(0)}catch{}},[]);M(()=>{if(n.trim()){const e=m(n);s(e),c(0),d(0)}else g(r)},[r,g,n,m]),B((r,s)=>{if(s.escape)t();else if(s.upArrow)c(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t});else if(s.downArrow)c(e=>{const t=Math.min(a.length-1,e+1);return t>=l+u&&d(t-u+1),t});else{if(s.rightArrow){const e=a[i];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(C(e.path)))}if(s.return){const t=a[i];if(!t)return;return void e(t.path)}}});const p=a.slice(l,l+u);return R.createElement(U,{flexDirection:"column",paddingLeft:1},R.createElement(U,{marginBottom:1,flexDirection:"column"},R.createElement(L,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),R.createElement(L,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===p.length?R.createElement(L,{color:"dim"},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):p.map((e,t)=>{const n=l+t,r=e.name;return R.createElement(L,{key:e.path,color:n===i?"white":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList");function loadCustomCommands(){const e=[],t=y.join(process.cwd(),".commandcode","commands"),n=y.join(k.homedir(),".commandcode","commands");function loadCommandsFromDirectory(t,n,r=""){if(J.existsSync(t))try{const o=J.readdirSync(t,{withFileTypes:!0});for(const a of o){const o=y.join(t,a.name);if(a.isDirectory())loadCommandsFromDirectory(o,n,r?`${r}/${a.name}`:a.name);else if(a.isFile()&&a.name.endsWith(".md")){const t=y.basename(a.name,".md"),s=J.readFileSync(o,"utf-8").trim();e.push({name:t,source:n,content:s,subdirectory:r})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(n,"user"),loadCommandsFromDirectory(t,"project"),e}function customCommandsToMenuItems(e){return e.map(e=>{const t=`/${e.name}`;let n;return n=e.subdirectory?"project"===e.source?`(project: ${e.subdirectory})`:`(user: ${e.subdirectory})`:"project"===e.source?"(project)":"(user)",{command:t,description:`${e.content.length>60?`${e.content.substring(0,57)}...`:e.content} ${n}`}})}function getCustomCommandContent(e){const t=loadCustomCommands(),n=e.startsWith("/")?e.substring(1):e,r=t.find(e=>e.name===n);return r?r.content:null}__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent");var cr=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/clear (reset, new)",description:"Clear the conversation history"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/agents",description:"Manage agent configurations"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/compact",description:"Compact the conversation history"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"}],lr=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=F(0),[a,s]=F(0),i=_(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...cr];if(!n)return e;const t=n.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let o=0;return n.startsWith("/"+t)?o+=100:n.includes(t)&&(o+=50),r.includes(t)&&(o+=25),{...e,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]),c=_(()=>{const e=a,t=Math.min(e+8,i.length);return i.slice(e,t)},[i,a]);return M(()=>{o(0),s(0)},[n]),B((n,c)=>{if(c.escape)t();else if(c.upArrow)o(e=>{const t=Math.max(0,e-1);return t<a&&s(t),t});else if(c.downArrow)o(e=>{const t=Math.min(i.length-1,e+1);return t>=a+8&&s(Math.max(0,t-8+1)),t});else if(c.return){const t=i[r];return void(t&&e(t.command))}}),0===i.length?R.createElement(U,{flexDirection:"column",paddingLeft:2},R.createElement(L,{color:"dim"},"No commands found")):(i.length,R.createElement(U,{flexDirection:"column",paddingLeft:1},R.createElement(U,{columnGap:4},R.createElement(U,{flexDirection:"column"},c.map((e,t)=>{const n=a+t;return R.createElement(L,{key:e.command,color:r===n?"white":"dim"},e.command)})),R.createElement(U,{flexDirection:"column"},c.map((e,t)=>{const n=a+t;return R.createElement(L,{key:e.command,color:r===n?"white":"dim"},e.description)})))))},"CommandMenu"),dr=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=F([]),[o,s]=F(0),[i,c]=F(!0);M(()=>{l()},[]);const l=__name(async()=>{c(!0);const e=await jn.listSessions();r(e.slice(0,30)),c(!1)},"loadSessions");if(B((r,a)=>{a.escape?t():a.upArrow?s(e=>Math.max(0,e-1)):a.downArrow?s(e=>Math.min(n.length-1,e+1)):a.return&&n.length>0&&o<n.length&&e(n[o].id)}),i)return R.createElement(U,{flexDirection:"column",paddingLeft:2},R.createElement(L,{color:"gray"},"Loading sessions..."));if(0===n.length)return R.createElement(U,{flexDirection:"column",paddingLeft:2},R.createElement(L,{color:"gray"},"No previous sessions found"),R.createElement(L,{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),a=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${a}d ago`},"formatRelativeTime"),u=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return R.createElement(U,{flexDirection:"column",paddingLeft:1,width:"100%"},R.createElement(L,{color:"cyan",bold:!0},"Resume Session"),R.createElement(L,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),R.createElement(U,{marginTop:1}),R.createElement(U,{columnGap:2,marginBottom:1},R.createElement(U,{width:5},R.createElement(L,{color:"gray"}," ")),R.createElement(U,{width:13},R.createElement(L,{color:"gray"},"Modified")),R.createElement(U,{width:20},R.createElement(L,{color:"gray"},"Git Branch")),R.createElement(U,{width:11},R.createElement(L,{color:"gray"},"# Messages")),R.createElement(U,null,R.createElement(L,{color:"gray"},"Summary"))),R.createElement(U,{columnGap:2},R.createElement(U,{flexDirection:"column",width:5},n.map((e,t)=>R.createElement(L,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${a.pointer} ${t+1}.`:` ${t+1}.`))),R.createElement(U,{flexDirection:"column",width:13},n.map((e,t)=>R.createElement(L,{key:`mod-${e.id}`,color:o===t?"white":"gray"},d(e.lastModified)))),R.createElement(U,{flexDirection:"column",width:20},n.map((e,t)=>R.createElement(L,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),R.createElement(U,{flexDirection:"column",width:11},n.map((e,t)=>R.createElement(L,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),R.createElement(U,{flexDirection:"column"},n.map((e,t)=>R.createElement(L,{key:`summary-${e.id}`,color:o===t?"white":"gray"},u(e.firstMessage))))))},"SessionsResumeTable"),ur=__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(U,{paddingRight:1},R.createElement(L,{color:r(n),dimColor:!0},n.toFixed(1),"% context used (",t(e.current),"/",t(e.limit),")"))},"ContextUsage"),mr=__name(()=>R.createElement(U,{flexDirection:"column",paddingLeft:1},R.createElement(L,{color:"dim",bold:!0},"Available Shortcuts:"),R.createElement(U,{columnGap:4},R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"dim"},"! for bash mode"),R.createElement(L,{color:"dim"},"/ for commands"),R.createElement(L,{color:"dim"},"@ for file paths")),R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"dim"},"double tap esc to clear input"),R.createElement(L,{color:"dim"},"shift + ⏎ for newline"),R.createElement(L,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),gr=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:i,fileSearchQuery:c,setFileSearchQuery:l,onCommand:d,contextUsage:u,tasteLearning:m=!1,tasteUsage:g=!1,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,updateStatus:w,updateFailedInfo:E,currentProvider:v,showProviderInfo:C,isOAuthMode:T=!1,autoAcceptMode:k=!1})=>{const[A,P]=F(0),[S,x]=F(!1),[$,I]=F(!1),[D,M]=F(!1),[O,W]=F(!1),[z,G]=F(""),[q,H]=F(!1),[J,K]=F(null),[Y,Q]=F([]),[Z,X]=F([]),[ee,te]=F(""),[ne,re]=F(""),oe=j(!1),[ae,se]=F(!1),ie=N(()=>{n(""),I(!1),W(!1),G(""),H(!1),Q([]),X([]),te(""),se(!1),P(e=>e+1)},[n]),ce=N(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)},[]),le=N(()=>{const t=ce(e);n(t),P(e=>e+1)},[e,ce,n]);B(async(t,r)=>{if(getIsExpandToolShortcut(r,t))return oe.current=!0,n(e),void P(e=>e+1);if(!r.ctrl&&!r.meta&&!r.shift){if(""===t)return void ie();if(""===t)return void le()}if(r.meta&&r.delete)return oe.current=!0,void le();if(r.meta&&r.backspace)ie();else if(r.alt&&r.backspace)le();else{if(r.ctrl&&"w"===t)return oe.current=!0,void le();if(r.meta&&"w"===t)return oe.current=!0,void ie();if(r.meta&&"v"===t||r.ctrl&&"v"===t){if(r.ctrl&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();if(r){const e=`[Image#${Z.length+1}]`;X(e=>[...e,r]),n(t+e),P(e=>e+1)}return void(oe.current=!0)}}else{if((r.ctrl||r.meta)&&"u"===t)return oe.current=!0,void ie();if(r.ctrl&&t)switch(t.toLowerCase()){case"k":case"a":return void ie();case"z":return M(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100)}if(r.escape){if(q)return H(!1),n(ee),void P(e=>e+1);const e=Date.now(),t=500;return J&&e-J<t?(ie(),K(null)):(K(e),setTimeout(()=>K(null),t)),x(!1),void I(!1)}S&&(r.backspace||r.delete)&&0===e.length&&x(!1)}}});const de=N(async t=>{const r=processBracketedPaste(t);if(r.isPasteStart&&!ae){if(se(!0),re(e),!r.isPasteEnd)return;se(!1);const t=await detectClipboardImage();if(t){const r=`[Image#${Z.length+1}]`;X(e=>[...e,t]),n(e+r),P(e=>e+1)}else{const e=await detectClipboardText();if(e)if(e.length>100){const t=`[Text#${Y.length+1}]`;Q(t=>[...t,e]),n(ne+t),P(e=>e+1)}else n(ne+e),P(e=>e+1)}return}if(ae&&!r.isPasteEnd)return;if(ae&&r.isPasteEnd){se(!1);const e=await detectClipboardImage();if(e){const t=`[Image#${Z.length+1}]`;X(t=>[...t,e]),n(r.cleanedContent+t),P(e=>e+1)}else{const e=await detectClipboardText();if(e)if(e.length>100){const t=`[Text#${Y.length+1}]`;Q(t=>[...t,e]),n(ne+t),P(e=>e+1)}else n(ne+e),P(e=>e+1)}return}if(r.isPasteEnd&&!r.isPasteStart)return;if(oe.current)return void(oe.current=!1);const o=1===t.length,a=t.slice(-1);if(o){if("?"===a&&!S)return x(!0),n(""),void P(e=>e+1);if("!"===a&&!$)return x(!1),I(!0),n(""),void P(e=>e+1);"/"!==a||O||(W(!0),G(""))}if(O){const e=t.lastIndexOf("/");if(-1!==e){const n=t.substring(e+1);G(n)}}"@"!==a||s||(i(!0),l(""));const c=t.lastIndexOf("@");if(t.length<e.length&&-1!==c&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(c+1);!e.includes(" ")&&(i(!0),l(e))}if(s)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),l("");else{const n=t.substring(e+1);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),i(!1)}else l(n)}}S&&(t!==e||t.length<e.length)&&x(!1),0===t.length&&(I(!1),W(!1),G(""),H(!1),X([]),Q([]),l(""),te(""),se(!1)),n(t)},[S,e,n,s,i,$,ae,Z]),ue=N(async()=>{if(S)return void x(!1);let n=e.trim(),r=[];const o=Z.length>0,a=Y.length>0;if(!$&&o){const e=[];Z.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!$&&a){let e=n;Y.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:$?"bash":"user",images:r}),I(!1),W(!1),G(""),X([]),Q([])},[t,S,e,$,Z]),me=N(t=>{const r=b(process.cwd(),t);let o;if(s&&""!==c){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),i(!1),l(""),P(e=>e+1)},[n,i,e,s,c,l]),ge=N(()=>{i(!1),l("")},[i,l]),pe=N(t=>{"/resume"===t?(te(e),W(!1),G(""),H(!0),n(""),P(e=>e+1)):(W(!1),G(""),n(""),P(e=>e+1),d&&d(t))},[d,n,e]),he=N(()=>{W(!1),G(""),n(""),P(e=>e+1)},[n]),fe=N(e=>{H(!1),n(""),te(""),P(e=>e+1),d&&d(`/resume:${e}`)},[d]),ye=N(()=>{H(!1),n(ee),P(e=>e+1)},[ee]),we=_(()=>!S&&0===e.length&&!$&&!q,[S,e,$,O,q]),Ee=__name(()=>S||s||O||q||D?0:we||$?3:4,"getBottomMargin");return R.createElement(U,{width:"100%",flexDirection:"column",marginBottom:Ee()},!q&&R.createElement(U,{borderStyle:"round",borderRight:!1,borderLeft:!1,borderColor:$?"green":"gray",paddingY:0,width:"100%"},R.createElement(L,{color:$?"green":"dim"},$?"!":a.pointer),R.createElement(U,{flexGrow:1,paddingLeft:1},R.createElement(V,{key:A,value:e,placeholder:o,onChange:de,onSubmit:()=>{s||O||q||ue()},showCursor:r}))),S&&R.createElement(mr,null),D&&R.createElement(U,{paddingTop:1},R.createElement(L,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),s&&R.createElement(ir,{onSelectFile:me,onClose:ge,searchQuery:c}),O&&R.createElement(lr,{onSelectCommand:pe,onClose:he,searchQuery:z}),q&&R.createElement(dr,{onSelectSession:fe,onClose:ye}),we&&R.createElement(U,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1},R.createElement(U,null,k?R.createElement(U,{flexDirection:"row"},R.createElement(L,{color:"#E4CCFF"},"» accept edits on "),R.createElement(L,{dimColor:!0},"(shift+tab to toggle)")):R.createElement(L,{color:"dim"},"? for shortcuts")),R.createElement(U,{flexDirection:"row",columnGap:1},w&&R.createElement(U,null,R.createElement(L,null,R.createElement(L,null,a.tick," ","Command Code"," updated:"," "),R.createElement(L,{dimColor:!0},"v",w.updatedFrom),R.createElement(L,{dimColor:!0}," ",a.arrowRight," "),R.createElement(L,null,"v",w.updatedTo))),!w&&E&&R.createElement(R.Fragment,null,R.createElement(U,null,R.createElement(L,{color:"yellow",dimColor:!0},a.info," Update available:"," ",E.currentVersion," ",a.arrowRight," ",E.latestVersion)),(v||m||g||u)&&R.createElement(U,{marginLeft:1,marginRight:1},R.createElement(L,{dimColor:!0,color:"gray"},"•"))),C&&v&&R.createElement(R.Fragment,null,R.createElement(U,null,R.createElement(L,{color:"green",dimColor:!0},`${a.bullet} Provider: ${getProviderDisplayName(v)}`)),(u||T)&&R.createElement(U,{marginLeft:1,marginRight:1},R.createElement(L,{dimColor:!0,color:"gray"},"•"))),T&&R.createElement(R.Fragment,null,R.createElement(U,null,R.createElement(L,{color:"yellow",dimColor:!0},"internal mode (oauth)")),u&&R.createElement(U,{marginLeft:1,marginRight:1},R.createElement(L,{dimColor:!0,color:"gray"},"•"))),R.createElement(ur,{usage:u||null}))),$&&R.createElement(U,{paddingLeft:1},R.createElement(L,{color:"green"},"! for bash mode")),h&&p&&R.createElement(U,{paddingLeft:1},R.createElement(L,{color:"#E4CCFF"},"SHARED: ",p.url," (copied to clipboard)")),f&&R.createElement(U,{paddingLeft:1},R.createElement(L,{color:f.includes("NOT SHARED")?"red":"#E4CCFF"},f)),y&&R.createElement(U,{paddingLeft:1},R.createElement(L,{color:"#E4CCFF"},y)))},"InputBox"),pr=__name(()=>{const[e,t]=F("continuous learning"),n=j([]),r=j(0),o=j(null),a=j(!1);M(()=>{const e=__name(e=>"analyzing"===e.type?(a.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):a.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(a.current=!1,void(n.current.length>0?(r.current=0,s()):t("continuous learning"))):void 0,"handleNewEvent"),s=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const a="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,s()},a)},"cycleThroughNextEvent");return Vn.on("new-event",e),()=>{Vn.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const s=9+e.length+19>100;let i=e;if(s){const t=100;e.length>t&&(i=e.substring(0,t-3)+"...")}else{const t=72;e.length>t&&(i=e.substring(0,t-3)+"...")}return R.createElement(U,null,!s&&R.createElement(L,{color:"green"},"● taste: "),R.createElement(L,null,i),!s&&R.createElement(L,{dimColor:!0}," (ctrl+t to expand)"))},"LearningFeedMini"),hr=R.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:a,onSubmit:s,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:v,currentProvider:C,showProviderInfo:T,isOAuthMode:k,autoAcceptMode:A})=>{const[P,S]=F(0);return M(()=>{if(!t)return void S(0);const e=setInterval(()=>{S(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),R.createElement(U,{flexDirection:"column"},R.createElement(rr,{messages:e}),R.createElement(U,{flexDirection:"row",justifyContent:"space-between"},R.createElement(U,null,(t||n.isExecuting)&&R.createElement(sr,{tokens:m,timeElapsed:P,status:n.isExecuting?`Executing: ${n.currentCommand}`:r})),R.createElement(U,null,p&&R.createElement(pr,null))),R.createElement(gr,{input:o,setInput:a,onSubmit:s,placeholder:"Ask your question...",showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:v,currentProvider:C,showProviderInfo:T,isOAuthMode:k,autoAcceptMode:A}))}),fr=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=z(),[r,o]=F([]),[s,i]=F(0),[c,l]=F(!0),[d,u]=F(0),m=30;M(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await jn.listSessions();o(e),l(!1)},"loadSessions");if(B((t,o)=>{o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t}):o.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=d+m&&u(t-m+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),c)return R.createElement(U,{flexDirection:"column",paddingLeft:2,paddingTop:1},R.createElement(L,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),a=Math.floor(n/864e5),s=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:a<7?`${a} day${a>1?"s":""} ago`:1===s?"1 week ago":`${s} weeks ago`},"formatRelativeTime"),h=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"gray"},"No sessions available"));const f=r.slice(d,d+m),y=d;return R.createElement(U,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&R.createElement(U,{marginBottom:1},R.createElement(L,{color:"dim"},"Showing ",d+1,"-",Math.min(d+m,r.length)," ","of ",r.length," sessions",d>0&&" (↑ for more)",d+m<r.length&&" (↓ for more)")),R.createElement(U,{columnGap:2,marginBottom:1},R.createElement(U,{width:7},R.createElement(L,{color:"gray"}," ")),R.createElement(U,{width:13},R.createElement(L,{color:"gray"},"Modified")),R.createElement(U,{width:11},R.createElement(L,{color:"gray"},"# Messages")),R.createElement(U,{width:20},R.createElement(L,{color:"gray"},"Git Branch")),R.createElement(U,null,R.createElement(L,{color:"gray"},"Summary"))),R.createElement(U,{columnGap:2},R.createElement(U,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${a.pointer} ${n+1}.`:` ${n+1}.`)})),R.createElement(U,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`mod-${e.id}`,color:s===n?"white":"gray"},p(e.lastModified))})),R.createElement(U,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),R.createElement(U,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),R.createElement(U,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`summary-${e.id}`,color:s===n?"white":"gray"},h(e.firstMessage))}))))},"SessionTable");function RetryMessage({attempt:e}){const[t,n]=F(0);if(M(()=>{if(null===e)return;const t=setInterval(()=>{n(e=>(e+1)%4)},500);return()=>clearInterval(t)},[e]),null===e)return null;const r=".".repeat(t).padEnd(3," ");return R.createElement(U,{marginBottom:1},R.createElement(L,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}__name(RetryMessage,"RetryMessage");var yr=__name(({onTrust:e,onExit:t})=>{const{exit:n}=z(),[r,o]=F(1),s=process.cwd().replace(process.env.HOME||"","~");return B((a,s)=>{s.upArrow||s.downArrow?o(1===r?2:1):s.return?1===r?e():(t(),n()):"1"===a?e():("2"===a||s.escape||s.ctrl&&"c"===a)&&(t(),n())}),R.createElement(U,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1},R.createElement(L,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),R.createElement(U,{marginTop:1},R.createElement(L,{color:"gray"},s)),R.createElement(U,{marginTop:1,flexDirection:"column"},R.createElement(L,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),R.createElement(U,{marginTop:1},R.createElement(L,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),R.createElement(U,{marginTop:1,flexDirection:"column"},R.createElement(U,null,R.createElement(L,{color:1===r?"cyan":"gray"},1===r?a.pointer:" "," 1. Yes, proceed")),R.createElement(U,null,R.createElement(L,{color:2===r?"cyan":"gray"},2===r?a.pointer:" "," 2. No, exit"))))},"TrustPrompt"),wr=class extends me{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||y.join(e,".commandcode","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 P.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.autoApprove&&(void 0!==t.permissions.autoApprove.create&&(this.config.autoApprove.create=t.permissions.autoApprove.create),void 0!==t.permissions.autoApprove.update&&(this.config.autoApprove.edit=t.permissions.autoApprove.update),void 0!==t.permissions.autoApprove.delete&&(this.config.autoApprove.delete=t.permissions.autoApprove.delete)),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=y.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=y.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?Array.isArray(e.args)?e.args.join(" "):e.args:""}`.trim()}isTrustedCommand(e){return!!["ls","ls -la","ls -l","ls -R","pwd","grep","tree","find","stat","file","dirname","basename","grep","git status","git log","git diff","git branch"].some(t=>e===t||!!e.startsWith(t+" "))||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=y.join(this.projectRoot,".commandcode"),t=y.join(e,"settings.local.json");try{await P.mkdir(e,{recursive:!0});let n={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await P.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 P.writeFile(t,JSON.stringify(n,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const t=y.join(this.projectRoot,".commandcode"),n=y.join(t,"settings.local.json"),r=`Bash(${e.split(" ")[0]}:*)`;try{let e;await P.mkdir(t,{recursive:!0});try{const t=await P.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 P.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},Er=__name((e={})=>{const[t,n]=F(null),[r,o]=F(null),[a,s]=F(!1);return M(()=>{const t=e.projectRoot||process.cwd(),r=new wr(t);return r.on("permission-request",(t,n)=>{o(t),s(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),s(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:N(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:N(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:N(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),s(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),s(!1)}},[t]),clearSessionPermissions:N(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:N(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:N((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:N(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:a,service:t}},"usePermissions"),br=__name(({request:e,onResponse:t})=>{const[n]=F(0),r=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, for this session only",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],o=__name(e=>{const n=r.find(t=>t.value===e.value);n&&t(n)},"handleSelect"),s=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),i=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const t=y.basename(e.filePath),n=y.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(U,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0,color:"yellow"},`${c()} ${"edit"===e.action?i():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&R.createElement(U,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:i(),marginLeft:0}).diffContent),R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0},"Do you want to ",s()," ",R.createElement(L,{color:"cyan"},i()),"?")),R.createElement(Ee,{items:r.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:"cyan"},e?a.pointer:" "),itemComponent:({label:e,isSelected:t})=>R.createElement(L,{color:t?"cyan":"white"},e.includes("(")?R.createElement(R.Fragment,null,e.split("(")[0],R.createElement(L,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),vr=__name(({request:e,onResponse:t})=>{const[n]=F(0),r=[{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:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],o=__name(e=>{const n=r.find(t=>t.value===e.value);n&&t(n)},"handleSelect"),s=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"",n=t?`${e.command} ${t}`:e.command;return n.length>60?n.substring(0,57)+"...":n},"getCommandDisplay");return R.createElement(U,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0,color:"yellow"},"Execute Shell Command")),R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0},"Command Code needs to execute ",R.createElement(L,{color:"cyan"},s()),".")),e.workingDirectory&&R.createElement(U,{marginBottom:1},R.createElement(L,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&R.createElement(U,{marginBottom:1},R.createElement(L,{color:"gray",italic:!0},e.description)),R.createElement(Ee,{items:r.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:"cyan"},e?a.pointer:" "),itemComponent:({label:e,isSelected:t})=>R.createElement(L,{color:t?"cyan":"white"},e)}))},"ShellPermissionPrompt"),Cr=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole"),Tr=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=F(!1),[a,s]=F(!0);M(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{s(!1)}},"loadSettings")()},[]),B((t,n)=>{if(!n.return&&" "!==t)return n.escape?(Cr(),void e()):void 0;i()});const i=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return a?R.createElement(U,{key:n,borderStyle:"round",borderColor:"blue",padding:1,flexDirection:"column"},R.createElement(L,{color:"blue",bold:!0},"Taste Settings"),R.createElement(L,{dimColor:!0},"Loading configuration...")):R.createElement(U,{key:n,borderStyle:"round",borderColor:"gray",padding:1,flexDirection:"column"},R.createElement(L,{bold:!0},"Taste Learning"),R.createElement(L,{dimColor:!0},"Configure taste learning preferences for this project"),R.createElement(U,{marginTop:1}),R.createElement(U,{justifyContent:"space-between"},R.createElement(L,null,"Taste learning",R.createElement(L,{dimColor:!0}," - Learn from your interactions")),R.createElement(L,{color:r?"green":"gray"},r?"enabled":"disabled")),R.createElement(U,{marginTop:1}),R.createElement(L,{dimColor:!0},"Taste data stored in .commandcode/taste/"),R.createElement(L,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig"),kr=__name(({onClose:e})=>{const[t,n]=F(Vn.getEvents());B((t,n)=>{n.ctrl&&"t"===t&&(Cr(),e())},{isActive:!0}),M(()=>{const e=__name(()=>{n(Vn.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return Vn.on("new-event",e),Vn.on("cleared",t),()=>{Vn.off("new-event",e),Vn.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored","updated"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase(),n=t[2],r={learned:"Learned",upgraded:"Reinforced",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:r,content:n}}return{type:null,label:null,content:e}},"formatLearningMessage"),s=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),i=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails");return R.createElement(U,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},R.createElement(U,{flexDirection:"column",marginBottom:1},R.createElement(pe,{name:"vice"},R.createElement(L,null,Xn()),R.createElement(L,null,er()))),R.createElement(U,{marginBottom:1,width:"100%",justifyContent:"space-between"},R.createElement(U,null,R.createElement(L,{bold:!0},"Learning Feed"),R.createElement(L,{dimColor:!0}," - Real-time taste learning activity")),R.createElement(L,{dimColor:!0},"Press ctrl+t to close")),R.createElement(U,{flexDirection:"column"},0===t.length?R.createElement(U,null,R.createElement(L,{dimColor:!0},"No learning events yet...")):R.createElement(U,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r}=o(e.message),a="moved"===t?i(e.details):null,c="upgraded"===t?s(r):null;return R.createElement(U,{key:e.id,marginBottom:1},R.createElement(U,{flexDirection:"column"},R.createElement(U,null,R.createElement(L,{backgroundColor:"green",color:"#FFFFFF",bold:!0},` ${n} `),a?R.createElement(L,{dimColor:!0}," (",a.fullPath,")"):e.details?R.createElement(L,{dimColor:!0}," (",e.details,")"):null),R.createElement(U,null,R.createElement(L,{dimColor:!0},"⎿"," "),a?R.createElement(R.Fragment,null,R.createElement(L,null,a.category," package ("),R.createElement(L,{dimColor:!0},a.oldPath),R.createElement(L,null," → ",a.newPath),R.createElement(L,null,")")):c?R.createElement(R.Fragment,null,R.createElement(L,null,c.text," ("),R.createElement(L,{dimColor:!0},c.oldPercent,"%"),R.createElement(L,null," → "),R.createElement(L,{color:c.diff>0?"green":"red"},c.newPercent,"%"),R.createElement(L,null,")")):R.createElement(L,null,r))))}return R.createElement(U,{key:e.id,marginBottom:1},R.createElement(L,{dimColor:!0},a.pointerSmall," ",e.message))}))))},"LearningFeedFull"),Ar=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");B((e,n)=>{n.escape&&t()});const a=n?r.findIndex(e=>e.value===n):0,s=n&&-1===a;return R.createElement(U,{flexDirection:"column",paddingX:0,width:"100%"},R.createElement(U,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},R.createElement(U,null,R.createElement(L,{bold:!0},"Select AI Provider")),n&&R.createElement(U,{flexDirection:"row"},R.createElement(L,{dimColor:!0},"Current: "),R.createElement(L,{color:"green"},getProviderDisplayName(n)),s&&R.createElement(L,{color:"yellow"}," [OAuth enforced]"))),R.createElement(U,{marginBottom:0},R.createElement(L,{dimColor:!0},"Available Providers:")),R.createElement(Ee,{items:r,onSelect:o,initialIndex:a>=0?a:0,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"cyan":"gray",bold:e},` ${t}`)}),R.createElement(U,{marginTop:1},R.createElement(L,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector"),Pr=__name(({onClose:e})=>{const[t,n]=F([]),[r,o]=F(0),[a,s]=F(!0),[i,c]=F(null);M(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),s(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),s(!1)}},"loadMemoryFiles")()},[]);const l=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(B((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&l(d[r]),"1"===t&&d[0]&&l(d[0]),"2"===t&&d[1]&&l(d[1]))}),a)return R.createElement(U,{paddingLeft:1,paddingTop:1},R.createElement(L,{color:"dim"},"Loading memory files..."));if(i)return R.createElement(U,{paddingLeft:1,paddingTop:1},R.createElement(L,{color:"red"},"❌ ",i));const u=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return R.createElement(U,{flexDirection:"column",width:"100%",borderStyle:"round",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},R.createElement(U,null,R.createElement(L,{color:"white",bold:!0},"Select memory to edit:")),R.createElement(U,{columnGap:4,marginTop:1},R.createElement(U,{flexDirection:"column"},u.map((e,t)=>R.createElement(L,{key:t,color:r===t?"white":"dim"},r===t?"> ":" ",e.label))),R.createElement(U,{flexDirection:"column"},u.map((e,t)=>R.createElement(L,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector"),Sr=class{static{__name(this,"TasteManager")}static async initializeProject(){const e=process.cwd(),t=f.join(e,".commandcode","taste");await A.mkdir(t,{recursive:!0});const n=f.join(t,"taste.md");try{await A.access(n)}catch{await A.writeFile(n,"# Taste (Continuously Learned by CommandCode)\n\n")}}static async isInitialized(){const e=process.cwd(),t=f.join(e,".commandcode","taste");try{return await A.access(t),!0}catch{return!1}}},xr=__name(({staticKey:e})=>R.createElement(O,{items:[{staticKey:e}],key:e},()=>R.createElement(L,{key:e},"\0")),"Responsive"),$r=__name(()=>y.join(k.homedir(),".commandcode","agents"),"getRootAgentDir"),Ir=__name(()=>y.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Dr=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=F("idle"),[a,s]=F(""),i=[...Un.map(e=>e.name),...Ln.map(e=>e.name)],c=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void s("Agent configuration is incomplete");o("saving");try{const n="personal"===e.location?$r():Ir();await P.mkdir(n,{recursive:!0});const r=`${e.agentType}.md`,o=y.join(n,r),a=Array.from(e.selectedTools).map(e=>Wn[e]||e).join(", "),s=0===e.selectedTools.size?"none":e.selectedTools.size===i.length?'"*"':JSON.stringify(a),c=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${s}\n---\n\n${e.sysPrompt}\n`;await P.writeFile(o,c,"utf-8"),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),s(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");B((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||c()});const l=Array.from(e.selectedTools).map(e=>Wn[e]||e).join(", "),d="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return R.createElement(U,{flexDirection:"column",gap:1},R.createElement(U,{flexDirection:"column"},R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"Name:"),R.createElement(L,{color:"gray"},e.agentType)),R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"Location:"),R.createElement(L,{color:"gray"},d)),R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"Tools:"),R.createElement(L,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===i.length?"*":l))),R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"Description"),R.createElement(L,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),R.createElement(L,{color:"gray"},e.ccToolDefinition),R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"System Prompt:")),R.createElement(L,{color:"gray"},e.sysPrompt),!n&&R.createElement(U,{marginTop:1},"idle"===r&&R.createElement(U,{gap:1},R.createElement(L,{color:"green",dimColor:!0},"Press"),R.createElement(L,{color:"green",bold:!0},"Enter"),R.createElement(L,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===r&&R.createElement(L,{color:"yellow"},"Saving agent..."),"saved"===r&&R.createElement(L,{color:"green"},"✓ ",a),"error"===r&&R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"red"},"✗ Error: ",a),R.createElement(L,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),Rr=__name(({agent:e,onBack:t,setRevalidateAgent:n})=>{const[r,o]=F("menu"),a=[...Un.map(e=>e.name),...Ln.map(e=>e.name)];let s=new Set;if("*"===e.tools||'"*"'===e.tools)s=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>zn[e]||e);s=new Set(t)}const i={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:s},c=__name(e=>{"back"===e.value?t():"view"===e.value?o("view"):"edit"===e.value?o("edit"):"delete"===e.value&&o("delete")},"handleMenuSelect");if(B((e,n)=>{n.escape&&("menu"===r?t():o("menu")),n.return&&"view"===r&&o("menu")}),"view"===r)return R.createElement(U,{flexDirection:"column"},R.createElement(Dr,{config:i,onSaveComplete:()=>o("menu"),viewOnly:!0}),R.createElement(U,{marginTop:1},R.createElement(L,{color:"gray"},"Press Enter to go back")));if("edit"===r)return R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"yellow"},"Edit functionality coming soon..."),R.createElement(L,{color:"gray"},"Press Esc to go back"));if("delete"===r){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],a=__name(async r=>{if("confirm-delete"===r.value)try{await P.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return R.createElement(U,{flexDirection:"column",gap:1},R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"red"},"Delete agent"),R.createElement(L,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),R.createElement(U,null,R.createElement(Ee,{items:r,onSelect:a,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"white":"gray"},` ${t}`)})))}return R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"white",bold:!0},e.name),R.createElement(U,{marginTop:1},R.createElement(Ee,{items:[{label:"1. View agent",value:"view"},{label:"2. Delete agent",value:"delete"},{label:"3. Back",value:"back"}],onSelect:c,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"white":"gray"},` ${t}`)})),R.createElement(U,{marginTop:1},R.createElement(L,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Fr=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=F([]),[o,a]=F([]),[s,i]=F(!0),[c,l]=F(!1),[d,u]=F(null),[m,g]=F(!1),p=__name(()=>y.join(k.homedir(),".commandcode","agents"),"getRootAgentDir"),h=__name(()=>y.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),f=__name(async(e,t)=>{try{l(!1);const n=(await P.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=y.join(e,n),o=await P.readFile(r,"utf-8"),{data:a,content:s}=le(o);let i=a.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:a.name||n.replace(".md",""),description:a.description||"",tools:i,sysPrompt:s.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");M(()=>{__name(async()=>{i(!0);const[e,t]=await Promise.all([f(p(),"personal"),f(h(),"project")]);r(e),a(t),i(!1)},"loadAgents")()},[c]);const w=[{label:"Create new agent",value:"create_new_agent"}];n.forEach(e=>{w.push({label:e.name,value:e.filePath})}),o.forEach(e=>{w.push({label:e.name,value:e.filePath})});const E=n.length>0||o.length>0,b=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...n,...o].find(e=>e.filePath===t.value);e&&(u(e),g(!0))}},"handleAgentSelect");if(s)return R.createElement(L,{color:"gray"},"Loading agents...");if(m&&d)return R.createElement(Rr,{agent:d,onBack:()=>{g(!1),u(null)},setRevalidateAgent:l});const v=__name(({isSelected:e,label:t})=>{const r=w.find(e=>e.label===t),a=r?.value||"",s=n[0]?.filePath===a,i=o[0]?.filePath===a;return R.createElement(U,{flexDirection:"column"},s&&n.length>0&&R.createElement(U,{marginTop:1,marginLeft:2},R.createElement(L,{color:"white"},"User agents (~/",".commandcode","/","agents",")")),i&&o.length>0&&R.createElement(U,{marginTop:1,marginLeft:2},R.createElement(L,{color:"white"},"Project agents")),R.createElement(U,null,R.createElement(L,{color:"white"},e?">":" "),R.createElement(L,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return R.createElement(U,{flexDirection:"column"},R.createElement(U,{flexDirection:"column",marginBottom:1},R.createElement(L,{color:"white",bold:!0},"Agents"),E?R.createElement(L,{color:"gray"},n.length+o.length," agents"):R.createElement(L,{color:"gray"},"No agents found")),t&&R.createElement(U,{flexDirection:"column",marginBottom:1},R.createElement(L,{color:"green",dimColor:!0},"Created agent: ",t)),R.createElement(Ee,{items:w,onSelect:b,indicatorComponent:()=>null,itemComponent:v}),!E&&R.createElement(U,{flexDirection:"column",marginTop:1},R.createElement(L,{color:"gray"},"No agents found. Create specialized subagents that Command Code can delegate to."),R.createElement(L,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools."),R.createElement(L,{color:"gray"},"Try creating: Code Reviewer, Code Simplifier, Security Reviewer, Tech Lead, or UX Reviewer.")))},"ManageAgents"),Mr=__name(({onSelect:e})=>R.createElement(Ee,{items:[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>R.createElement(L,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector"),jr=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:a,onCCToolDefinitionChange:s,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=F(!1),[m,g]=F(!1),p=N(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[d,a]),h=N(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||m){if(!m||t.isPasteEnd){if(m&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[m,s]);return"agentType"===e?R.createElement(R.Fragment,null,R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(Wn).some(e=>ue(e)===ue(t))||Object.keys(Wn).some(e=>ue(e)===ue(t)))&&R.createElement(L,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name.")),R.createElement(V,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=ue(t);Object.values(Wn).some(t=>ue(t)===e)||Object.keys(Wn).some(t=>ue(t)===e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?R.createElement(R.Fragment,null,R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"white"},"Enter the system prompt for your agent:"),R.createElement(L,{color:"gray"},"Be comprehensive for best results.")),R.createElement(V,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?R.createElement(R.Fragment,null,R.createElement(L,{color:"white"},"When should ","Command Code"," use this agent?"),R.createElement(V,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&l()},onChange:h,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow"),Nr=__name(({onSelect:e})=>R.createElement(Ee,{items:[{label:"1. Generate with Command Code (recommended)",value:"recommended"},{label:"2. Manual configuration",value:"manual"}],onSelect:t=>{"recommended"!==t.value&&"manual"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>R.createElement(L,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector"),_r=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=F(!1),[c,l]=F(0),d=N(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[s,t]);return R.createElement(U,{flexDirection:"column"},r?R.createElement(U,null,R.createElement(GlowIcon,null),R.createElement(L,{color:"white"},"Generating agent from description...")):R.createElement(V,{key:c,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:d,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&R.createElement(U,{marginTop:1},R.createElement(L,{color:"red"},`${a.warning} ${o}`)))},"RecommendedFlow"),Or=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,a]=F(!1),[s,i]=F(0),c=_(()=>[...Un.map(e=>e.name),...Ln.map(e=>e.name)],[]),l=_(()=>[{name:"All tools",tools:c},{name:"Read-only tools",tools:c.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:c.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:c.filter(e=>"shell_command"===e)},{name:"Search tools",tools:c.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:c.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[c]),d=_(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),c.forEach(t=>{e.push({type:"tool",value:t})})):(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,l,e,c]),u=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=l.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${o?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${Wn[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),m=u.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return B((e,c)=>{if(c.upArrow)i(e=>{const t=e-1;return t<0?m.length-1:t});else if(c.downArrow)i(e=>{const t=e+1;return t>=m.length?0:t});else if(c.return||" "===e){const e=m[s];if(e){const s=d[e.value];if(!s)return;"continue"===s.type?r():"toggle"===s.type?(a(!o),i(0)):"category"===s.type?n(s.value):"tool"===s.type&&t(s.value)}}}),R.createElement(U,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===s;if("divider"===e.type)return R.createElement(U,{key:`divider-${t}`},R.createElement(L,{color:"gray"}," ",e.label));if("spacer"===e.type)return R.createElement(U,{key:`spacer-${t}`,height:1});if("label"===e.type)return R.createElement(U,{key:`label-${t}`},R.createElement(L,{color:"gray"}," ",e.label));const o="continue"===e.type;return R.createElement(U,{key:`item-${t}`},R.createElement(L,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),R.createElement(U,{marginTop:1},e.size===c.length&&R.createElement(L,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&R.createElement(L,{color:"gray"},e.size," tools selected"),0===e.size&&R.createElement(L,{color:"gray"},"No tools selected")))},"ToolsSelector"),Ur=__name(({onComplete:e})=>{const[t,n]=F("location"),[r,o]=F(!1),[a,s]=F(null),[i,c]=F("agentType"),l=_(()=>[...Un.map(e=>e.name),...Ln.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=F(d()),g=__name(t=>{n("location"),c("agentType"),m(d()),e(t)},"resetToDefaults"),p=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===u.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===i)return"Agent type (identifier)";if("sysPrompt"===i)return"System prompt";if("ccToolDefinition"===i)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),h=__name(e=>{m({...u,location:e}),n("method")},"handleLocationSelect"),f=__name(e=>{m({...u,method:e}),n("configuration")},"handleMethodSelect"),y=__name(async()=>{try{s(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===Me&&(r=await je.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const a={[Se]:t.toString()};r&&(a[xe]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new dt({baseUrl:i}),l=await c.post({headers:a,endpoint:De.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription}});m({...u,agentType:ue(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof nt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?s(Ne):s("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),w=__name(()=>{m({...u,agentType:ue(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),b=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),v=__name(()=>{n("summary")},"handleToolsComplete"),C=__name(e=>{const t=new Set(u.selectedTools);t.has(e)?t.delete(e):t.add(e),m({...u,selectedTools:t})},"handleToggleTool"),T=__name(e=>{const t=[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(u.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),m({...u,selectedTools:n})},"handleToggleCategory");return R.createElement(U,{flexDirection:"column",gap:1},R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"white",bold:!0},"Create new agent"),R.createElement(L,{color:"gray"},p())),R.createElement(U,null,"location"===t&&R.createElement(Mr,{onSelect:h}),"method"===t&&R.createElement(Nr,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&R.createElement(_r,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:a,onSubmit:y}),"configuration"===t&&"manual"===u.method&&R.createElement(U,{flexDirection:"column",gap:1},R.createElement(jr,{step:i,agentType:u.agentType,sysPrompt:u.sysPrompt,ccToolDefinition:u.ccToolDefinition,onAgentTypeChange:e=>m({...u,agentType:e}),onSysPromptChange:e=>m({...u,sysPrompt:e}),onCCToolDefinitionChange:e=>m({...u,ccToolDefinition:e}),onAgentTypeSubmit:w,onSysPromptSubmit:E,onCCToolDefinitionSubmit:b})),"tools"===t&&R.createElement(Or,{selectedTools:u.selectedTools,onToggleTool:C,onToggleCategory:T,onComplete:v}),"summary"===t&&R.createElement(Dr,{config:u,onSaveComplete:g})))},"AgentNew"),Lr=__name(({onCancel:e})=>{const[t,n]=F(null),[r,o]=F(null),a=__name(e=>{n(e.value),o(null)},"handleSelect");return B((t,n)=>{n.escape&&e()}),R.createElement(U,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"round",flexDirection:"column"},null===t&&R.createElement(Fr,{handleSelect:a,createdAgentName:r}),"create_new_agent"===t&&R.createElement(Ur,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r=["create","edit","delete","execute","shellCommands"];for(const e of r)n.setAutoApprove(e,t)}__name(applyAutoAcceptMode,"applyAutoAcceptMode");var{setText:Br}=ge,Wr=__name(({resume:e=!1,continue:t=!1,trust:n=!1,updateStatus:r,updateFailedInfo:o})=>{const{exit:a}=z(),[s,i]=F(""),[c,l]=F("Ready..."),[d,u]=F(null),[m,g]=F(r);M(()=>{if(m){const e=setTimeout(()=>{g(null)},3e4);return()=>clearTimeout(e)}},[m]);const{stdout:p}=G(),[h,f]=F(!1),[y,w]=F(!1),[E,b]=F(!1),[v,C]=F(!1),[T,k]=F(!1),[A,P]=F(!1),[S,x]=F(null),[$,I]=F(null),[D,N]=F(!1),[_,O]=F(!1),W=j(null),[V,q]=F(0),[H,J]=F(!1),{executeBash:K,executionState:Y}=dn(),[Q,Z]=F(""),[X,ee]=F([]),[te,ne]=F(!1),[re,oe]=F([]),[ae,se]=F(crypto.randomUUID()),[ie,ce]=F(!1),[le,de]=F(!1),[ue,me]=F(!1),[ge,pe]=F(!1),[he,fe]=F(!0),[ye,we]=F(!1),[Ee,be]=F(0),[ve,Ce]=F(null),[Te,ke]=F(null),[Ae,Pe]=F(null),Se=j(!1),xe=j(Ae);M(()=>{xe.current=Ae},[Ae]);const[$e,Ie]=F(!1),[Re,Fe]=F(""),[Me,Ne]=F(!1),[_e,Oe]=F(!1),Ue=__name(async()=>{try{const e=await isTasteLearningEnabled();Ne(e),e&&await Sr.initializeProject()}catch(e){}},"loadTasteStatus"),Le=__name(async()=>{const e=await getConfiguredProvider();I(e);const t=await isOAuthEnforced();N(t)},"loadCurrentProvider"),Be=j([]),We=j(null),[ze,Ge]=F(null),{requestShellPermission:Ve,service:qe,respondToPrompt:He,clearSessionPermissions:Je,setEnabled:Ke}=Er({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{Ge({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),We.current&&l("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Ge({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),We.current&&l("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?l("Permission granted"):l("Permission denied")},"onPermissionResponse")});async function getBillingLink(){if(Te)return Te;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return ke(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return ke(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}M(()=>{qe&&applyAutoAcceptMode({enabled:_e,service:qe})},[_e,qe]),M(()=>{(async()=>{if(await jn.isProjectInitialized())if(pe(!0),fe(!1),Ue(),Le(),t){const e=await jn.listSessions();if(e.length>0){const t=e[0];at(t.id)}}else e&&ce(!0);else if(n)if(await jn.initializeProject(),pe(!0),fe(!1),Ue(),Le(),t){const e=await jn.listSessions();if(e.length>0){const t=e[0];at(t.id)}}else e&&ce(!0);else me(!0),fe(!1)})()},[e,t,n,a]),M(()=>{Be.current=re},[re]),M(()=>{(async()=>{if($&&"anthropic"===$&&D)try{await je.getValidAccessToken()||l("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){l("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[$,D]),M(()=>{if(!te)return;const e=setInterval(()=>{l(an())},7e3);return()=>clearInterval(e)},[te]),M(()=>()=>{W.current&&clearTimeout(W.current)},[]),B((e,t)=>{if(!(E||v||T||S||A)){if(t.ctrl&&"c"===e&&a(),t.ctrl&&"t"===e)return Cr(),P(e=>!e),void q(e=>e+1);if(t.shift&&t.tab)Oe(e=>!e);else{if(getIsExpandToolShortcut(t,e))return Cr(),J(e=>!e),void q(e=>e+1);if(t.escape)if(ze)He({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),ze.resolve(!1),Ge(null),l("Permission denied");else if(te&&We.current){We.current.interrupt(!0),ne(!1),l("Interrupted by user");const e=Xt("Interrupted by user");ee(t=>[...t,e])}t.meta||t.ctrl}}}),M(()=>{const e=__name(()=>{Cr(),q(e=>e+1)},"handleResize");if(p)return p.on("resize",e),()=>{p.off("resize",e)}},[p]),M(()=>{We.current||!ge||ie||le||(We.current=new Yn({onFeedUpdate:__name(e=>{ee(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Be.current];return Be.current=[],oe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{be(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ce(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{u(e)},"onRetryUpdate"),onProviderChange:__name(e=>{I(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&qe){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",n={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${e}`};return qe.requestShellPermission(n).then(e=>e.allowed)}if(qe){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`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return qe.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=xe.current;return e?{sessionId:ae,secret:e.secret}:null},"getShareInfo")},ae),(async()=>{await tt()})())},[ae,ie,le,ge]),__name(getBillingLink,"getBillingLink");const Ye=__name(async({role:e,input:t,images:n})=>{if(t.length)if(m&&g(null),be(0),"bash"===e){if(Se.current)return;Se.current=!0;const e=Qt(t);ee([...X,e]),i(""),await K(t,e=>{ee(e)},()=>{Cr(),q(e=>e+1)}),Se.current=!1}else{if(te)return oe(e=>[...e,t]),void i("");if(Se.current)return;Se.current=!0,ne(!0),l(an()),i("");try{We.current&&await We.current.sendMessage(t,n)}catch(e){if("Interrupted by user"===e?.message||e?.message?.toLowerCase().includes("interrupt")||e?.message?.toLowerCase().includes("abort")||"InterruptedError"===e?.name||"AbortError"===e?.name||"ECONNABORTED"===e?.code);else if("Insufficient credits"===e.message){l("Insufficient credits");const e=await getBillingLink(),t=Xt(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);ee(e=>[...e,t])}else if(e.message.startsWith("Error:")){l("Error");const t=Xt(e.message);ee(e=>[...e,t])}else{l("Error");const t=e.message||"An unexpected error occurred",n=Xt(t);ee(e=>[...e,n])}}finally{ne(!1),"Interrupted by user"!==c&&"Permission denied"!==c&&"Insufficient credits"!==c&&l("Ready..."),Se.current=!1}}},"handleSubmit"),Qe=__name(()=>{const e=`**Command Code v0.0.4-beta.6**\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${cr.filter(e=>"/help"!==e.command).map(e=>`**${e.command}** - ${e.description}`).join("\n")}`;ee(t=>[...t,Zt(e)])},"handleHelpCommand"),Ze=__name(async()=>{if(ee([]),Cr(),Oe(!1),Pe(null),Ie(!1),Fe(""),We.current){const e=We.current.getSessionManager();e&&await e.deleteShareInfo(),We.current=null;const t=crypto.randomUUID();se(t),Je(),We.current=new Yn({onFeedUpdate:__name(e=>{ee(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Be.current];return Be.current=[],oe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{be(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ce(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{u(e)},"onRetryUpdate"),onProviderChange:__name(e=>{I(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&qe){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",n={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${e}`};return qe.requestShellPermission(n).then(e=>e.allowed)}if(qe){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`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return qe.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=xe.current;return e?{sessionId:t,secret:e.secret}:null},"getShareInfo")},t)}q(e=>e+1),Ce(null),be(0)},"handleClearCommand"),Xe=__name(async()=>{if(We.current)if(We.current.isRequestInProgress())ee(e=>[...e,Jt("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{l("Compacting conversation...");const e=await We.current.compactConversation();Cr(),q(e=>e+1);const t=e.messagesRemoved>0?`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`:"Conversation is already compact.";ee(e=>[...e,Jt(t)]),l("Ready..."),Ce({current:We.current.getContextTokensUsed()||0,limit:Mn})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;ee(e=>[...e,Xt(t)]),l("Ready...")}else ee(e=>[...e,Jt("No active conversation to compact.")])},"handleCompactCommand"),et=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await at(t)}switch(e){case"/exit":a();break;case"/clear (reset, new)":await Ze();break;case"/help":Qe();break;case"/share":nt();break;case"/unshare":ot();break;case"/taste":b(!0);break;case"/provider":C(!0);break;case"/memory":k(!0);break;case"/init":rt();break;case"/agents":w(!0);break;case"/compact":await Xe();break;default:const t=getCustomCommandContent(e);t&&await Ye({input:t,role:"user"})}},"handleCommand"),tt=__name(async()=>{const e=We.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&Pe({url:t.url,secret:t.secret})}},"loadShareInfo"),nt=__name(async()=>{if(ae){if(Ae)return await Br(Ae.url),l(""),Ie(!0),void setTimeout(()=>{Ie(!1)},3e3);try{l("Creating share link...");const e=We.current?.getMessages()||[],t=Gn.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new dt({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:De.ALPHA.SHARE.CREATE,body:{sessionId:ae,messages:t}}),o={url:r.url,secret:r.secret};Pe(o);const a=We.current?.getSessionManager();a&&await a.saveShareInfo({url:r.url,secret:r.secret}),await Br(r.url),l(""),Ie(!0),setTimeout(()=>{Ie(!1)},5e3)}catch(e){l(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else l("No active session to share")},"handleShareCommand"),rt=__name(async()=>{try{const e=process.cwd(),t=`Created AGENTS.md at ${await initProjectMemory(e)}. You can now edit it with /memory or open it in your editor.`;ee(e=>[...e,Jt(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;ee(e=>[...e,Jt(t)])}},"handleInitCommand"),ot=__name(async()=>{if(ae){if(!Ae)return Fe("NOT SHARED: Session is not currently shared"),void setTimeout(()=>Fe(""),5e3);try{l("Removing share link...");const e=new dt({baseUrl:getApiBaseUrl()});await e.delete({endpoint:De.ALPHA.SHARE.DELETE,body:{sessionId:ae,secret:Ae.secret}});const t=We.current?.getSessionManager();t&&await t.deleteShareInfo(),Fe("UNSHARED: Sharing has stopped"),l(""),Pe(null),setTimeout(()=>{Fe("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;l(t),setTimeout(()=>l(""),5e3)}}else l("No active session to unshare")},"handleUnshareCommand"),at=__name(async e=>{try{ee([]),We.current=null,Oe(!1),se(e),ce(!1),de(!0),await new Promise(e=>setTimeout(e,100)),We.current=new Yn({onFeedUpdate:__name(e=>{ee(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Be.current];return Be.current=[],oe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{be(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ce(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{u(e)},"onRetryUpdate"),onProviderChange:__name(e=>{I(e)},"onProviderChange"),getShareInfo:__name(()=>{const t=xe.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const t=await We.current.loadSession(e);await tt(),ee(t),Cr(),q(e=>e+1)}catch(e){console.error("Failed to load session:",e),ce(!0),se(crypto.randomUUID())}},"handleSelectSession"),st=__name(async()=>{ee([]),We.current=null,Oe(!1),se(crypto.randomUUID()),ce(!1),de(!1)},"handleNewSession"),it=__name(async()=>{try{await jn.initializeProject(),me(!1),e?(console.log("No conversations found to resume."),we(!0),a()):(pe(!0),Ue(),Le())}catch(e){console.error("Failed to initialize project:",e),me(!1),we(!0),a()}},"handleTrust"),ct=__name(()=>{a()},"handleNoTrust"),lt=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void x({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),I(e),C(!1);const n=getProviderDisplayName(e);l(`Provider set to ${n}`),W.current&&clearTimeout(W.current),O(!0),W.current=setTimeout(()=>{O(!1),W.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),l("Failed to set provider"),C(!1)}},"handleProviderSelect"),ut=__name(()=>{C(!1)},"handleProviderCancel"),mt=__name(()=>{if(S){x(null),C(!1),I(S.provider);const e=getProviderDisplayName(S.provider);l(`${e} authentication successful`),W.current&&clearTimeout(W.current),O(!0),W.current=setTimeout(()=>{O(!1),W.current=null},5e3)}},"handleAuthSuccess"),gt=__name(()=>{x(null)},"handleAuthCancel");if(ye)return null;if(ue)return R.createElement(R.Fragment,null,R.createElement(xr,{staticKey:V}),R.createElement(yr,{onTrust:it,onExit:ct}));if(he)return null;if(ie)return R.createElement(fr,{onSelectSession:at,onNewSession:st});if(!ge)return null;if(ze){if("shell_command"===ze.toolName){const e=ze.params;return R.createElement(U,{flexDirection:"column",width:"100%"},R.createElement(nr,{staticKey:V,feed:X,showHeader:!0,expandedToolOutput:H}),R.createElement(U,{marginY:1},R.createElement(vr,{request:e,onResponse:e=>{He(e);const t="no"!==e.value;ze.resolve(t),Ge(null),l(t?"Shell command allowed":"Shell command denied")}})))}{const e={action:ze.toolName.includes("edit")?"edit":ze.toolName.includes("write")?"create":ze.toolName.includes("delete")?"delete":"edit",filePath:ze.params.filePath||ze.params.file_path||ze.params.path||ze.params.absolutePath||ze.params.notebook_path||"unknown",description:`Allow ${ze.toolName} operation`,oldContent:"edit_file"===ze.toolName?ze.params.oldContent:void 0,newContent:"edit_file"===ze.toolName?ze.params.newContent:void 0};return R.createElement(U,{flexDirection:"column",width:"100%"},R.createElement(nr,{staticKey:V,feed:X,showHeader:!0,expandedToolOutput:H}),R.createElement(U,{marginY:1},R.createElement(br,{request:e,onResponse:e=>{He(e);const t="no"!==e.value;ze.resolve(t),Ge(null),l(t?"File operation allowed":"File operation denied")}})))}}return A?R.createElement(kr,{onClose:()=>{P(!1),q(e=>e+1)}}):E?R.createElement(R.Fragment,null,R.createElement(xr,{staticKey:V}),R.createElement(U,{flexDirection:"column",width:"100%"},R.createElement(U,{marginBottom:1},R.createElement(L,{dimColor:!0},"Press Esc to return to conversation")),R.createElement(Tr,{onClose:()=>b(!1),onSettingsChange:Ue,staticKey:V}))):R.createElement(U,{flexDirection:"column",width:"100%"},R.createElement(nr,{staticKey:V,feed:X,showHeader:!0,expandedToolOutput:H}),R.createElement(RetryMessage,{attempt:d}),!v&&!S&&!T&&!y&&R.createElement(hr,{queuedMessages:re,isProcessing:te,executionState:Y,status:c,input:s,setInput:i,onSubmit:Ye,showFileList:h,setShowFileList:f,fileSearchQuery:Q,setFileSearchQuery:Z,onCommand:et,outputTokens:Ee,contextUsage:ve,tasteLearning:Me,shareInfo:Ae,showShareNotification:$e,unshareNotificationMessage:Re,updateStatus:m,updateFailedInfo:o,currentProvider:$,showProviderInfo:_,isOAuthMode:D,autoAcceptMode:_e}),v&&R.createElement(U,{marginY:1},R.createElement(Ar,{onSelect:lt,onCancel:ut,currentProvider:$})),y&&R.createElement(U,{marginY:1},R.createElement(Lr,{onCancel:()=>w(!1)})),T&&R.createElement(U,{marginY:1},R.createElement(Pr,{onClose:()=>k(!1)})),S&&R.createElement(U,{marginY:1},R.createElement(S.Component,{onSuccess:mt,onCancel:gt})))},"InteractiveCLI"),zr=__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 jn.isProjectInitialized()&&0===(await jn.listSessions()).length&&(console.log("No conversations found to resume."),process.exit(0)),W(R.createElement(Wr,{resume:e.resume,continue:e.continue,trust:e.trust,updateStatus:t,updateFailedInfo:n}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})},"interactive"),{red:Gr,yellow:Vr}=te,qr=__name((e="ERROR: ",t,n=!0,r=!0)=>{if(t){if(console.log(),n?(console.log(`${ve.error} ${Gr(e)}`),console.log(`${ve.error} ${Gr("ERROR →")} ${t.name}`),console.log(`${ve.info} ${Gr("REASON →")} ${t.message}`),console.log(`${ve.info} ${Gr("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${ve.warning} ${Vr(e)}\n`),!r)return!1;process.exit(0)}},"handleError"),Hr=__name(()=>{process.on("unhandledRejection",e=>{qr(be`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(),t="win32"===process.platform,r=Le();if(!e){const e=er(),a=Xn();console.log(te.white(a)),console.log(te.dim(`${e} ${r?`env: (${r.replace("--","")})`:""}`)),console.log(""),console.log(`${o.warning} Authentication required to use Command Code.`),console.log("");const s=Ce.createInterface({input:process.stdin,output:process.stdout});try{const e=await s.question(`Would you like to sign in now? ${te.dim("(y/n)")}: `);s.close();const a=e.trim().toLowerCase();if(""!==a&&"y"!==a&&"yes"!==a)return console.log(""),console.log(`${o.info} You can authenticate later by running: ${t?"command-code":"cmd"} login`),!1;console.log(""),console.log(`${o.arrowUp} Running: ${t?"command-code":"cmd"} login`),console.log("");try{return n(`${t?"command-code":"cmd"} login ${r}`,{stdio:"inherit",cwd:process.cwd()}),await getAuthKey()?(console.log(""),console.log(`${o.tick} Authentication successful! Starting Command Code...`),console.log(""),!0):(console.log(""),console.log(`${o.cross} Authentication failed. Please try again with: ${t?"command-code":"cmd"} login`),!1)}catch(e){return console.log(""),console.log(`${o.cross} Login command failed. Please run: ${t?"command-code":"cmd"} login`),!1}}catch(e){return s.close(),console.log(""),console.log(`${o.info} Authentication cancelled. You can authenticate later with: ${t?"command-code":"cmd"} login`),!1}}return!0}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var Jr=__name(()=>{const e=[];for(const t of process.argv)"-v"===t?e.push("--version"):"-CRUD"===t?e.push("--crud"):"-CRU"===t?e.push("--cru"):"-C"===t?e.push("--create"):"-R"===t?e.push("--read"):"-U"===t?e.push("--update"):"-D"===t?e.push("--delete"):"-T"===t?e.push("--trust"):e.push(t);process.argv=e},"preprocessCustomFlags");async function updateProjectPermissions(e){const t=process.cwd(),n=f.join(t,".commandcode"),r=f.join(n,"settings.local.json");try{await A.mkdir(n,{recursive:!0});const t=await loadOrCreateSettings(r);updatePermissionsInSettings({settings:t,permissions:e}),await saveSettings({settingsPath:r,settings:t})}catch(e){throw new Error(`Failed to update project permissions: ${e instanceof Error?e.message:String(e)}`)}}async function loadOrCreateSettings(e){try{const t=parseJSON(await A.readFile(e,"utf-8"))||{permissions:{allow:[],deny:[],autoApprove:{}}};return t.permissions||(t.permissions={allow:[],deny:[]}),t.permissions.autoApprove||(t.permissions.autoApprove={}),t}catch{return{permissions:{allow:[],deny:[],autoApprove:{}}}}}function updatePermissionsInSettings(e){const{settings:t,permissions:n}=e;void 0!==n.create&&(t.permissions.autoApprove.create=n.create),void 0!==n.read&&(t.permissions.autoApprove.read=n.read),void 0!==n.update&&(t.permissions.autoApprove.update=n.update),void 0!==n.delete&&(t.permissions.autoApprove.delete=n.delete)}async function saveSettings(e){const{settingsPath:t,settings:n}=e;await A.writeFile(t,JSON.stringify(n,null,2),"utf-8")}async function handleCrudFlags(e){if(!(e.crud||e.cru||e.create||e.read||e.update||e.delete))return;await jn.initializeProject();const t={};e.crud&&(t.create=!0,t.read=!0,t.update=!0,t.delete=!0),e.cru&&(t.create=!0,t.read=!0,t.update=!0,t.delete=!1),e.create&&(t.create=!0),e.read&&(t.read=!0),e.update&&(t.update=!0),e.delete&&(t.delete=!0),await updateProjectPermissions(t)}async function migrateUserDirectory(){const e=k.homedir(),t=y.join(e,".command-code"),n=y.join(e,".commandcode");if(!J.existsSync(t))return{success:!0,message:"User directory migration not needed (old directory does not exist)",skipped:!0};if(J.existsSync(n))return console.warn("Both ~/.command-code and ~/.commandcode exist. Manual intervention required."),console.warn("Please manually merge or remove ~/.command-code/"),{success:!1,message:"Both old and new directories exist. Manual intervention required."};try{J.renameSync(t,n);const e=y.join(n,"config.json");if(J.existsSync(e)){const t=J.readFileSync(e,"utf-8"),n=JSON.parse(t);delete n.tasteUsage,J.writeFileSync(e,JSON.stringify(n,null,2))}return{success:!0,message:"User directory migrated successfully"}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("User directory migration failed:",t),console.error("Please manually rename ~/.command-code to ~/.commandcode"),{success:!1,message:`User directory migration failed: ${t}`}}}async function migrateProjectDirectory(e){const{projectRoot:t}=e,n=y.join(t,".command-code"),r=y.join(t,".commandcode");if(!J.existsSync(n))return{success:!0,message:"Project directory migration not needed (old directory does not exist)",skipped:!0};if(J.existsSync(r))return console.warn(`Both .command-code and .commandcode exist in ${t}`),console.warn("Manual intervention required. Please manually merge or remove .command-code/"),{success:!1,message:"Both old and new directories exist. Manual intervention required."};try{return J.renameSync(n,r),{success:!0,message:"Project directory migrated successfully"}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("Project directory migration failed:",t),console.error("Please manually rename .command-code to .commandcode"),{success:!1,message:`Project directory migration failed: ${t}`}}}async function migrateDirectories(e){const{projectRoot:t}=e,n=await migrateUserDirectory(),r=await migrateProjectDirectory({projectRoot:t}),o=n.skipped,a=r.skipped;return o&&a||n.success&&r.success||console.warn("\n⚠️ Some migrations failed. See messages above."),{userResult:n,projectResult:r}}__name(updateProjectPermissions,"updateProjectPermissions"),__name(loadOrCreateSettings,"loadOrCreateSettings"),__name(function createDefaultPermissionsStructure(){return{allow:[],deny:[]}},"createDefaultPermissionsStructure"),__name(updatePermissionsInSettings,"updatePermissionsInSettings"),__name(saveSettings,"saveSettings"),__name(handleCrudFlags,"handleCrudFlags"),__name(migrateUserDirectory,"migrateUserDirectory"),__name(migrateProjectDirectory,"migrateProjectDirectory"),__name(migrateDirectories,"migrateDirectories");var Kr=getPackageJson(),Yr=process.cwd();global.COMMAND_CODE_CWD=Yr;var Qr=new ke("CommandCode");Hr();var Zr=__name(()=>{const e=process.argv.slice(2);return!e.includes("--skip-update-check")&&0===e.length},"shouldAutoUpdate");(async()=>{if(Jr(),await migrateDirectories({projectRoot:Yr}),Zr()&&(await performAutoUpdate()).success){const e=process.argv[1]?.includes("command-code")?"command-code":"cmd",t=r(e,["--skip-update-check"],{stdio:"inherit",detached:!1,shell:!0});await new Promise(()=>{t.on("exit",e=>{process.exit(e||0)})})}const n=new e;async function commanderAction(e){await checkAuthAndPromptLogin()||process.exit(1),await handleCrudFlags({crud:e.crud,cru:e.cru,create:e.create,read:e.read,update:e.update,delete:e.delete});const t={};switch(e.trust&&(t.trust=!0),!0){case e.resume:zr({resume:!0,...t});break;case e.continue:zr({continue:!0,...t});break;default:zr(t)}}__name(commanderAction,"commanderAction"),n.name(Kr.name).description(Kr.description||"Command Code — Coding Agent with taste by Langbase").version(Kr.version,"-v, --version","output the version number").option("-r, --resume","Resume a conversation").option("-c, --continue","Continue the last conversation").option("-T, --trust","Auto-trust project (skip initial permission prompt)").option("--crud","Enable all CRUD permissions (shortcut: -CRUD)").option("--cru","Enable Create, Read, Update (no Delete) (shortcut: -CRU)").option("--create","Enable Create permission (shortcut: -C)").option("--read","Enable Read permission (shortcut: -R)").option("--update","Enable Update permission (shortcut: -U)").option("--delete","Enable Delete permission (shortcut: -D)").addOption(new t(Ae).hideHelp()).addOption(new t(Pe).hideHelp()).action(commanderAction).allowUnknownOption().allowExcessArguments(),n.addCommand(Xe),n.addCommand(Qe),n.addCommand(ut),n.addCommand(Ct),n.addCommand(createTasteCommand()),n.addCommand(qe),n.addCommand(He),n.addCommand(Je),n.hook("preAction",()=>{Qr.debug("Command starting...")}),n.hook("postAction",()=>{Qr.debug("Command completed.")}),n.parse()})();
2
+ import"dotenv/config";import{Command as e,Option as t}from"commander";import{execSync as n,spawn as r}from"child_process";import o,{mainSymbols as a}from"figures";import*as s from"@clack/prompts";import{confirm as i,isCancel as c,cancel as l,note as d,password as u,select as m,outro as g}from"@clack/prompts";import p from"picocolors";import h from"open";import*as f from"path";import y,{dirname as w,join as E,relative as b,isAbsolute as v,resolve as C}from"path";import*as T from"os";import k from"os";import*as A from"fs/promises";import P,{mkdir as S,writeFile as x}from"fs/promises";import $ from"crypto";import I,{z as D}from"zod";import R,{useState as F,useEffect as j,useRef as M,useCallback as N,useMemo as _}from"react";import{Static as O,Box as U,Text as L,useInput as B,render as W,useApp as z,useStdout as G}from"ink";import V from"ink-text-input";import q from"sharp";import*as H from"fs";import J,{existsSync as K,readFileSync as Y,promises as Q,constants as Z,readdirSync as X,statSync as ee}from"fs";import te from"chalk";import ne from"open-editor";import*as re from"process";import oe from"semver";import{fileURLToPath as ae}from"url";import{minimatch as se}from"minimatch";import{glob as ie}from"glob";import{quote as ce}from"shell-quote";import le from"gray-matter";import{MessageStream as de}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import ue from"@sindresorhus/slugify";import{EventEmitter as me}from"events";import ge from"@crosscopy/clipboard";import pe from"ink-gradient";import{setOptions as he,parse as fe}from"marked";import ye from"marked-terminal";import*as we from"diff";import Ee from"ink-select-input";import be from"dedent";import ve from"log-symbols";import Ce from"readline/promises";var Te=Object.defineProperty,__name=(e,t)=>Te(e,"name",{value:t,configurable:!0}),ke=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${o.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${o.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${o.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${o.warning} ${e}`)}debug(e){process.env.DEBUG&&console.log(`[${this.prefix}] ${o.bullet} ${e}`)}};function heading({text:e,sub:t,dim:n,green:r}){return r?`${p.bgGreen(p.black(` ${e} `))} ${t&&t}`:n?`${p.bgBlack(p.white(` ${e} `))} ${t&&t}`:`${p.bold(p.bgCyan(p.black(` ${e} `)))} ${t&&t}`}__name(heading,"heading");var Ae="--co",Pe="--xco",Se=`x-${Ae.replace("--","")}-flag`,xe="x-oauth-token",$e="x-project-slug",Ie="x-taste-learning",De={ALPHA:{GENERATE:"/alpha/generate",WHOAMI:"/alpha/whoami",NAMESPACES:"/alpha/namespaces",AGENT:{GENERATE:"/alpha/agent/generate"},SHARE:{CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",DATA:"/alpha/share/data",APPEND:"/alpha/share/append",CONNECT:"/alpha/share/connect"},TASTE:{GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"}},BETA:{TASTE:{PACKAGES:{UPLOAD:"/beta/taste/packages/:namespace",LIST:"/beta/taste/packages",GET:"/beta/taste/packages/:namespace/:packageName",FILES:"/beta/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/beta/taste/packages/:namespace/:packageName/download"}}},INTERNAL:{ADMIN:{USERS:"/internal/admin/users",GRANT_CREDITS:"/internal/admin/grant-credits",ORGS:"/internal/admin/orgs",GRANT_ORG_CREDITS:"/internal/admin/grant-org-credits",ENTITY_TYPE:"/internal/admin/entity-type"},API_KEYS:{CREATE:"/internal/api-keys/create",LIST:"/internal/api-keys/list",DELETE:"/internal/api-keys/delete"},BILLING:{CREDITS:{GET:"/internal/billing/credits"},CUSTOMERS:{GET:"/internal/billing/customers",UPSERT:"/internal/billing/customers",SETUP_INTENT:"/internal/billing/customers/setup-intent",PAYMENT_METHOD:"/internal/billing/customers/payment-method",SET_DEFAULT_PAYMENT_METHOD:"/internal/billing/customers/payment-method/set-default",INVOICES:"/internal/billing/customers/invoices"},SUBSCRIPTIONS:{GET:"/internal/billing/subscriptions"},WEBHOOK:"/internal/billing/webhook"},ORGS:{LIST:"/internal/orgs",GET:"/internal/orgs/:login",CREATE:"/internal/orgs",UPDATE:"/internal/orgs/:id",DELETE:"/internal/orgs/:id",AVATAR:"/internal/orgs/:id/avatar",MEMBERS:{LIST:"/internal/orgs/:id/members",ADD:"/internal/orgs/:id/members",UPDATE:"/internal/orgs/:id/members/:userId",REMOVE:"/internal/orgs/:id/members/:userId"},INVITATIONS:{LIST:"/internal/orgs/:id/invitations",SEND:"/internal/orgs/:id/invitations",ACCEPT:"/internal/invitations/:token/accept",CANCEL:"/internal/invitations/:id"}},USER:{SETTINGS:"/internal/user/settings",AVATAR:"/internal/user/avatar"},USAGE:{LIST:"/internal/usage",SUMMARY:"/internal/usage/summary"},TASTE:{PACKAGES:{LIST:"/internal/taste/packages",GET:"/internal/taste/packages/:namespace/:packageName",FILES:"/internal/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/internal/taste/packages/:namespace/:packageName/download"}}}},Re={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")}},BETA:{TASTE_PACKAGES:{UPLOAD:new RegExp("^/beta/taste/packages/[a-zA-Z0-9_-]+$"),FILES:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download")}},INTERNAL:{ORGS:{GET:new RegExp("/internal/orgs/[a-zA-Z0-9_-]+")},TASTE:{PACKAGES:{GET:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),FILES:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),DOWNLOAD:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download")}}}};function getStudioAuthUrl(e){return"dev"===e?"http://localhost:3000/settings/api":"staging"===e?"https://staging.commandcode.ai/settings/api":"https://commandcode.ai/settings/api"}Object.values(Re.ALPHA.TASTE),Object.values(Re.BETA.TASTE_PACKAGES),De.ALPHA.GENERATE,De.ALPHA.AGENT.GENERATE,De.ALPHA.WHOAMI,De.ALPHA.NAMESPACES,De.ALPHA.SHARE.CREATE,De.ALPHA.SHARE.DELETE,De.ALPHA.SHARE.APPEND,De.ALPHA.TASTE.LEARN,De.ALPHA.TASTE.DELETE,De.ALPHA.TASTE.GET,De.ALPHA.TASTE.UPDATE,Object.values(De.BETA.TASTE.PACKAGES),Object.values(Re.INTERNAL.ORGS),Object.values(Re.INTERNAL.TASTE.PACKAGES),__name(getStudioAuthUrl,"getStudioAuthUrl");var Fe,je="anthropic";I.enum(["owner","admin","member"]),(e=>{e.OAuth=D.object({type:D.literal("oauth"),refresh:D.string(),access:D.string(),expires:D.number()}),e.ApiKey=D.object({type:D.literal("api"),key:D.string()}),e.Info=D.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(()=>y.join(k.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=t(),r="dev"===e?"models.dev.json":"staging"===e?"models.staging.json":"models.json";return y.join(n(),r)},"getAuthFile");async function get(e){try{const t=await P.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),a=r();await P.mkdir(o,{recursive:!0});let s={};try{const e=await P.readFile(a,"utf-8");s=JSON.parse(e)}catch{}s[e]=t,await P.writeFile(a,JSON.stringify(s,null,2)),await P.chmod(a,384)}async function remove(e){const t=r();try{const n=await P.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await P.unlink(t):(await P.writeFile(t,JSON.stringify(r,null,2)),await P.chmod(t,384))}catch{}}async function list2(){try{const e=await P.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=list2,__name(list2,"list")})(Fe||(Fe={}));var Me,Ne="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing";async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=q(n),a=await o.metadata();if(!a.width||!a.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const s=1200;let i,c,{width:l,height:d}=a;(l>s||d>s)&&(l>d?(d=Math.round(d*s/l),l=s):(l=Math.round(l*s/d),d=s)),t.includes("png")&&a.hasAlpha?(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=i.length;return{compressedBase64:i.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")}(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 $.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return $.createHash("sha256").update(e).digest("base64url")}function generateState(){return $.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,a){const s=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:a})});if(!s.ok){const e=await s.text();throw new Error(`Token exchange failed: ${e}`)}const i=await s.json();await Fe.set("anthropic",{type:"oauth",refresh:i.refresh_token,access:i.access_token,expires:Date.now()+1e3*i.expires_in})}async function refreshAccessToken(){const e=await Fe.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 Fe.remove("anthropic");const o=await r.json();return await Fe.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 Fe.remove("anthropic")}}}async function getValidAccessToken(){const e=await Fe.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")})(Me||(Me={})),__name(compressImageForSharing,"compressImageForSharing"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode");var _e={"command-code":{id:"command-code",displayName:"Command Code",description:"recommended",requiresAuth:!1},anthropic:{id:"anthropic",displayName:"Anthropic",description:"Claude Pro/Max",requiresAuth:!0,hidden:!0,authComponent:__name(({onSuccess:e,onCancel:t})=>{const[n,r]=F(""),[o,a]=F(null),[s,i]=F(!1),[c,l]=F(null),[d,u]=F(!0),[m,g]=F(!1),[p,f]=F(!1);j(()=>{const{url:e,verifier:t,state:n}=Me.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=N(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||p){if(!p||t.isPasteEnd){if(p&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();r(t)}else if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();r(e)}return}r(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();r(t)}else if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();r(e)}return}},[p]);B((e,n)=>{n.escape&&t(),d&&!m&&("y"===e||"Y"===e?o&&(h(o.url).catch(console.error),g(!0),u(!1)):"n"!==e&&"N"!==e||t())});const w=__name(async()=>{if(n.trim()&&o&&!s){i(!0),l(null);try{const t=n.split("#")[0].trim();await Me.exchangeCodeForTokens(t,o.verifier,o.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){l(e instanceof Error?e.message:"Authentication failed"),i(!1)}}},"handleSubmit");return d&&!m?R.createElement(U,{flexDirection:"column"},R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0,color:"cyan"},"Anthropic Authentication")),R.createElement(U,{marginBottom:1},R.createElement(L,null,"Open the Anthropic auth page?",R.createElement(L,{dimColor:!0}," (Y/n)")))):R.createElement(U,{flexDirection:"column"},R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0,color:"cyan"},"Anthropic Authentication")),R.createElement(U,{marginBottom:1},R.createElement(L,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),R.createElement(U,{marginBottom:1},R.createElement(L,{dimColor:!0},"After authorizing, copy the code and paste it below:")),c&&R.createElement(U,{marginBottom:1},R.createElement(L,{color:"red"},"Error: ",c)),R.createElement(U,null,R.createElement(L,null,"Authorization code: "),R.createElement(V,{mask:"*",focus:!0,value:n,onChange:y,onSubmit:w,placeholder:"Paste code here..."})),R.createElement(U,{marginTop:1},R.createElement(L,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth"),checkAuth:__name(async()=>!!await Me.getValidAccessToken(),"checkAuth")}};function getProviderDisplayName(e){if(!e)return"None";const t=_e[e];return t?.displayName||e}function getProviderConfig(e){return _e[e]}function isInternalFlagPresent(){return process.argv.includes(Ae)}function getProviderOptions(){const e=isInternalFlagPresent();return Object.values(_e).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}async function loadUserConfig(){try{const e=ze();return parseJSON(await A.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=ze();await A.writeFile(t,JSON.stringify(e,null,2)),await A.chmod(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t={...await loadUserConfig(),...e};await saveUserConfig(t)}async function isTasteLearningEnabled(){return(await loadUserConfig()).tasteLearning??!0}async function setTasteLearning(e){const{tasteLearning:t}=e;await updateUserConfig({tasteLearning:t})}async function isOAuthEnforced(){return isInternalFlagPresent()?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),!0):(await loadUserConfig()).forceOAuth??!1}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error('OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.')}__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalFlagPresent,"isInternalFlagPresent"),__name(getProviderOptions,"getProviderOptions"),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken");var Oe=__name(()=>y.join(k.homedir(),".commandcode"),"getAuthDir"),Ue=__name(()=>{const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"dev":t?"staging":"prod"},"getEnv"),Le=__name(()=>{const e=Ue();return"dev"===e?"--dev":"staging"===e?"--staging":""},"getEnvFlag"),Be=__name(e=>{const t=e??Ue(),n="dev"===t?"auth.dev.json":"staging"===t?"auth.staging.json":"auth.json";return y.join(Oe(),n)},"getAuthFile"),We=__name(()=>y.join(k.homedir(),".commandcode"),"getConfigDir"),ze=__name(e=>{const t=e??Ue(),n="dev"===t?"config.dev.json":"staging"===t?"config.staging.json":"config.json";return y.join(We(),n)},"getConfigFile"),Ge=__name(e=>{const t=e??Ue(),n="dev"===t?"models.dev.json":"staging"===t?"models.staging.json":"models.json";return y.join(We(),n)},"getModelsFile");async function loginAction(){try{const e=Ue(),t=getStudioAuthUrl(e);console.log("\n"),s.intro(heading({text:"Command Code Authentication",sub:""}));const n=await i({message:`Open the authentication page? ${p.dim("— copy your API key from there and paste it here.")}`});c(n)&&(l(`${o.cross} Login cancelled.`),process.exit(0)),n&&(await h(t),d(p.yellow("Please copy your API key from the opened page and paste it here.")));const r=await u({message:"Paste your API key:",mask:"*"});c(r)&&(l(`${o.cross} No API key provided.`),process.exit(0)),r.trim()||(console.log(`${o.cross} No API key provided.`),process.exit(1));const a=Oe(),f=Be(e);await P.mkdir(a,{recursive:!0}),await P.writeFile(f,JSON.stringify({apiKey:r},null,2)),await P.chmod(f,384);const y=await m({message:"Select provider",options:getProviderOptions()});if(c(y))l(`${o.cross} No provider selected.`);else if("anthropic"===y){const e=await m({message:"Login method",options:[{value:"anthropic-oauth",label:"Claude Pro/Max"}]});c(e)?l(`${o.cross} No login method selected.`):"anthropic-oauth"===e&&await anthropicAuth()}await updateUserConfig({provider:y});let w=`You are logged in. API key is stored in ~/.commandcode/${"dev"===e?"auth.dev.json":"staging"===e?"auth.staging.json":"auth.json"}. Run \`cmd\` to get started.`;g(p.green(w)),process.exit(0)}catch(e){console.error(`${o.cross} Login failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function anthropicAuth(){try{const{url:e,verifier:t,state:n}=Me.createAuthorizationUrl();await i({message:"Open the Anthropic auth page?"})&&(await h(e),d(p.yellow("Please copy your authorization code from the opened page and paste it here.")));const r=await u({message:"Paste your authorization code:",mask:"*"});c(r)&&(l(`${o.cross} No API key provided.`),process.exit(1)),r.trim()||(console.log(`${o.cross} No authorization code provided`),process.exit(1));const a=r.split("#")[0].trim();return await Me.exchangeCodeForTokens(a,t,n),!0}catch(e){l(`${o.cross} Anthropic OAuth failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function logoutAction(){try{const e=Ue(),t=Be(e),n=Ge(e);try{await P.unlink(t)}catch(e){}try{const e=await loadUserConfig(),{provider:t,...n}=e;await saveUserConfig(n)}catch(e){}try{await P.unlink(n)}catch(e){}g(p.green("Successfully logged out from Command Code")),process.exit(0)}catch(e){l(`${o.cross} Logout failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function getAuthKey(e){try{const t=Be(e),n=await P.readFile(t,"utf-8");return JSON.parse(n).apiKey||null}catch{return null}}async function statusAction(){try{const e=Ue();await getAuthKey(e)||(l(`${o.cross} Not authenticated. Please login using "cmd auth login".`),process.exit(1)),g(p.green(`${o.tick} Authenticated with Command Code`)),process.exit(0)}catch(e){l(`${o.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 Ve=new e("auth").description("Manage authentication with Command Code");Ve.command("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),Ve.command("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Ve.command("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);var qe=new e("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),He=new e("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Je=new e("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${k.platform()}-${k.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return J.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!e.name.startsWith(".")).filter(e=>!t.has(e.name)).map(e=>e.name).sort()}catch{return[]}}function isGitRepository(){try{return n("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return n("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=n("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=n("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),r=t.filter(e=>e.startsWith(" M")).length,o=t.filter(e=>e.startsWith("A ")).length,a=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,i=[];return r>0&&i.push(`M ${r}`),o>0&&i.push(`A ${o}`),a>0&&i.push(`D ${a}`),s>0&&i.push(`?? ${s}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=n("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 detectTerminal(){const e=process.env;if(e.TERM_PROGRAM){const t=e.TERM_PROGRAM;if("vscode"===t)return{name:"Visual Studio Code",type:"vscode",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("iTerm.app"===t)return{name:"iTerm2",type:"iterm2",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION,iterm2Profile:e.ITERM_PROFILE}};if("Apple_Terminal"===t)return{name:"macOS Terminal",type:"terminal",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("WarpTerminal"===t)return{name:"Warp",type:"warp",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("Hyper"===t)return{name:"Hyper",type:"hyper",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}}}if(e.WT_SESSION||e.WT_PROFILE_ID)return{name:"Windows Terminal",type:"windows-terminal",details:{wtSession:e.WT_SESSION,wtProfileId:e.WT_PROFILE_ID}};if(e.ALACRITTY_SOCKET||e.ALACRITTY_WINDOW_ID)return{name:"Alacritty",type:"alacritty",details:{alacrittySocket:e.ALACRITTY_SOCKET,alacrittyWindowId:e.ALACRITTY_WINDOW_ID}};if(e.KITTY_WINDOW_ID||e.KITTY_PID)return{name:"Kitty",type:"kitty",details:{kittyWindowId:e.KITTY_WINDOW_ID,kittyPid:e.KITTY_PID}};if(e.GNOME_TERMINAL_SERVICE||e.VTE_VERSION)return{name:"GNOME Terminal",type:"gnome-terminal",details:{gnomeTerminalService:e.GNOME_TERMINAL_SERVICE,vteVersion:e.VTE_VERSION}};if(e.KONSOLE_VERSION||e.KONSOLE_PROFILE_NAME)return{name:"Konsole",type:"konsole",details:{konsoleVersion:e.KONSOLE_VERSION,konsoleProfile:e.KONSOLE_PROFILE_NAME}};if(e.TMUX)return{name:"tmux",type:"tmux",details:{tmux:e.TMUX,tmuxPane:e.TMUX_PANE}};if(e.ConEmuPID||e.ConEmuBuild)return{name:"ConEmu",type:"conemu",details:{conEmuPid:e.ConEmuPID,conEmuBuild:e.ConEmuBuild}};if(e.SSH_CLIENT||e.SSH_TTY)return{name:"SSH",type:"ssh",details:{sshClient:e.SSH_CLIENT,sshTty:e.SSH_TTY}};if(e.CI){const t=e.GITHUB_ACTIONS?"GitHub Actions":e.GITLAB_CI?"GitLab CI":e.JENKINS_URL?"Jenkins":e.CIRCLECI?"CircleCI":"Unknown CI";return{name:t,type:"ci",details:{ci:e.CI,ciName:t}}}const t=e.TERM||"unknown";return{name:`Unknown Terminal (${t})`,type:"unknown",details:{term:t,colorterm:e.COLORTERM,shell:e.SHELL}}}function getIsTerminalIterm2(){return"iTerm2"===detectTerminal().name}function isDisableOAuthFlagPresent(){return process.argv.includes(Pe)}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=ze(),t=await P.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,a=isInternalFlagPresent();return isDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):a||o?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),"anthropic"):r}catch{return null}}function getIsExpandToolShortcut(e,t){const n=getIsTerminalIterm2();return!(!n||!e.shift||"O"!==t)||!(n||!e.ctrl||"o"!==t)}__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(detectTerminal,"detectTerminal"),__name(getIsTerminalIterm2,"getIsTerminalIterm2"),__name(isDisableOAuthFlagPresent,"isDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut");var Ke=new ke("Config"),Ye=f.join(T.homedir(),".commandcode-config.json");async function loadConfig(){try{return parseJSON(await A.readFile(Ye,"utf-8"))||{}}catch{return{}}}async function saveConfig(e){await A.writeFile(Ye,JSON.stringify(e,null,2))}__name(loadConfig,"loadConfig"),__name(saveConfig,"saveConfig");var Qe=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?Ke.info(`${e}: ${JSON.stringify(t)}`):Ke.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)=>{"provider"===e&&"anthropic"===t&&(Ke.error('Invalid provider "anthropic". Available provider: command-code'),process.exit(1));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),Ke.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?Ke.info("No configuration values set"):(Ke.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({}),Ke.success("Configuration reset successfully")})),Ze=new ke("Info"),Xe=new e("info").description("Display system information").option("-v, --verbose","Show verbose output").action(e=>{if(Ze.info("System Information:"),console.log("-------------------"),console.log(`${o.info} Date: ${formatDate()}`),console.log(`${o.info} Platform: ${T.platform()}`),console.log(`${o.info} Architecture: ${T.arch()}`),console.log(`${o.info} CPUs: ${T.cpus().length}`),console.log(`${o.info} Memory: ${Math.round(T.totalmem()/1024/1024/1024)} GB`),console.log(`${o.info} Home Directory: ${T.homedir()}`),e.verbose){console.log("\nDetailed CPU Information:"),T.cpus().forEach((e,t)=>{console.log(` CPU ${t}: ${e.model} @ ${e.speed} MHz`)}),console.log("\nNetwork Interfaces:");const e=T.networkInterfaces();Object.keys(e).forEach(t=>{const n=e[t];n&&n.forEach(e=>{"IPv4"!==e.family||e.internal||console.log(` ${t}: ${e.address}`)})})}Ze.success("Information displayed successfully!")});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 et=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 tt({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new nt(e,o,n,r);case 401:return new rt(e,o,n,r);case 403:return new ot(e,o,n,r);case 404:return new at(e,o,n,r);case 409:return new st(e,o,n,r);case 422:return new it(e,o,n,r);case 429:return new ct(e,o,n,r);default:return e>=500?new lt(e,o,n,r):new _APIError(e,o,n,r)}}},tt=class extends et{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)}},nt=class extends et{static{__name(this,"BadRequestError")}status=400},rt=class extends et{static{__name(this,"AuthenticationError")}status=401},ot=class extends et{static{__name(this,"PermissionDeniedError")}status=403},at=class extends et{static{__name(this,"NotFoundError")}status=404},st=class extends et{static{__name(this,"ConflictError")}status=409},it=class extends et{static{__name(this,"UnprocessableEntityError")}status=422},ct=class extends et{static{__name(this,"RateLimitError")}status=429},lt=class extends et{static{__name(this,"InternalServerError")}},dt=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 tt({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 a=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),a}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}),et.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"})}};async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new dt({baseUrl:e});return await t.get({endpoint:De.ALPHA.WHOAMI})}async function whoamiAction(){try{await getAuthKey()||(console.log(`${o.cross} ${p.red('Not authenticated. Please login using "cmd auth login"')}`),process.exit(1));const e=await getAuthenticatedEntity();e.success&&e.user||(console.log(`${o.cross} ${p.red("Failed to fetch user info")}`),process.exit(1)),console.log(`\n${p.bold("User Information:")}`),console.log(`${o.info} Name: ${p.cyan(e.user.name)}`),console.log(`${o.info} Email: ${p.cyan(e.user.email)}`),console.log(`${o.info} Username: ${p.cyan(e.user.userName)}`),e.org&&(console.log(`\n${p.bold("Organization:")}`),console.log(`${o.info} Name: ${p.cyan(e.org.name)}`),console.log(`${o.info} Login: ${p.cyan(e.org.login)}`)),console.log("")}catch(e){console.log(`${o.cross} ${p.red(`Error: ${e instanceof Error?e.message:"Unknown error"}`)}`),process.exit(1)}}__name(getAuthenticatedEntity,"getAuthenticatedEntity"),__name(whoamiAction,"whoamiAction");var ut=new e("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function getTastePath(e){const{target:t}=e;switch(t){case"local-project":return f.join(process.cwd(),".commandcode","taste");case"local-global":return f.join(T.homedir(),".commandcode","taste");case"remote-project":case"remote-user":throw new Error(`Remote storage not yet implemented: ${t}`);default:throw new Error(`Unknown storage target: ${t}`)}}function getRootTasteFile(e){const{target:t}=e;return f.join(getTastePath({target:t}),"taste.md")}function getCategoryPath(e){const{target:t,category:n}=e;return f.join(getTastePath({target:t}),n)}function getCategoryTasteFile(e){const{target:t,category:n}=e;return f.join(getCategoryPath({target:t,category:n}),"taste.md")}function parseTasteBuckets(e){const{content:t,sourcePath:n}=e,r=[],o=t.split(/^# /gm).filter(e=>e.trim());for(const e of o){const t=e.split("\n"),o=t[0].trim();if(e.includes("See ["))continue;const a=[];for(const e of t){const t=parseLearning({line:e});t&&a.push(t)}a.length>0&&r.push({category:normalizeCategory({category:o}),learnings:a,sourcePath:n})}return r}function parseLearning(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)[\.:,]?\s*confidence:\s*(\d*\.?\d+)/i);if(!n)return null;const r=parseFloat(n[2]);return isNaN(r)||r<0||r>1?null:{text:n[1].trim(),confidence:r}}function normalizeCategory(e){const{category:t}=e;return t.toLowerCase().replace(/\s+/g,"-")}function denormalizeCategory(e){const{slug:t}=e;return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function formatBucket(e){const{bucket:t}=e;let n=`# ${denormalizeCategory({slug:t.category})}\n`;for(const e of t.learnings)n+=`- ${e.text}. Confidence: ${e.confidence.toFixed(2)}\n`;return n}__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),__name(parseTasteBuckets,"parseTasteBuckets"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),__name(formatBucket,"formatBucket");var mt="# Taste (Continuously Learned by CommandCode)",gt=class{static{__name(this,"LocalProjectStorage")}target="local-project";async getAllBuckets(){const e=getTastePath({target:this.target});if(!K(e))return[];const t=[],n=getRootTasteFile({target:this.target});if(K(n)){const e=parseTasteBuckets({content:await A.readFile(n,"utf-8"),sourcePath:n});t.push(...e)}const r=await A.readdir(e,{withFileTypes:!0});for(const e of r)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(K(n)){const r=parseTasteBuckets({content:await A.readFile(n,"utf-8"),sourcePath:n});for(const t of r)t.category=e.name;t.push(...r)}}return t}async getBucket(e){const{category:t}=e;return(await this.getAllBuckets()).find(e=>e.category===t)||null}async writeBucket(e){const{bucket:t}=e,n=getTastePath({target:this.target});await A.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:this.target}),o=t.learnings.length,a=await this.removeBucket({category:t.category});o<=5?await this.writeToRoot({bucket:t,rootFile:r,categoryPosition:a}):await this.writeToSubdirectory({bucket:t,rootFile:r,categoryPosition:a})}async removeBucket(e){const{category:t}=e,n=getRootTasteFile({target:this.target});let r=null;if(K(n)){const e=(await A.readFile(n,"utf-8")).split("\n");let o=-1,a=-1;const s=new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i");for(let t=0;t<e.length;t++)if(s.test(e[t])){o=t;for(let n=t+1;n<e.length;n++)if(e[n].startsWith("# ")){let r=n-1;for(;r>t&&""===e[r].trim();)r--;a=r;break}-1===a&&(a=e.length-1);break}if(-1!==o){const t=e.slice(0,o),s=a<e.length-1?e.slice(a+1):[];r={before:t.join("\n").trim(),after:s.join("\n").trim()};const i=[...t,...s].join("\n").trim();""===i?await A.rm(n,{force:!0}):await A.writeFile(n,i+"\n","utf-8")}}const o=getCategoryTasteFile({target:this.target,category:t}),a=f.dirname(o);return K(a)&&await A.rm(a,{recursive:!0,force:!0}),r}async writeToRoot(e){const{bucket:t,rootFile:n,categoryPosition:r}=e,o=formatBucket({bucket:t});if(r){let e=r.before;e&&!e.trim().startsWith(mt)&&(e=mt+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o.trim(),r.after&&(e+="\n\n"+r.after),await A.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";K(n)&&(e=await A.readFile(n,"utf-8")),e?e.trim().startsWith(mt)||(e=mt+"\n\n"+e):e=mt+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o,await A.writeFile(n,e.trim()+"\n","utf-8")}}async writeToSubdirectory(e){const{bucket:t,rootFile:n,categoryPosition:r}=e,o=getCategoryTasteFile({target:this.target,category:t.category}),a=f.dirname(o);await A.mkdir(a,{recursive:!0});const s=formatBucket({bucket:t});await A.writeFile(o,s,"utf-8");const i=`# ${t.category}\nSee [${t.category}/taste.md](${t.category}/taste.md)\n`;if(r){let e=r.before;e&&!e.trim().startsWith(mt)&&(e=mt+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i.trim(),r.after&&(e+="\n\n"+r.after),await A.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";K(n)&&(e=await A.readFile(n,"utf-8")),e?e.trim().startsWith(mt)||(e=mt+"\n\n"+e):e=mt+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i,await A.writeFile(n,e.trim()+"\n","utf-8")}}exists(){const e=getTastePath({target:this.target});return K(e)}},pt=class{static{__name(this,"LocalGlobalStorage")}target="local-global";async getAllBuckets(){const e=getTastePath({target:this.target});if(!K(e))return[];const t=[],n=await A.readdir(e,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(K(n)){const r=parseTasteBuckets({content:await A.readFile(n,"utf-8"),sourcePath:n});for(const t of r)t.category=e.name;t.push(...r)}}return t}async getBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t});return K(n)&&parseTasteBuckets({content:await A.readFile(n,"utf-8"),sourcePath:n})[0]||null}async writeBucket(e){const{bucket:t}=e,n=getTastePath({target:this.target});await A.mkdir(n,{recursive:!0});const r=getCategoryTasteFile({target:this.target,category:t.category}),o=f.dirname(r);await A.mkdir(o,{recursive:!0});const a=formatBucket({bucket:t});await A.writeFile(r,a,"utf-8")}async deleteBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t}),r=f.dirname(n);K(r)&&await A.rm(r,{recursive:!0,force:!0})}async listBuckets(){const e=await this.getAllBuckets(),t=[];for(const n of e){let e;try{e=(await A.stat(n.sourcePath)).mtime}catch{e=new Date}t.push({category:n.category,learningCount:n.learnings.length,lastUpdated:e,filePath:n.sourcePath})}return t}exists(){const e=getTastePath({target:this.target});return K(e)}};async function prepareUploadFormData(e){const{packageName:t,bucket:n,description:r,type:o="category"}=e,a=new FormData;if(a.append("name",t),r&&a.append("description",r),a.append("type",o),"category"===o){const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});a.append("files[taste.md]",r)}else{const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});a.append("files[taste.md]",r);const o=getTastePath({target:"local-project"}),s=f.join(o,n.category);if(K(s)){const e=getCategoryTasteFile({target:"local-project",category:n.category});if(K(e)){const t=await A.readFile(e,"utf-8"),r=new Blob([t],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});a.append(`files[${n.category}/taste.md]`,o)}}}return a}async function prepareMultiplePackagesUpload(e){const{buckets:t,projectName:n,description:r}=e,o=new FormData;o.append("name",n),r&&o.append("description",r),o.append("type","project");const a=getRootTasteFile({target:"local-project"});if(K(a)){const e=await A.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});o.append("files[taste.md]",n)}for(const e of t){const t=getCategoryTasteFile({target:"local-project",category:e.category});if(K(t)){const n=await A.readFile(t,"utf-8"),r=new Blob([n],{type:"text/markdown"}),a=new File([r],"taste.md",{type:"text/markdown"});o.append(`files[${e.category}/taste.md]`,a)}}return o}function parseTasteContent(e){const t=[],n=e.split("\n");for(const e of n){const n=e.trim();if(!n||n.startsWith("#")||!n.startsWith("-"))continue;const r=n.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(r){const e=r[1].trim(),n=parseFloat(r[2]);e&&!isNaN(n)&&t.push({text:e,confidence:n})}}return t}__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),__name(parseTasteContent,"parseTasteContent");var ht=class{static{__name(this,"RemoteStorage")}async getAllBuckets(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");const t=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let e="Failed to list taste packages";try{const t=await n.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const a=[];for(const e of o)try{const t=await this.getBucket({category:e.name});t&&a.push(t)}catch(t){console.warn(`Warning: Failed to download package '${e.name}': ${t instanceof Error?t.message:String(t)}`)}return a}async downloadPackage(e){const{namespace:t,packageName:n}=e,r=await getAuthKey();if(!r)throw new Error("No API key found. Please authenticate with: cmd login");const o=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",t).replace(":packageName",n)}`,a=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!a.ok){if(404===a.status)return null;let e="Failed to download taste package";try{const t=await a.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:s}=await a.json();return{type:s.type||"category",files:s.files||[]}}async getBucket(e){const{category:t}=e;if(!await getAuthKey())throw new Error("No API key found. Please authenticate with: cmd login");const n=await getAuthenticatedEntity();if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");const r=n.user.userName;return this.downloadPackageToBucket({namespace:r,packageName:t})}async downloadPackageToBucket(e){const{namespace:t,packageName:n}=e,r=await this.downloadPackage({namespace:t,packageName:n});if(!r)return null;const o=r.files||[];if(0===o.length)return null;const a=o.find(e=>"taste.md"===e.file);if(!a)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`}}async writeBucket(e){const{bucket:t,namespace:n}=e,r=await getAuthKey();if(!r)throw new Error("No API key found. Please authenticate with: cmd login");const o=await prepareUploadFormData({packageName:t.category,bucket:t,type:"category"}),a=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,s=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:o});if(!s.ok){let e="Failed to upload taste package";try{const t=await s.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}await s.json()}async writeBuckets(e){const{buckets:t,projectName:n,namespace:r}=e,o=await getAuthKey();if(!o)throw new Error("No API key found. Please authenticate with: cmd login");const a=await prepareMultiplePackagesUpload({buckets:t,projectName:n}),s=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:a});if(!i.ok){let e="Failed to upload taste packages";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}await i.json()}async deleteBucket(e){throw new Error("Remote storage not yet implemented")}async listBuckets(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");const t=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let e="Failed to list taste packages";try{const t=await n.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:r}=await n.json();return(r.packages||[]).map(e=>({category:e.name,learningCount:e.learningCount||0,lastUpdated:e.createdAt?new Date(e.createdAt):new Date,filePath:""}))}async importBucket(e){throw new Error("Remote storage not yet implemented")}};function mergeLearnings(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},o=new Map;for(const e of n)o.set(e.text,e);const a=new Map(o);for(const e of t){const t=o.get(e.text);t?e.confidence>t.confidence?(a.set(e.text,e),r.updated++):(e.confidence,t.confidence,r.unchanged++):(a.set(e.text,e),r.added++)}for(const e of n)t.some(t=>t.text===e.text)||r.unchanged++;return{merged:Array.from(a.values()),details:r}}__name(mergeLearnings,"mergeLearnings");var ft=/confidence:/i;function validateTasteFile(e){const{content:t,filePath:n}=e,r=[];if(!t.trim())return r.push({severity:"error",message:"File is empty",suggestion:"Add at least one category with learnings"}),buildResult({issues:r,filePath:n});const o=t.split("\n");let a=null,s=null,i=0;for(let e=0;e<o.length;e++){const t=o[e],n=e+1;if(!t.trim())continue;if(t.trim().startsWith("# ")){if("# Taste (Continuously Learned by CommandCode)"===t.trim())continue;a&&0===i&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:s-1})||r.push({line:s,severity:"warning",message:`Category '${a}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),a=t.trim().substring(2).trim(),s=n,i=0;continue}if(t.trim().startsWith("-")){if(!a){r.push({line:n,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'});continue}i++;const e=validateLearningLine({line:t.trim(),lineNum:n});r.push(...e);continue}const c=t.trim();/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i.test(c)||r.push({line:n,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"})}return a&&0===i&&s&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:s-1})||r.push({line:s,severity:"warning",message:`Category '${a}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),buildResult({issues:r,filePath:n})}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=n+3;for(let e=n+1;e<t.length&&e<r;e++){const n=t[e];if(n.trim().startsWith("# "))break;if(n.includes("See [")&&n.includes("taste.md"))return!0}return!1}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!ft.test(o))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const a=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),s=a.length>0?a[a.length-1]:null;if(!s)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const i=s[1],c=parseFloat(i);if(isNaN(c))return r.push({line:n,severity:"error",message:`Confidence value "${i}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;c<0||c>1?r.push({line:n,severity:"error",message:`Confidence value ${c} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}):0===c&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});let l="";return l=s&&void 0!==s.index?o.substring(0,s.index).trim():o.trim(),l&&0!==l.length?l.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}):r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),o=t.filter(e=>"warning"===e.severity),a=0===r.length;let s;if(0===t.length)s=`✓ ${n} is valid`;else{const e=[];r.length>0&&e.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&e.push(`${o.length} warning${o.length>1?"s":""}`),s=`${r.length>0?"✗":"⚠"} ${n} has ${e.join(", ")}`}return{valid:a,issues:t,summary:s}}function formatValidationIssues(e){const{result:t,verbose:n=!0}=e;if(0===t.issues.length){const e=t.summary.charAt(0),n=t.summary.substring(2);return`${te.green(e)} ${te.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity),a=[r.length>0?te.red(t.summary):te.yellow(t.summary),""];if(r.length>0){a.push(te.bold(te.red("Errors:")));for(const e of r){const t=e.line?te.dim(` Line ${e.line}: `):" ";a.push(`${t}${te.red(e.message)}`),e.suggestion&&a.push(te.dim(` → ${e.suggestion}`))}a.push("")}if(o.length>0){a.push(te.bold(te.yellow("Warnings:")));for(const e of o){const t=e.line?te.dim(` Line ${e.line}: `):" ";a.push(`${t}${te.yellow(e.message)}`),e.suggestion&&a.push(te.dim(` → ${e.suggestion}`))}a.push("")}return a.join("\n").trim()}async function promptMergeStrategy(e){const{packageName:t,namespace:n,localBucket:r,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${r.learnings.length} learnings`),console.log(`Remote: ${a} learnings (from ${n})\n`);const i=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${r.learnings.length} → ${a} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});return s.isCancel(i)&&(s.cancel("Operation cancelled"),process.exit(0)),i}async function promptPushStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteBucket:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${a.learnings.length} learnings (in ${n})\n`);const i=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${a.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"}],initialValue:"merge"});return s.isCancel(i)&&(s.cancel("Operation cancelled"),process.exit(0)),i}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalBucket:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in global storage\n`)),console.log(`Local: ${n} learnings`),console.log(`Global: ${r.learnings.length} learnings\n`);const a=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${r.learnings.length} → ${n} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});return s.isCancel(a)&&(s.cancel("Operation cancelled"),process.exit(0)),a}async function promptGlobalPullStrategy(e){const{packageName:t,localBucket:n,globalLearningsCount:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${n.learnings.length} learnings`),console.log(`Global: ${r} learnings\n`);const a=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${n.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});return s.isCancel(a)&&(s.cancel("Operation cancelled"),process.exit(0)),a}async function push(e){const{buckets:t,target:n,overwrite:r=!1}=e,o=new gt,a={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!o.exists())return a.success=!1,a.errors.push({bucket:"all",error:"No taste directory found in project"}),a;const s=await o.getAllBuckets();if(0===s.length)return a.success=!1,a.errors.push({bucket:"all",error:"No taste packages found in project"}),a;for(const e of s){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){a.success=!1;const n=formatValidationIssues({result:t,verbose:!0});a.errors.push({bucket:e.category,error:`Validation failed for taste package in project:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in project has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(a.errors.length>0)return a;const i=t.length>0?s.filter(e=>t.includes(e.category)):s;if(t.length>0&&0===i.length){a.success=!1;for(const e of t)a.errors.push({bucket:e,error:"Taste package not found in project"});return a}let c,l;if("remote-project"===n||"remote-user"===n)try{const e=await getAuthenticatedEntity();e.success&&e.user?.userName&&(c=e.user.userName)}catch{}if("remote-project"===n&&0===t.length){const e=f.basename(process.cwd()),t=new ht;if(!c)return a.success=!1,a.errors.push({bucket:"all",error:"Failed to get user namespace for remote push"}),a;try{await t.writeBuckets({buckets:i,projectName:e,namespace:c,type:"project"}),a.bucketsPushed=i.map(e=>e.category);for(const e of i)a.filePaths[e.category]=`${c}/${e.category}`;return a}catch(e){return a.success=!1,a.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),a}}switch(n){case"local-global":l=new pt;break;case"remote-project":case"remote-user":l=new ht;break;default:return a.success=!1,a.errors.push({bucket:"all",error:`Invalid target: ${n}`}),a}for(const e of i)try{const t=await l.getBucket({category:e.category});let o;if(o=r?"overwrite":t&&"local-global"===n?await promptGlobalPushStrategy({packageName:e.category,localLearningsCount:e.learnings.length,globalBucket:t}):"merge","skip"===o)continue;if("overwrite"===o){if("local-global"===n)await l.writeBucket({bucket:e});else{if(!c)throw new Error("Failed to get user namespace for remote push");await l.writeBucket({bucket:e,namespace:c})}a.bucketsPushed.push(e.category),a.overwritten.push(e.category)}else{let r;if(t){const n=mergeLearnings({source:e.learnings,target:t.learnings});r={...e,learnings:n.merged},a.mergeDetails[e.category]=n.details}else r=e,a.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if("local-global"===n)await l.writeBucket({bucket:r});else{if(!c)throw new Error("Failed to get user namespace for remote push");await l.writeBucket({bucket:r,namespace:c})}a.bucketsPushed.push(e.category)}if("local-global"===n){const t=getCategoryTasteFile({target:"local-global",category:e.category});a.filePaths[e.category]=t}else"remote-project"!==n&&"remote-user"!==n||!c||(a.filePaths[e.category]=`${c}/${e.category}`)}catch(t){a.success=!1,a.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return a}async function pull(e){const{buckets:t,source:n,overwrite:r=!1}=e,o=new gt,a={success:!0,bucketsPulled:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},s=__name(()=>{switch(n){case"local-global":return"global";case"remote-project":return"remote project";case"remote-user":return"remote";default:return"source"}},"getSourceName")();let i,c;switch(n){case"local-global":i=new pt;break;case"remote-project":case"remote-user":i=new ht;break;default:return a.success=!1,a.errors.push({bucket:"all",error:`Invalid source: ${n}`}),a}try{c=await i.getAllBuckets()}catch(e){return a.success=!1,a.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),a}if(0===c.length)return a.success=!1,a.errors.push({bucket:"all",error:`No taste packages found in ${s}`}),a;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){a.success=!1;const n=formatValidationIssues({result:t,verbose:!0});a.errors.push({bucket:e.category,error:`Validation failed for taste package in ${s}:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in ${s} has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(a.errors.length>0)return a;const l=t.length>0?c.filter(e=>t.includes(e.category)):c;if(t.length>0&&0===l.length){a.success=!1;for(const e of t)a.errors.push({bucket:e,error:`Taste package not found in ${s}`});return a}for(const e of l)try{const t=await o.getBucket({category:e.category});let s;if(s=r?"overwrite":t&&"local-global"===n?await promptGlobalPullStrategy({packageName:e.category,localBucket:t,globalLearningsCount:e.learnings.length}):"merge","skip"===s)continue;if("overwrite"===s)await o.writeBucket({bucket:e}),a.bucketsPulled.push(e.category),a.overwritten.push(e.category);else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},a.mergeDetails[e.category]=r.details}else n=e,a.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),a.bucketsPulled.push(e.category)}const i=getCategoryTasteFile({target:"local-project",category:e.category});a.filePaths[e.category]=i}catch(t){a.success=!1,a.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return a}async function pullRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new gt,a=new ht,s={success:!0,bucketsPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};try{const e=await a.downloadPackage({namespace:t,packageName:n});if(!e)return s.success=!1,s.errors.push({bucket:n,error:"Taste package not found in remote"}),s;const{type:i,files:c}=e;for(const e of c){const t=validateTasteFile({content:e.content,filePath:e.file});if(!t.valid){s.success=!1;const r=formatValidationIssues({result:t,verbose:!0});s.errors.push({bucket:n,error:`Validation failed for ${e.file}:\n${r}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(s.errors.length>0)return s;"project"===i?await pullProjectPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:s}):await pullCategoryPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:s})}catch(e){s.success=!1,s.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return s}async function pullProjectPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:a,result:s}=e,i=t.find(e=>"taste.md"===e.file);if(i){const e=parseTasteBuckets({content:i.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processBucket({bucket:t,namespace:r,overwrite:o,targetStorage:a,result:s})}for(const e of t){if("taste.md"===e.file)continue;const t=e.file.replace("/taste.md",""),i={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processBucket({bucket:i,namespace:r,overwrite:o,targetStorage:a,result:s})}}async function processBucket(e){const{bucket:t,namespace:n,overwrite:r,targetStorage:o,result:a}=e;try{const e=await o.getBucket({category:t.category});let s;if(s=r?"overwrite":e?await promptMergeStrategy({packageName:t.category,namespace:n,localBucket:e,remoteLearningsCount:t.learnings.length}):"merge","skip"===s)return void a.skipped.push(t.category);if("overwrite"===s)await o.writeBucket({bucket:t}),a.bucketsPulled.push(t.category),a.overwritten.push(t.category);else{let n;if(e){const r=mergeLearnings({source:t.learnings,target:e.learnings});n={...t,learnings:r.merged},a.mergeDetails[t.category]=r.details}else n=t,a.mergeDetails[t.category]={added:t.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),a.bucketsPulled.push(t.category)}const i=getCategoryTasteFile({target:"local-project",category:t.category});a.filePaths[t.category]=i}catch(e){a.success=!1,a.errors.push({bucket:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullCategoryPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:a,result:s}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return s.success=!1,void s.errors.push({bucket:n,error:"No taste.md file found in category package"});const c={category:n,learnings:parseTasteContent(i.content),sourcePath:`remote:${n}`};await processBucket({bucket:c,namespace:r,overwrite:o,targetStorage:a,result:s})}async function pushRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new gt,a=new ht,s={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!o.exists())return s.success=!1,s.errors.push({bucket:n,error:"No taste directory found in project"}),s;try{const e=await o.getBucket({category:n});if(!e)return s.success=!1,s.errors.push({bucket:n,error:`Taste package '${n}' not found in local project`}),s;const i=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!i.valid){s.success=!1;const e=formatValidationIssues({result:i,verbose:!0});return s.errors.push({bucket:n,error:`Validation failed:\n${e}`}),s}if(i.issues.filter(e=>"warning"===e.severity).length>0){console.warn(`\nWarning: Taste package '${n}' has validation warnings:\n`);const e=formatValidationIssues({result:i,verbose:!0});console.warn(e+"\n")}const c=await a.downloadPackageToBucket({namespace:t,packageName:n});let l;if(l=r?"overwrite":c?await promptPushStrategy({packageName:n,namespace:t,localLearningsCount:e.learnings.length,remoteBucket:c}):"merge","skip"===l)return s;if("overwrite"===l)await a.writeBucket({bucket:e,namespace:t}),s.bucketsPushed.push(n),s.overwritten.push(n);else{let r;if(c){const t=mergeLearnings({source:e.learnings,target:c.learnings});r={...e,learnings:t.merged},s.mergeDetails[n]=t.details}else r=e,s.mergeDetails[n]={added:e.learnings.length,updated:0,unchanged:0};await a.writeBucket({bucket:r,namespace:t}),s.bucketsPushed.push(n)}s.filePaths[n]=`${t}/${n}`}catch(e){s.success=!1,s.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return s}async function list(e){const{location:t}=e;let n;switch(t){case"local-project":n=new gt;break;case"local-global":n=new pt;break;case"remote-project":case"remote-user":n=new ht;break;default:throw new Error(`Invalid location: ${t}`)}return n instanceof pt||n instanceof ht?await n.listBuckets():(await n.getAllBuckets()).map(e=>({category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}))}async function deleteBuckets(e){const{buckets:t,location:n}=e,r={success:!0,bucketsDeleted:[],errors:[]};let o;switch(n){case"local-global":o=new pt;break;case"remote-project":case"remote-user":o=new ht;break;case"local-project":return r.success=!1,r.errors.push({bucket:"all",error:"Cannot delete from local project via sync. Use taste clear instead."}),r;default:return r.success=!1,r.errors.push({bucket:"all",error:`Invalid location: ${n}`}),r}if(0===t.length)return r.success=!1,r.errors.push({bucket:"all",error:"No taste packages specified for deletion"}),r;for(const e of t)try{await o.deleteBucket({category:e}),r.bucketsDeleted.push(e)}catch(t){r.success=!1,r.errors.push({bucket:e,error:t instanceof Error?t.message:String(t)})}return r}async function lint(e){const{packages:t,target:n}=e,r={success:!0,filesLinted:[],errors:[],totalErrors:0,totalWarnings:0},o=getTastePath({target:n});if(!K(o))return r.success=!1,r.errors.push({file:"all",error:"No taste directory found in "+("local-global"===n?"global":"project")}),r;const a=[];if(t.length>0)for(const e of t){const t=getCategoryTasteFile({target:n,category:e});K(t)?a.push({path:t,displayName:`${e}/taste.md`}):(r.success=!1,r.errors.push({file:e,error:`Taste package '${e}' not found in ${"local-global"===n?"global":"project"}`}))}else{const e=getRootTasteFile({target:n});K(e)&&a.push({path:e,displayName:"taste.md"});const t=await A.readdir(o,{withFileTypes:!0});for(const e of t)if(e.isDirectory()){const t=getCategoryTasteFile({target:n,category:e.name});K(t)&&a.push({path:t,displayName:`${e.name}/taste.md`})}}if(0===a.length&&r.errors.length>0)return r;if(0===a.length)return r.success=!1,r.errors.push({file:"all",error:"No taste files found in "+("local-global"===n?"global":"project")}),r;for(const e of a){const t=validateTasteFile({content:await A.readFile(e.path,"utf-8"),filePath:e.displayName}),n=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);r.totalErrors+=n.length,r.totalWarnings+=o.length,t.valid||(r.success=!1);const a=formatValidationIssues({result:t});r.filesLinted.push({file:e.displayName,valid:t.valid,errors:n.length,warnings:o.length,formatted:a})}return r}async function open3(e){const{package:t,target:n}=e;try{let e;switch(n){case"local-project":e=new gt;break;case"local-global":e=new pt;break;case"remote-project":case"remote-user":e=new ht;break;default:throw new Error(`Invalid target: ${n}`)}const r=(await e.getAllBuckets()).find(e=>e.category===t);if(!r)return{success:!1,error:`Taste package '${t}' not found in ${"local-global"===n?"global":"project"}`};const o=r.sourcePath,a=await findCategoryLineNumber({filePath:o,category:t});return await ne([{file:o,line:a}]),{success:!0,filePath:o,lineNumber:a}}catch(e){return e instanceof Error&&e.message.includes("$EDITOR environment variable")?{success:!1,error:getEditorSetupInstructions()}:{success:!1,error:e instanceof Error?e.message:String(e)}}}async function findCategoryLineNumber(e){const{filePath:t,category:n}=e;try{const e=await A.readFile(t,"utf-8");if("taste.md"===f.basename(t)&&f.basename(f.dirname(t))===n)return 1;const r=e.split("\n");for(let e=0;e<r.length;e++)if(r[e].trim().toLowerCase()===`# ${n.toLowerCase()}`)return e+1;return 1}catch{return 1}}function getEditorSetupInstructions(){const e=re.platform;if("win32"===e)return'Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n\nCommand Prompt (as Administrator):\n setx EDITOR "code" # VS Code\n setx EDITOR "notepad" # Notepad\n setx EDITOR "vim" # Vim (if installed via WSL/Git Bash)\n\nPowerShell:\n [Environment]::SetEnvironmentVariable("EDITOR", "code", "User")\n\nThen restart your terminal.';const t="darwin"===e?"~/.zshrc":"~/.bashrc";return`Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n echo 'export EDITOR="code"' >> ${t} # VS Code\n echo 'export EDITOR="vim"' >> ${t} # Vim\n echo 'export EDITOR="nano"' >> ${t} # Nano\n echo 'export EDITOR="subl"' >> ${t} # Sublime Text\n\nFor bash users ${"darwin"===e?"(or ~/.bash_profile for bash)":"(or ~/.zshrc for zsh)"}, replace ${t} with the appropriate file.\n\nThen restart your terminal or run: source ${t}`}async function runMigrations(){await removeMetadataFile()}async function removeMetadataFile(){const e=f.join(T.homedir(),".commandcode","taste",".metadata.json");if(K(e))try{await A.unlink(e)}catch{}}__name(validateTasteFile,"validateTasteFile"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(validateLearningLine,"validateLearningLine"),__name(buildResult,"buildResult"),__name(formatValidationIssues,"formatValidationIssues"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptPushStrategy,"promptPushStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(push,"push"),__name(pull,"pull"),__name(pullRemote,"pullRemote"),__name(pullProjectPackage,"pullProjectPackage"),__name(processBucket,"processBucket"),__name(pullCategoryPackage,"pullCategoryPackage"),__name(pushRemote,"pushRemote"),__name(list,"list"),__name(deleteBuckets,"deleteBuckets"),__name(lint,"lint"),__name(open3,"open"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(runMigrations,"runMigrations"),__name(removeMetadataFile,"removeMetadataFile");var yt=class{static{__name(this,"TasteSyncManager")}constructor(){runMigrations().catch(()=>{})}async push(e){return await push(e)}async pull(e){return await pull(e)}async pullRemote(e){return await pullRemote(e)}async pushRemote(e){return await pushRemote(e)}async list(e){return await list(e)}async delete(e){return await deleteBuckets(e)}async lint(e){return await lint(e)}async open(e){return await open3(e)}};async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new dt({baseUrl:e}),n=await t.get({endpoint:De.ALPHA.NAMESPACES});if(!n.success)throw new Error("Failed to fetch namespaces");if("org"===n.type)return{userName:n.org.login,orgs:[]};const r=n.orgs.map(e=>({id:e.id,login:e.login,name:e.name}));return{userName:n.user.userName,orgs:r}}async function promptNamespaceSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const r=[{value:t,label:t,hint:"Personal"},...n.map(e=>({value:e.login,label:e.name||e.login,hint:"Organization"}))],o=await s.select({message:"Select namespace to push to\n",options:r,initialValue:t});return s.isCancel(o)&&(s.cancel("Operation cancelled"),process.exit(0)),o}function createTasteCommand(){const n=new e("taste");n.description("Manage taste learning packages");const r=new yt;return n.command("push").argument("[package]","Package name (optional if using --all)").option("-g, --global","Push to global storage").option("--remote","Push to remote (default)").option("--all","Push all packages").option("--overwrite","Overwrite target without prompting (default: interactive merge)").addOption(new t("--dev","Push to dev environment").hideHelp()).addOption(new t("--staging","Push to staging environment").hideHelp()).description("Push packages from project to remote or global storage (prompts on conflicts)").action(async(e,t)=>{try{let n;if(t.global||t.remote||(t.remote=!0),t.global&&t.remote&&(console.error(te.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste push <package> (pushes to remote by default)")),console.error(te.gray(" cmd taste push --all (pushes whole project)")),console.error(te.gray(" cmd taste push <package> -g (for global)")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1)),t.remote)if(t.all)n=await r.push({buckets:[],target:"remote-project",overwrite:t.overwrite});else{let o,a;if(e&&e.includes("/")){const[t,n]=e.split("/");t&&n||(console.error(te.red("Error: Invalid namespace/package format")),console.error(te.gray("Usage: cmd taste push --remote username/packageName")),console.error(te.gray(" cmd taste push --remote org-name/packageName")),process.exit(1)),o=t,a=n}else{e||(console.error(te.red("Error: Please specify a package name")),console.error(te.gray("Usage: cmd taste push <namespace>/<package>")),console.error(te.gray(" or: cmd taste push <package> (interactive namespace selection)")),process.exit(1)),a=e;let t;(await r.list({location:"local-project"})).some(e=>e.category===a)||(console.error(te.red(`Error: Taste package '${a}' not found in local project`)),process.exit(1));try{t=await fetchUserNamespaces()}catch(e){throw e}o=t.orgs.length>0?await promptNamespaceSelection(t):t.userName}n=await r.pushRemote({namespace:o,packageName:a,overwrite:t.overwrite})}else{const o="local-global",a=t.all?[]:[e];n=await r.push({buckets:a,target:o,overwrite:t.overwrite})}if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}let o=!1;if(1===n.bucketsPushed.length){const e=n.bucketsPushed[0],r=n.filePaths?.[e];if(t.overwrite)t.remote&&r?console.log(te.green(`✓ Replaced '${e}' taste package in ${r}`)):(console.log(te.green(`✓ Replaced '${e}' taste package in global`)),r&&console.log(te.gray(` Path: ${r}`)));else if(n.mergeDetails?.[e]){const a=n.mergeDetails[e],s=[];a.added>0&&s.push(`${a.added} ${1===a.added?"learning":"learnings"} added`),a.updated>0&&s.push(`${a.updated} ${1===a.updated?"learning":"learnings"} updated`),a.unchanged>0&&s.push(`${a.unchanged} ${1===a.unchanged?"learning":"learnings"} unchanged`),t.remote&&r?console.log(te.green(`✓ Pushed '${e}' taste package to ${r} (${s.join(", ")})`)):(console.log(te.green(`✓ Pushed '${e}' taste package to global (${s.join(", ")})`)),r&&console.log(te.gray(` Path: ${r}`))),(a.added>0||a.updated>0)&&a.unchanged>0&&(o=!0)}else t.remote&&r?console.log(te.green(`✓ Pushed '${e}' taste package to ${r}`)):(console.log(te.green(`✓ Pushed '${e}' taste package to global`)),r&&console.log(te.gray(` Path: ${r}`)))}else if(n.bucketsPushed.length>0){const e=t.remote?"remote":"global";if(console.log(te.green(`✓ Pushed ${n.bucketsPushed.length} taste packages (${n.bucketsPushed.join(", ")}) to ${e}`)),!t.overwrite&&n.mergeDetails)for(const e of Object.values(n.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){o=!0;break}}o&&console.log(te.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("pull").argument("[package]","Package name (optional if using --all)").option("-g, --global","Pull from global").option("--remote","Pull from remote").option("--all","Pull all packages").option("--overwrite","Overwrite local without prompting (default: interactive merge)").addOption(new t("--dev","Use dev environment").hideHelp()).addOption(new t("--staging","Use staging environment").hideHelp()).description("Pull packages from storage to project (prompts on conflicts)").action(async(e,t)=>{try{let n,o;if(t.global||t.remote||(t.remote=!0),t.global&&t.remote&&(console.error(te.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),t.remote&&t.all&&(console.error(te.red("Error: The --all flag is not supported for remote pull")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),t.remote&&!e&&(console.error(te.red("Error: Please provide both namespace and package name")),process.exit(1)),t.remote&&e&&!e.includes("/")&&(console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package> (remote by default)")),console.error(te.gray(" cmd taste pull <package> -g (from global)")),console.error(te.gray(" cmd taste pull --all -g (all from global)")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1)),t.remote){e.includes("/")||(console.error(te.red("Error: Package name must include namespace")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1));const[a,s]=e.split("/");a&&s||(console.error(te.red("Error: Invalid namespace/package format")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),o=a,n=await r.pullRemote({namespace:o,packageName:s,overwrite:t.overwrite})}else{const o="local-global",a=t.all?[]:[e];n=await r.pull({buckets:a,source:o,overwrite:t.overwrite})}const a=t.remote?o?`${o}`:"remote":"global";if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}if(n.skipped&&n.skipped.length>0)for(const e of n.skipped)console.log(te.yellow(`⊘ Skipped '${e}' - kept local version`));let s=!1;if(1===n.bucketsPulled.length){const e=n.bucketsPulled[0],r=n.filePaths?.[e];if(t.overwrite)console.log(te.green(`✓ Replaced '${e}' taste package in project`)),r&&console.log(te.gray(` Saved to: ${r}`));else if(n.mergeDetails?.[e]){const t=n.mergeDetails[e],o=[];t.added>0&&o.push(`${t.added} ${1===t.added?"learning":"learnings"} added`),t.updated>0&&o.push(`${t.updated} ${1===t.updated?"learning":"learnings"} updated`),t.unchanged>0&&o.push(`${t.unchanged} ${1===t.unchanged?"learning":"learnings"} unchanged`),console.log(te.green(`✓ Pulled '${e}' taste package from ${a} (${o.join(", ")})`)),r&&console.log(te.gray(` Saved to: ${r}`)),(t.added>0||t.updated>0)&&t.unchanged>0&&(s=!0)}else console.log(te.green(`✓ Pulled '${e}' taste package from ${a}`)),r&&console.log(te.gray(` Saved to: ${r}`))}else if(n.bucketsPulled.length>0){const e=` (${n.bucketsPulled.join(", ")})`;if(console.log(te.green(`✓ Pulled ${n.bucketsPulled.length} taste packages${e} from ${a}`)),!t.overwrite&&n.mergeDetails)for(const e of Object.values(n.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){s=!0;break}}s&&console.log(te.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("list").option("-g, --global","List global packages").option("--remote","List remote packages").addOption(new t("--dev","Use dev environment").hideHelp()).addOption(new t("--staging","Use staging environment").hideHelp()).description("List available packages").action(async e=>{try{let t,n;e.global&&e.remote&&(console.error(te.red("Error: Cannot specify both --global and --remote flags")),process.exit(1)),e.remote?(t="remote-project",n="remote"):e.global?(t="local-global",n="global"):(t="local-project",n="project");const o=await r.list({location:t});if(0===o.length)return void console.log(te.yellow(`No taste packages found in ${n}`));console.log(te.bold(`\n${n.charAt(0).toUpperCase()+n.slice(1)} Taste Packages:\n`));let a=0;for(const e of o){a+=e.learningCount;const t=getTimeAgo(e.lastUpdated);console.log(`${te.cyan(e.category)} (${e.learningCount} learnings, updated ${t})`)}console.log(te.gray(`\nTotal: ${o.length} taste packages, ${a} learnings\n`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("delete").argument("<package>","Package name to delete").option("-g, --global","Delete from global").description("Delete a package").action(async(e,t)=>{try{t.global||(console.error(te.red("Error: Currently only global is supported. Use -g flag.")),process.exit(1));const n=await r.delete({buckets:[e],location:"local-global"});if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}console.log(te.green(`✓ Deleted '${e}' taste package from global`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("lint").argument("[package]","Package name (required unless using --all)").option("-g, --global","Lint global taste files").option("--all","Lint all packages").description("Validate taste file format and structure").action(async(e,t)=>{try{e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste lint <package>")),console.error(te.gray(" cmd taste lint --all")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1));const n=await r.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(te.red(`Error: ${e.error}`));process.exit(1)}for(const e of n.filesLinted)console.log(e.formatted);if(n.filesLinted.length>1)if(console.log(""),0===n.totalErrors&&0===n.totalWarnings)console.log(te.green(`✓ All ${n.filesLinted.length} taste files are valid`));else{const e=[];n.totalErrors>0&&e.push(te.red(`${n.totalErrors} error${n.totalErrors>1?"s":""}`)),n.totalWarnings>0&&e.push(te.yellow(`${n.totalWarnings} warning${n.totalWarnings>1?"s":""}`)),console.log(`Summary: ${e.join(", ")} across ${n.filesLinted.length} files`)}n.success||process.exit(1)}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("open").argument("<package>","Package name to open").option("-g, --global","Open from global").description("Open a package in your editor").action(async(e,t)=>{try{const n=t.global?"local-global":"local-project",o=await r.open({package:e,target:n});o.success||(console.error(te.red(o.error)),process.exit(1)),console.log(te.green(`✓ Opened '${e}' taste package from ${t.global?"global":"project"}`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n}function getTimeAgo(e){const t=(new Date).getTime()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),o=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${o} day${o>1?"s":""} ago`}function getPackageJson(){const e=import.meta.url,t=ae(e),n=w(t);return JSON.parse(Y(E(n,"./../package.json"),"utf8"))}__name(fetchUserNamespaces,"fetchUserNamespaces"),__name(promptNamespaceSelection,"promptNamespaceSelection"),__name(createTasteCommand,"createTasteCommand"),__name(getTimeAgo,"getTimeAgo"),__name(getPackageJson,"getPackageJson");var wt=getPackageJson(),Et=y.join(k.homedir(),".commandcode"),bt=y.join(Et,"update-status.json"),vt=y.join(Et,"update-failed.json");function ensureCommandCodeDir(){J.existsSync(Et)||J.mkdirSync(Et,{recursive:!0})}async function checkForUpdateAvailable(){try{const e=n("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3}),t=JSON.parse(e),r=wt.version,o=r.includes("alpha"),a=t.filter(e=>!e.includes("alpha")),s=t.filter(e=>e.includes("alpha"));let i=r,c=!1;if(a.length>0){const e=a.sort(oe.rcompare)[0];oe.gt(e,r)&&(i=e,c=!0)}if(!c&&o&&s.length>0){const e=s.sort(oe.rcompare)[0];oe.gt(e,r)&&(i=e,c=!0)}return{currentVersion:r,latestVersion:i,updateAvailable:c}}catch(e){return null}}async function performAutoUpdate(e){const{silent:t=!1,updateInfo:r,onProgress:o}=e||{},a=r||await checkForUpdateAvailable();if(!a||!a.updateAvailable)return{success:!1};o?.(`Updating to v${a.latestVersion}...`);try{n(`npm i -g command-code@${a.latestVersion}`,{stdio:"ignore",env:{...process.env,NODE_NO_WARNINGS:"1"}}),ensureCommandCodeDir();const e={updatedFrom:a.currentVersion,updatedTo:a.latestVersion,updatedAt:Date.now()};return J.writeFileSync(bt,JSON.stringify(e,null,2)),{success:!0}}catch(e){console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code"),ensureCommandCodeDir();const t={currentVersion:a.currentVersion,latestVersion:a.latestVersion,failedAt:Date.now()};return J.writeFileSync(vt,JSON.stringify(t,null,2)),{success:!1,updateInfo:a}}}function getUpdateStatus(){try{if(ensureCommandCodeDir(),J.existsSync(bt)){const e=JSON.parse(J.readFileSync(bt,"utf-8"));return J.unlinkSync(bt),e}}catch(e){}return null}function getFailedUpdateInfo(){try{if(ensureCommandCodeDir(),J.existsSync(vt)){const e=JSON.parse(J.readFileSync(vt,"utf-8"));return J.unlinkSync(vt),{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 Ct=new e("update").description("Update Command Code to the latest version").option("--check","Check for updates without installing").action(async e=>{if(e.check){console.log(te.dim("Checking for updates..."));const e=await checkForUpdateAvailable();if(!e)return console.log(te.red("✗ Failed to check for updates")),void console.log(te.dim("Please check your internet connection or try again later."));e.updateAvailable?(console.log(te.bold("Update available!")),console.log(te.dim("Current: ")+te.white(e.currentVersion)),console.log(te.dim("Latest: ")+te.bold.green(e.latestVersion)),console.log(te.dim("Run ")+te.cyan("cmd update")+te.dim(" to install."))):console.log(te.green("✓ Already on latest version ")+te.dim(`(${e.currentVersion})`))}else{console.log(te.dim("Checking for updates..."));const e=await checkForUpdateAvailable();if(!e)return console.log(te.red("✗ Failed to check for updates")),void console.log(te.dim("Please check your internet connection or try again later."));if(!e.updateAvailable)return void console.log(te.green("✓ Already on latest version ")+te.dim(`(${e.currentVersion})`));console.log(te.dim("Current: ")+te.white(e.currentVersion)),console.log(te.dim("Latest: ")+te.bold.green(e.latestVersion)),console.log(te.dim(`\nUpdating command-code from ${e.currentVersion} → `)+te.white(e.latestVersion)+te.dim("...")),(await performAutoUpdate({silent:!0,updateInfo:e})).success?(console.log(te.green("\n✓ Successfully updated to ")+te.bold(e.latestVersion)),console.log(te.dim("Run ")+te.cyan("cmd")+te.dim(" to start using the new version."))):(console.log(te.red("✗ Update failed")),console.log(te.dim("Please try updating manually:")),console.log(te.cyan("npm i -g command-code")),process.exit(1))}}),Tt=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:o=process.cwd(),env:a=process.env}=t;return new Promise(t=>{const s=r("/bin/bash",["-c",e],{cwd:o,env:{...a},stdio:["pipe","pipe","pipe"]});let i="",c="",l=null;n>0&&(l=setTimeout(()=>{s.kill("SIGTERM"),t({stdout:i,stderr:c+(c?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),s.stdout?.on("data",e=>{i+=e.toString()}),s.stderr?.on("data",e=>{c+=e.toString()}),s.on("close",n=>{l&&clearTimeout(l),t({stdout:i.trim(),stderr:c.trim(),exitCode:n??0,command:e})}),s.on("error",n=>{l&&clearTimeout(l),t({stdout:i,stderr:c+`\n[Error: ${n.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),kt=__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"),At="read_file",Pt="edit_file",St="write_file",xt="read_directory",$t="read_multiple_files",It="grep",Dt="shell_command",Rt="think",Ft="todo_write",jt="web_search",Mt="web_fetch",Nt=__name(e=>e===jt,"isWebSearchTool");function toRelativePath(e){const t=global.COMMAND_CODE_CWD||process.cwd(),n=process.env.HOME||process.env.USERPROFILE||"",r=f.relative(t,e);return r.startsWith("..")?n&&e.startsWith(n)?e.replace(n,"~"):e:""===r?f.basename(e):r}function replacePathsInText(e){if(!e||"string"!=typeof e)return e;let t=e;return t=t.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,e=>f.isAbsolute(e)?toRelativePath(e):e),t=t.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),t}__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText");var _t=D.object({id:D.string(),timestamp:D.number(),type:D.literal("image"),source:D.object({type:D.enum(["base64","url"]),media_type:D.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:D.string()})}),Ot=D.object({id:D.string(),timestamp:D.number(),input:D.string(),output:D.string().optional(),metadata:D.record(D.string(),D.any()).optional(),images:D.array(_t).optional().default([])}),Ut=Ot.extend({role:D.literal("user")}),Lt=Ot.extend({role:D.literal("assistant")}),Bt=Ot.extend({role:D.literal("tool"),name:D.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),Wt=Ot.extend({role:D.literal("bash"),command:D.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),zt=Ot.extend({role:D.literal("system")}),Gt=Ot.extend({role:D.literal("error")}),Vt=Ot.extend({role:D.literal("info")}),qt=D.discriminatedUnion("role",[Ut,Lt,Bt,Wt,zt,Gt,Vt]),Ht=__name((e,t)=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),Jt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e}),"createInfoEntry"),Kt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),Yt=__name((e,t,n)=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Qt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),Zt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Xt=__name(e=>qt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),en=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return qt.parse(n)},"updateEntryWithOutput"),tn=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),nn=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),rn=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),on=["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…"],an=__name(()=>on[Math.floor(Math.random()*on.length)],"getRandomLLMStatus"),sn=__name(e=>{switch(e){case At:return"Read";case Pt:return"Edit";case St:return"Write";case xt:return"List";case $t:return"Read Multiple";case It:return"Search";case Dt:return"Shell";case Ft:return"Todos";case Rt:return"Thinking…";case jt:return"Web Search";case Mt:return"Web Fetch";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),cn=__name((e,t)=>{try{switch(e){case At:case St:const e=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(e);case Pt:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case xt:return toRelativePath(t.path||"directory");case It:const n=t.path||"files";return`"${t.pattern}" in ${toRelativePath(n)}`;case Dt:if(t.command){const e=Array.isArray(t.args)&&t.args.length>0?` ${t.args.join(" ")}`:"string"==typeof t.args&&t.args?` ${t.args}`:"";return`${t.command}${e}`}return t.command||"";case Ft:return`${t.todos?t.todos.length:0} items`;case Rt:return t.content||"planning";case $t:const r=t.include||[];return Array.isArray(r)?r.join(", "):"multiple files";case jt:return t.query||"search";case Mt:return t.url||"fetch";default:const o=t?.messages||[];if(Array.isArray(o)&&o.length>0&&o[0]&&"object"==typeof o[0]&&"content"in o[0]){const e=o[0].content;if("string"==typeof e)return e.slice(0,50)+(e.length>50?"...":"")}return JSON.stringify(t||{})}}catch{return"parameters"}},"getToolInputContent"),ln=__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"),dn=__name(()=>{const[e,t]=F({isExecuting:!1,currentCommand:null});return{executeBash:N(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Tt(e,{timeout:3e4,cwd:process.cwd()}),o=kt(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]=en(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]=en(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var un=D.object({absolutePath:D.string().describe("The absolute path to the file to read"),offset:D.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:D.number().optional().describe("Optional number of lines to read")});D.object({content:D.union([D.string(),D.instanceof(Buffer)]),contentType:D.enum(["text","binary"]),fileType:D.string(),size:D.number(),linesRead:D.number().optional()});var mn=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(!f.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw new mn("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=f.normalize(t);try{await A.access(o,H.constants.F_OK|H.constants.R_OK)}catch{throw new mn(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await A.stat(o)).isFile())throw new mn("Path does not point to a file","NOT_A_FILE");const a=getFileType(o),s=isBinaryFile(a);if(void 0!==n&&void 0===r||void 0===n&&void 0!==r)throw new mn("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new mn("Offset must be >= 0","INVALID_OFFSET");if(void 0!==r&&r<=0)throw new mn("Limit must be > 0","INVALID_LIMIT");try{if(s){const e=await A.readFile(o);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==n&&void 0!==r){const e=await readTextFileLines(o,n,r);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await A.readFile(o,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof mn)throw e;throw new mn(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var gn={".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=f.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",...gn}[t]||"unknown"}function isBinaryFile(e){return Object.values(gn).includes(e)}async function readTextFileLines(e,t,n){const r=(await A.readFile(e,"utf8")).split(/\r?\n/),o=t,a=Math.min(o+n,r.length),s=r.slice(o,a);return{content:s.join("\n"),linesRead:s.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=f.isAbsolute(o)?o:f.resolve(process.cwd(),o),a=await readFileContent({absolutePath:e});if("binary"===a.contentType)continue;const s=String(a.content),i=f.relative(process.cwd(),e),c=1e5;if(s.length>c){t.push({token:r,resolvedPath:e,content:"",tooLarge:!0});const o=`${i}`;n=n.replace(r,o);continue}t.push({token:r,resolvedPath:e,content:s});const l=`{${i}: ${s}}`;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=`{${f.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 pn={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=un.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading file`}},"execute")},hn=D.object({filePath:D.string().describe("The absolute path to the file to edit"),oldValue:D.string().describe("The text to replace"),newValue:D.string().describe("The new text to insert"),replacementCount:D.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:D.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:a=1}=e;if(!t)throw createFileEditError("filePath is required","INVALID_PATH");if(!f.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&&a<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await Q.access(t,Z.F_OK|Z.R_OK|Z.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${t}`,"FILE_ACCESS_ERROR")}let s;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");s=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 i=(s.match(new RegExp(escapeRegExp(n),"g"))||[]).length;if(0===i)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let c,l;if(o)c=i;else if(c=a,c>i)throw createFileEditError(`Expected ${c} replacements, but only found ${i} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||c===i)l=s.split(n).join(r),d=i;else{l=s;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 Q.writeFile(t,l,"utf-8"),{path:t,replacementsCount:d,oldContent:s,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}D.object({path:D.string(),replacementsCount:D.number(),oldContent:D.string(),newContent:D.string()}),D.object({name:D.string(),message:D.string(),code:D.string().optional()}),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),__name(formatOutput2,"formatOutput");var fn={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=hn.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while editing file`}},"execute")},yn=D.object({path:D.string().describe("The absolute path to the directory to read"),exclude:D.array(D.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:D.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});D.object({files:D.array(D.string()),directories:D.array(D.string())});var wn=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(!f.isAbsolute(t))throw new wn("Path must be absolute, not relative","INVALID_PATH");try{if(!(await A.stat(t)).isDirectory())throw new wn("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof wn)throw e;throw new wn(`Directory does not exist or is not accessible: ${t}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await A.readdir(t);let o=[];r&&(o=await loadGitIgnorePatterns(t));const a=[...n,...o],s=[],i=[];for(const n of e){if(shouldIgnoreEntry(n,a))continue;const e=f.join(t,n);try{const t=await A.stat(e);t.isDirectory()?i.push(n):t.isFile()&&s.push(n)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:s.sort(),directories:i.sort()}}catch(e){if(e instanceof wn)throw e;throw new wn(`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=f.resolve(e);const r=await findGitRoot(e);for(;n&&isWithinGitRoot(n,r);){const e=f.join(n,".gitignore");try{const n=(await A.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));t.push(...n)}catch(e){}const r=f.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=f.resolve(e);for(;;){try{const e=f.join(t,".git");if((await A.stat(e)).isDirectory())return t}catch{}const e=f.dirname(t);if(e===t)throw new Error("Not in a git repository");t=e}}function isWithinGitRoot(e,t){const n=f.resolve(e),r=f.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(se(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 En={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=yn.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading directory`}},"execute")},bn=D.object({filePath:D.string().describe("The absolute path where the file should be written"),content:D.string().describe("The content to write to the file")});async function writeFile5({filePath:e,content:t}){if(!v(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=w(e);return K(n)||await S(n,{recursive:!0}),await x(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}`}D.object({success:D.boolean(),message:D.string(),path:D.string().optional()}),__name(writeFile5,"writeFile"),__name(formatOutput4,"formatOutput");var vn={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=bn.parse(e),n=await writeFile5(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")},Cn=D.object({include:D.array(D.string()).describe("Array of glob patterns to include files"),exclude:D.array(D.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:D.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:D.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:D.string().optional().describe("Base directory for relative paths. Default: current working directory")}),Tn=D.object({filePath:D.string(),content:D.string(),fileType:D.string(),size:D.number()});D.object({content:D.string(),filesRead:D.array(D.string()),errors:D.array(D.object({file:D.string(),error:D.string()})),fileDetails:D.array(Tn)});var kn=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},An=["**/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 a of e)try{(await ie(a,{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 "${a}": ${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:a=process.cwd()}=e;if(!t||0===t.length)throw new kn("At least one include pattern must be provided","NO_PATTERNS");const s=y.resolve(a),i={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(...An);const a=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:s});for(const e of a)try{const t=y.resolve(s,e),n=await readFileContent({absolutePath:t}),r=processFileResult({content:n,filePath:e});i.fileDetails.push(r),i.content+=`\n// File: ${e} (${n.fileType})\n`,i.content+=r.content,i.content+="\n",i.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);i.errors.push({file:e,error:n}),i.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return i}catch(e){if(e instanceof kn)throw e;throw new kn(`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 Pn={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=Cn.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading multiple files`}},"execute")},Sn=D.object({pattern:D.string().min(1,"Pattern is required"),include:D.array(D.string()).optional(),directory:D.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,o)=>{const a=r(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",i="";a.stdout?.on("data",e=>{s+=e.toString()}),a.stderr?.on("data",e=>{i+=e.toString()}),a.on("close",e=>{0===e?n(s):1!==e||i?o(new Error(i||`Command failed with exit code ${e}`)):n("")}),a.on("error",e=>{o(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(a){if(!(a instanceof Error&&a.message.includes("ENOENT")))throw a;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 a=e.trim().split("\n"),s=[];for(const e of a){const t=parseGrepLine(e);t&&s.push(t)}return s}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 xn={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=Sn.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while searching files`}},"execute")},$n=D.object({command:D.string().min(1,"Command cannot be empty"),args:D.array(D.string()).optional(),directory:D.string().optional(),timeout:D.number().optional()}),In=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,a,s){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=a,this.duration=s}};async function executeShellCommand(e){const{command:t,args:n=[],directory:o,timeout:a=3e4}=e,s=Date.now();if(!t.trim())throw new In("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(f.isAbsolute(o))throw new In("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=f.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await P.stat(i)).isDirectory())throw new In(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof In)throw e;throw new In(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:i,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((o,i)=>{let c="",l="",d=!1;const u=n.length>0?ce([t,...n]):t,m=setTimeout(()=>{if(!d){g.kill("SIGTERM");const e=Date.now()-s;i(new In(`Command timed out after ${a}ms`,"TIMEOUT",null,"SIGTERM",c,l,e))}},a),g=r(u,[],e);g.stdout?.on("data",e=>{c+=e.toString()}),g.stderr?.on("data",e=>{l+=e.toString()}),g.on("close",(e,t)=>{d=!0,clearTimeout(m);const n=Date.now()-s;0===e?o({stdout:c.trim(),stderr:l.trim(),exitCode:e,signal:t,duration:n}):i(new In(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,c.trim(),l.trim(),n))}),g.on("error",e=>{d=!0,clearTimeout(m);const t=Date.now()-s;i(new In(`Failed to start command: ${e.message}`,"START_FAILED",null,null,c.trim(),l.trim(),t))})})}catch(e){if(e instanceof In)throw e;throw new In(`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 Dn={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=$n.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${o.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${o.cross} Error: ${e.message}`}return`${o.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}__name(think,"think");var Rn={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 Fn={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};function getRootAgentDir(){return y.join(k.homedir(),".commandcode","agents")}function getLocalAgentDir(){return y.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,t){try{const n=(await P.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=y.join(e,n),o=await P.readFile(r,"utf-8"),{data:a,content:s}=le(o);let i=a.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:a.name||n.replace(".md",""),description:a.description||"",tools:i,systemPrompt:s.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}}async function loadAllAgents(){const[e,t]=await Promise.all([loadAgentsFromDirectory(getRootAgentDir(),"personal"),loadAgentsFromDirectory(getLocalAgentDir(),"project")]);return{personal:e,project:t}}__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents");var jn=2e5;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)}function getEnterpriseMemoryPath(){switch(T.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return f.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const e=T.homedir();return f.join(e,".commandcode","AGENTS.md")}function getProjectMemoryPaths(e){return[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:K(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(K(n)){t.push({type:"project",path:n,exists:!0,description:"Team-shared project instructions"});break}t.find(e=>"project"===e.type)||t.push({type:"project",path:e[0],exists:!1,description:"Team-shared project instructions"})}const o=getUserMemoryPath();return t.push({type:"user",path:o,exists:K(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return K(e)?await A.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}async function processImports(e,t,n=0,r=5){if(n>=r)return e;const o=[],a=e.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),s=Array.from(a.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let i=a;for(const e of s){const o=e[1];let a=o;o.startsWith("~/")?a=f.join(T.homedir(),o.slice(2)):f.isAbsolute(o)||(a=f.resolve(f.dirname(t),o));const s=await loadMemoryFile(a);if(s){const t=await processImports(s,a,n+1,r);i=i.replace(e[0],`\n# Imported from ${o}\n${t}\n`)}}return i=i.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>o[parseInt(t)]),i}async function loadAllMemories(e,t){const n=new Map,r=getEnterpriseMemoryPath();if(K(r)){const e=await loadMemoryFile(r);if(e){const t=await processImports(e,r);n.set(r,t)}}const o=getUserMemoryPath();if(K(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);n.set(o,t)}}const a=[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")];for(const e of a)if(K(e)){const t=await loadMemoryFile(e);if(t){const r=await processImports(t,e);n.set(e,r)}break}if(t&&t.length>0)for(const r of t){const t=f.isAbsolute(r)?f.dirname(r):f.dirname(f.resolve(e,r));if(t.startsWith(e)&&t!==e){const r=[];let o=t;for(;o.startsWith(e)&&o!==e;)r.push(o),o=f.dirname(o);for(const e of r.reverse()){const t=[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")];for(const e of t)if(K(e)&&!n.has(e)){const t=await loadMemoryFile(e);if(t){const r=await processImports(t,e);n.set(e,r)}break}}}}return n}async function openInEditor(e){const t=process.env.EDITOR||process.env.VISUAL||"code",n=f.dirname(e);return K(n)||await A.mkdir(n,{recursive:!0}),K(e)||await A.writeFile(e,"# AGENTS.md\n\n","utf-8"),new Promise((n,o)=>{const a=r(t,[e],{stdio:"inherit",shell:!0});a.on("exit",e=>{0===e?n():o(new Error(`Editor exited with code ${e}`))}),a.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),o(e)})})}async function initProjectMemory(e){const t=f.join(e,"AGENTS.md");return K(t)||await A.writeFile(t,"# Memory\n\n## Project Overview\nSee @README.md for project overview and @package.json for available npm/pnpm commands for this project.\n\n## Code Style Guidelines\n- Use descriptive variable names\n- Follow existing patterns in the codebase\n- Extract complex conditions into meaningful boolean variables\n\n## Architecture Notes\nAdd important architectural decisions and patterns here.\n\n## Common Workflows\nDocument frequently used workflows and commands here.\n","utf-8"),t}async function getMemoryContent(e){try{const t=process.cwd(),n=await loadAllMemories(t,e);if(0===n.size)return null;const r=[],o=getEnterpriseMemoryPath(),a=getUserMemoryPath(),s=[f.join(t,"AGENTS.md"),f.join(t,".commandcode","AGENTS.md")];n.has(o)&&r.push(`# Memory from: ${o}\n\n${n.get(o)}`),n.has(a)&&r.push(`# Memory from: ${a}\n\n${n.get(a)}`);for(const e of s)if(n.has(e)){r.push(`# Memory from: ${e}\n\n${n.get(e)}`);break}for(const[e,t]of n)e===o||e===a||s.includes(e)||r.push(`# Memory from: ${e}\n\n${t}`);return r.join("\n\n---\n\n")}catch(e){return null}}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),__name(getEnterpriseMemoryPath,"getEnterpriseMemoryPath"),__name(getUserMemoryPath,"getUserMemoryPath"),__name(getProjectMemoryPaths,"getProjectMemoryPaths"),__name(discoverMemoryFiles,"discoverMemoryFiles"),__name(loadMemoryFile,"loadMemoryFile"),__name(function getCodeBlockRegex(){return/```[\s\S]*?```|`[^`]+`/g},"getCodeBlockRegex"),__name(function getImportRegex(){return/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm},"getImportRegex"),__name(processImports,"processImports"),__name(loadAllMemories,"loadAllMemories"),__name(openInEditor,"openInEditor"),__name(initProjectMemory,"initProjectMemory"),__name(getMemoryContent,"getMemoryContent");var Mn=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return y.join(k.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return ue(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=y.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=y.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=n("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await P.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),!1}}async isProjectInitialized(){try{return(await P.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 P.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=y.join(this.projectPath,`${t}.jsonl`);try{const e=(await P.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=cn(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=cn(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=y.join(this.projectPath,`${t}.jsonl`);try{const e=(await P.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=y.join(e,t);try{return(await P.stat(n)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=y.join(e,t);try{return await P.mkdir(n,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=y.join(_SessionManager.getProjectsBasePath(),e);try{try{await P.access(t)}catch{return[]}const e=(await P.readdir(t)).filter(e=>e.endsWith(".jsonl")),n=[];for(const r of e){const e=r.replace(".jsonl",""),o=y.join(t,r);try{const r=await P.stat(o),a=(await P.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(a.length>0){let o="",s="";const i=JSON.parse(a[0]);i.gitBranch&&(s=i.gitBranch);for(const e of a){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:a.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=y.join(this.projectPath,`${this.sessionId}.share.json`);try{await P.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=y.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await P.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=y.join(this.projectPath,`${this.sessionId}.share.json`);try{await P.unlink(e)}catch(e){}}},Nn=new ke("AgentExecutor");function agentToTool(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a}=t;return{name:e.name,description:e.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object"}}},required:["messages"]},execute:__name(async(t,s)=>{let i=getAvailableTools(e,{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a});if(s?.onFeedUpdate){const n=cn(e.name,t),r={id:`${e.name}-tool-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:"Running..."};s.onFeedUpdate(r)}const c=await getConfiguredProvider(),l=await isOAuthEnforced();let d;c===je&&(d=await Me.getValidAccessToken(),validateOAuthToken({token:d,provider:c}));const u=getApiBaseUrl(),m=new dt({baseUrl:u});let g=0;const p=[];if(Array.isArray(t?.messages)&&t?.messages.length>0)for(const e of t.messages)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&p.push({role:"user",content:t})}const h={stream:!0,messages:p,max_tokens:64e3,system:e.systemPrompt,temperature:.3,tools:i,model:"anthropic:claude-sonnet-4-20250514"},y=await isTasteLearningEnabled(),w={[$e]:Mn.getCurrentProjectDirName(),[Ie]:y.toString(),[Se]:l.toString()};d&&(w[xe]=`Bearer ${d}`);const E=getEnvironmentContext(),b=await getMemoryContent([]);let v="",C=!0;for(;C;){if(s?.abortSignal?.aborted)throw new Error("Interrupted by user");if(0===g&&p.length>0){const e=p[p.length-1];g=estimateTokens(e)}const e=await callAPIWithRetry({request:m,body:{config:E,memory:b,params:{...h,messages:p}},headers:w,abortSignal:s?.abortSignal,onTextDelta:__name(e=>{g+=estimateTokens(e)},"onTextDelta")}),t=e.content.filter(e=>"tool_use"===e.type);if(v=e.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(e,s):e.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===t.length){const t=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);t.length>0&&p.push({role:"assistant",content:t}),C=!1;break}const n=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);n.length>0&&p.push({role:"assistant",content:n});const r=[],o=new Set;let a=!1;for(const e of t){if(s?.abortSignal?.aborted)throw new Error("Interrupted by user");let t=e.input;try{if(["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&s?.onPermissionRequest&&!await s.onPermissionRequest(e.name,t)){Nn.debug(`Permission denied for tool: ${e.name}`),a=!0;break}if("object"==typeof t&&null!==t){const n={...t};let r=!1;const o=["path","file_path","absolutePath","filePath","directory","folder"];for(const e of o)if(e in n&&"string"==typeof n[e]){const t=n[e];if(!f.isAbsolute(t)){const o=f.resolve(process.cwd(),t);n[e]=o,r=!0,Nn.debug(`Converted '${e}': '${t}' -> '${o}'`)}}"paths"in n&&Array.isArray(n.paths)&&(n.paths=n.paths.map(e=>"string"!=typeof e||f.isAbsolute(e)?e:(r=!0,f.resolve(process.cwd(),e)))),r?(t=n,Nn.debug(`Resolved input for ${e.name}: ${JSON.stringify(t,null,2)}`)):Nn.debug(`No path resolution needed for ${e.name}: ${JSON.stringify(t,null,2)}`)}if(s?.onFeedUpdate){const n=cn(e.name,t),r={id:`${e.name}-${e.id}-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:"Processing…"};s.onFeedUpdate(r)}const n=await executeTool(e.name,t,s),i=estimateTokens(n);if(g+=i,s?.abortSignal?.aborted)throw new Error("Interrupted by user");const c=checkToolOutputTokensLimit(n,e.name);if(r.push({type:"tool_result",tool_use_id:e.id,content:c}),o.add(e.id),s?.onFeedUpdate){const n=cn(e.name,t),r={id:`${e.name}-${e.id}-complete-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:c};s.onFeedUpdate(r)}Nn.debug(`Tool executed successfully: ${e.name}`)}catch(n){const a=n instanceof Error?n.message:"Unknown error";if(r.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${a}`,is_error:!0}),o.add(e.id),s?.onFeedUpdate){const n=cn(e.name,t),r={id:`${e.name}-${e.id}-error-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:`Error: ${a}`};s.onFeedUpdate(r)}Nn.error(`Tool execution failed: ${e.name} - ${a}`)}}if(a){const e=p[p.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?o.has(e.id):"text"===e.type);t.length>0?e.content=t:p.pop()}C=!1;break}const i=[...r];p.push({role:"user",content:i})}return v||"DONE"},"execute")}}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a}=t;let s=[];if("*"===e.tools)s=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){const t=a[e];if(t){const e=o.get(t);if(e)s.push(e);else{const e=r.find(e=>e.name===t);e&&s.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){const e=a[t];if(e){const t=o.get(e);if(t)s.push(t);else{const t=r.find(t=>t.name===e);t&&s.push(t)}}}return s}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:a}=e;let s=null;for(let e=0;e<5;e++)try{const e=await t.post({body:n,stream:!0,endpoint:De.ALPHA.GENERATE,signal:o,headers:r}),s=de.fromReadableStream(e);a&&s.on("text",a);let i=null;s.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await s.finalMessage();if(i)throw i;return c}catch(t){if(s=t,isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Nn.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await new Promise(e=>setTimeout(e,n))}throw s||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof nt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ot||403===e?.status}function isRetryableError(e){return!!e?.message&&!!['Unexpected event order, got error before "message_start"',"API Error: Unexpected event order","Body is unusable: Body has already been read"].some(t=>e.message.includes(t))}function formatAPIError(e,t){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||t?.aborted)return new Error("Interrupted by user");if(e instanceof nt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof ot||403===e?.status)return e;if(e?.message?.startsWith("Error:"))return e;let n="Error: ";return e.message?n+="Something went wrong. Please try again or contact support if the issue persists.":e.toString?n+=e.toString():n+="Unknown error occurred",new Error(n)}function processServerToolBlocks(e,t){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let n="";for(const r of e.content)if("text"===r.type)n+=r.text;else if("server_tool_use"===r.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const e=cn(r.name,r.input),n=Nt(r.name)?"Found 10 results":"Content fetched",o={id:`${r.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:r.name,input:e,output:n};t.onFeedUpdate(o)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}__name(agentToTool,"agentToTool"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks");var _n=new Map,On=null;function initializeAgentManager(e){On=e}async function loadAgentTools(){if(!On)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");const{personal:e,project:t}=await loadAllAgents();_n.clear();const n=[...e,...t];for(const e of n){const t=agentToTool(e,On);_n.set(t.name,t)}}async function getAgentTools(){return 0===_n.size&&await loadAgentTools(),Array.from(_n.values())}async function getAgentTool(e){return 0===_n.size&&await loadAgentTools(),_n.get(e)}function isPathInTasteDirectory(e){const{filePath:t,projectRoot:n}=e,r=f.join(n,".commandcode","taste"),o=f.normalize(f.resolve(n,t)),a=f.normalize(r);return o.startsWith(a)}function getTasteFileInfo(e){const t=f.normalize(f.resolve(e)),n=f.normalize(f.join(process.cwd(),".commandcode","taste")),r=f.normalize(f.join(T.homedir(),".commandcode","taste"));let o=null;if(t.startsWith(n)?o=n:t.startsWith(r)&&(o=r),!o)return{isTaste:!1};if(!t.endsWith("taste.md"))return{isTaste:!1};const a=f.relative(o,t).split(f.sep);return 1===a.length?{isTaste:!0}:2===a.length?{isTaste:!0,category:a[0]}:{isTaste:!1}}__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool"),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(function getTasteAccessError(){return"Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system."},"getTasteAccessError");var Un=[pn,fn,En,vn,Pn,xn,Dn,Rn,Fn],Ln=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],Bn=new Map(Un.map(e=>[e.name,e]));async function executeTool(e,t,n){let r=Bn.get(e);if(r||(r=await getAgentTool(e)),!r){const t=await getAgentTools(),n=[...Array.from(Bn.keys()),...t.map(e=>e.name)];throw new Error(`Tool "${e}" not found. Available tools: ${n.join(", ")}`)}if(("write_file"===e||"edit_file"===e)&&!0!==n?.allowTasteWrite){const e=t.filePath,n=isPathInTasteDirectory({filePath:e,projectRoot:process.cwd()});if(e&&n)throw new Error("Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system.".replace("Error: ",""))}try{return!Bn.has(e)&&n?await r.execute(t,n):await r.execute(t)}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message)throw e;return e instanceof Error?`Error: ${e.message}`:"Error: Unknown error occurred"}}async function getToolSchemas(){return[...Un.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...(await getAgentTools()).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...Ln]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var Wn={};Un.forEach(e=>{Wn[e.name]=toPascalCase(e.name)}),Ln.forEach(e=>{Wn[e.name]=toPascalCase(e.name)});var zn={};Object.entries(Wn).forEach(([e,t])=>{zn[t]=e}),initializeAgentManager({clientTools:Un,serverTools:Ln,toolsMap:Bn,displayNameToToolName:zn});var Gn=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(!y.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=y.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=y.basename(e);return y.dirname(e),this.isUserPath(e)?`<user-home>/${y.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))}},Vn=new class extends me{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;addEvent(e){const{type:t,message:n,details:r}=e,o={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r};this.events.unshift(o),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",o)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}};function extractLearningWithConfidence(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)\.\s+Confidence:\s*(\d+\.?\d*)/);return n?{text:n[1].trim(),confidence:parseFloat(n[2])}:null}function extractLearnings(e){const{text:t}=e;return t.split("\n").filter(e=>e.trim().startsWith("-")).map(e=>extractLearningWithConfidence({line:e})).filter(Boolean)}function compareLearnings(e){const{oldText:t,newText:n}=e,r=extractLearnings({text:t}),o=extractLearnings({text:n}),a=new Map(r.map(e=>[e.text,e.confidence])),s=[],i=[],c=[];return o.forEach(e=>{const t=a.get(e.text);void 0===t?s.push(e):e.confidence>t?i.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&c.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:s,upgraded:i,downgraded:c}}__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings");var qn=__name((e,t)=>{},"dlog"),Hn=new ke("LearningAgent"),Jn=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=5;request;projectRoot;tasteDir;constructor(e){this.request=e.request,this.projectRoot=e.projectRoot,this.tasteDir=f.join(e.projectRoot,".commandcode","taste")}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)this.pendingMessages=t;else if(0!==t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length){this.isProcessing=!0;try{for(await this.runLearningLoop({messages:t}),this.lastProcessedMessageIndex=t.length-1;null!==this.pendingMessages;){const e=this.pendingMessages;this.pendingMessages=null,e.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length>0&&(await this.runLearningLoop({messages:e}),this.lastProcessedMessageIndex=e.length-1)}}catch(e){Vn.addEvent({type:"error",message:"learning pass failed",details:e instanceof Error?e.message:String(e)}),this.lastProcessedMessageIndex=t.length-1}finally{this.isProcessing=!1}}}async runLearningLoop(e){const{messages:t}=e,n=["analyzing deltas","computing embeddings","updating weights","refining patterns","processing signals","extracting features","tuning parameters","optimizing priors"],r=n[Math.floor(Math.random()*n.length)];Vn.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),a=t.length-this.lastProcessedMessageIndex-1,s=Math.max(20,a),i=Math.max(0,t.length-s),c=t.slice(i);let l=0,d=!1;qn("New messages count",a),qn("Context window size",s),qn("Sending conversation messages",c.length);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){qn(`Starting learning turn ${l+1}/${this.maxTurns}`);const e=await this.callLearningAPI({conversation:u});qn("Received response from learning API"),qn("Response content blocks",e.content.length);const t=this.extractToolCalls({content:e.content});if(qn("Extracted tool calls",t.length),t.length>0&&qn("Tool calls",t.map(e=>({name:e.name,id:e.id}))),0===t.length){qn("No tool calls found, checking for text response");const t=e.content.filter(e=>"text"===e.type);if(t.length>0){const e=t[0].text||"";qn("Text response from LLM",e.substring(0,300))}break}qn("Executing tools");const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});qn("Tools executed, learnings found?",r),r&&(d=!0),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&Hn.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Vn.addEvent({type:"no_learnings",message:"no changes to taste"}),Vn.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{qn(`Executing tool: ${e.name}`),this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",a="";if("write_file"===e.name||"edit_file"===e.name){qn("Tool is write/edit, will track changes");const e=t;if(a=String(e.filePath||e.file_path||""),a)try{o=await H.promises.readFile(a,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const s=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&a)try{i=await H.promises.readFile(a,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=a.replace(`${this.projectRoot}/`,"");qn("Target file path",e);const t=compareLearnings({oldText:o,newText:i});qn("Diff results",{added:t.added.length,upgraded:t.upgraded.length,downgraded:t.downgraded.length}),t.added.forEach(t=>{Vn.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Vn.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Vn.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:s})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:t instanceof Error?t.message:String(t)})}return{results:n,learningsFound:r}}validateTastePath(e){const{toolName:t,input:n}=e,r={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[t];if(!r||!n[r])return;const o=String(n[r]);if(f.isAbsolute(o))throw new Error(`Security: ${t} received absolute path. Only taste-relative paths are allowed (e.g., " .commandcode/taste/cli/taste.md" or " .commandcode/taste/taste.md"). Attempted: ${o}`);const a=f.join(this.tasteDir,o);if(!f.normalize(a).startsWith(this.tasteDir))throw new Error(`Security: ${t} can only access files within .commandcode/taste/. Attempted: ${o}`)}adjustPathsForTaste(e){const{toolName:t,input:n}=e,r={...n},o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[t];if(o&&r[o]){const e=String(r[o]);let n;const a="write_file"===t||"edit_file"===t;if(f.isAbsolute(e)&&e.startsWith(this.tasteDir))if(a){if(!this.isValidTasteFilePath(e))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${e}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);n=e}else n=e;else{if(f.isAbsolute(e))throw new Error(`Invalid path: Absolute path outside taste directory: ${e}`);if(n=e.startsWith(".commandcode/taste")?e.replace(".commandcode/taste",this.tasteDir):f.join(this.tasteDir,e),a&&!this.isValidTasteFilePath(n))throw new Error(`Invalid adjusted path: ${n}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}r[o]=n}return r}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isValidTasteFilePath(e))throw new Error(`Security: Invalid taste file path. Only allowed:\n - {project}/.commandcode/taste/taste.md\n - {project}/.commandcode/taste/{category}/taste.md\nAttempted: ${e}`)}async initializeTasteDirectory(){if(!H.existsSync(this.tasteDir)){H.mkdirSync(this.tasteDir,{recursive:!0});const e=f.join(this.tasteDir,"taste.md");H.writeFileSync(e,"","utf-8")}}async reorganizeIfNeeded(){const e=f.join(this.tasteDir,"taste.md");if(!H.existsSync(e))return!1;const t=H.readFileSync(e,"utf-8"),n=this.parseCategories({content:t}).filter(e=>e.learningCount>5);if(0===n.length)return!1;let r=t;for(const e of n){const t=e.name.toLowerCase().replace(/\s+/g,"-"),n=f.join(this.tasteDir,t),o=f.join(n,"taste.md");H.mkdirSync(n,{recursive:!0}),Vn.addEvent({type:"refactored",message:`moved: ${e.name} package`,details:`moved to ${t}/taste.md`});const a=`# ${e.name}\n${e.learnings.join("\n")}\n`;H.writeFileSync(o,a,"utf-8");const s=`# ${e.name}\nSee [${t}/taste.md](${t}/taste.md)\n`;r=r.replace(e.fullSection,s)}return H.writeFileSync(e,r,"utf-8"),!0}parseCategories(e){const{content:t}=e,n=[],r=t.split(/^# /gm).filter(e=>e.trim());for(const e of r){const t=e.split("\n"),r=t[0].trim();if(e.includes("See ["))continue;const o=t.filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:"));o.length>0&&n.push({name:r,learningCount:o.length,learnings:o,fullSection:`# ${e}`})}return n}async getTasteStructure(){return H.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(e){const{dir:t,prefix:n}=e,r=H.readdirSync(t,{withFileTypes:!0});let o="";for(let e=0;e<r.length;e++){const a=r[e],s=e===r.length-1,i=s?"└── ":"├── ";if(a.isDirectory()){o+=`${n}${i}${a.name}/\n`;const e=n+(s?" ":"│ ");o+=await this.buildTree({dir:f.join(t,a.name),prefix:e})}else if("taste.md"===a.name){const e=(H.readFileSync(f.join(t,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${n}${i}${a.name} (${e} learnings)\n`}else o+=`${n}${i}${a.name}\n`}return o}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===je&&(o=await Me.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const a={[$e]:Mn.getCurrentProjectDirName(),[Se]:r.toString()};o&&(a[xe]=`Bearer ${o}`);let s=0,i=null;for(;s<=this.maxApiRetries;)try{return await this.request.post({endpoint:De.ALPHA.TASTE.LEARN,body:{conversation:t,tools:await this.getTasteTools()},headers:a})}catch(e){if(i=e instanceof Error?e:new Error(String(e)),s++,s>this.maxApiRetries)throw i;const t=2e3*Math.pow(2,s);await this.sleep({ms:t})}throw i||new Error("API call failed")}sleep(e){const{ms:t}=e;return new Promise(e=>setTimeout(e,t))}static async isInitialized(e){const{projectRoot:t}=e,n=f.join(t,".commandcode","taste");return H.existsSync(n)}};async function getTasteContent(){try{const e=process.cwd(),t=f.join(e,".commandcode","taste","taste.md");if(!K(t))return null;const n=await A.readFile(t,"utf-8"),r=n.trim();return r&&"# Taste (Continuously Learned by CommandCode)"!==r?n:null}catch(e){return null}}__name(getTasteContent,"getTasteContent");var Kn=new ke("ContextEngine"),Yn=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();lastFileContexts=[];learningAgent;constructor(e,t){const n=getApiBaseUrl();this.request=new dt({baseUrl:n}),this.callbacks=e,this.sessionManager=new Mn(t),this.learningAgent=new Jn({request:this.request,projectRoot:process.cwd()})}async interrupt(e=!1){if(this.abortController){this.abortController.abort(),this.abortController=null,Kn.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(),Kn.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=Ht("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>Kn.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t){let n=e,r=[];try{const t=await processFileReferences(e);if(n=t.processedContent,r=t.fileReferences,r.length>0){const e=r.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}const o=Ht(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 a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),n.trim()&&a.push({type:"text",text:n});const s={role:"user",content:a};return this.addMessageAndSync(this.createMessageWithMeta(s)),this.sessionManager.saveMessages(this.messages,o).catch(e=>Kn.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent(),await this.processMessages()}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){Kn.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}async processMessages(){let e="";this.abortController=new AbortController;let t=!1;for(;;)try{this.checkIfInterrupted(),t||(this.initializeInteractionTokens(),t=!0);const{body:n,headers:r}=await this.prepareAPICall(),o=await this.callAPIWithRetry({body:n,headers:r});this.updateContextUsage(o);const a=o.content.filter(e=>"tool_use"===e.type),s=o.content.filter(e=>"server_tool_use"===e.type);if(e=s.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===a.length){const t=o.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===s.length){const t=Kt(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>Kn.error(`Failed to save messages: ${e}`))}if(0!==s.length&&this.sessionManager.saveMessages(this.messages).catch(e=>Kn.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=Ht(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>Kn.error(`Failed to save messages: ${e}`)),this.triggerLearningAgent();continue}}break}const i=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(i.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:i})),e.trim()){const t=Kt(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:a}),{toolResults:l,executedToolIds:d,permissionDenied:u}=c;if(u){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?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const m=[...l];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){m.push({type:"text",text:t});const e=Ht(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>Kn.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&Kn.debug("Request interrupted or insufficient credits"),this.formatAPIError(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 Kn.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}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async compactConversation({preserveCurrentInteraction:e=!1}={preserveCurrentInteraction:!1}){const t=this.messages.length,n=this.contextTokensUsed;let r=-1;if(e)for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if("user"===t.message.role){const n=t.message.content;if(!Array.isArray(n)){r=e;break}if(!n.some(e=>"tool_result"===e.type)){r=e;break}}}const o=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],a=n.message.role;if(e&&t>=r&&-1!==r)o.push(n);else if("user"===a){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type))continue;o.push(n)}else o.push(n)}else if("assistant"===a){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"text"===e.type&&e.text?.trim());t.length>0&&o.push({...n,message:{...n.message,content:t}})}else"string"==typeof e&&e.trim()&&o.push(n)}}this.messages=o,await this.sessionManager.saveMessages(this.messages);const a=estimateTokens(this.getRawMessages());return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:jn}),{messagesRemoved:t-o.length,tokensSaved:Math.max(0,n-a)}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}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){}}))}async syncMessageToShare(e,t){try{const n=Gn.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:De.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.abortController?.signal.aborted)throw new Error("Interrupted by user")}initializeInteractionTokens(){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message)}async prepareAPICall(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(t),t===je&&(r=await Me.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o={tools:e,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:"anthropic:claude-sonnet-4-5-20250929"},a={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),params:o};Kn.debug(`🔍 API Call: ${o.model}, ${this.messages.length} messages, ${e.length} tools, streaming: true`);const s=await isTasteLearningEnabled(),i={[$e]:Mn.getCurrentProjectDirName(),[Ie]:s.toString(),[Se]:n.toString()};return r&&(i[xe]=`Bearer ${r}`),{body:a,headers:i}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++)try{const t=await this.request.post({body:e.body,stream:!0,endpoint:De.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers}),n=de.fromReadableStream(t);n.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let r=null;n.on("error",e=>{r="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const o=await n.finalMessage();if(r)throw r;return this.callbacks.onRetryUpdate?.(null),o}catch(e){if(t=e,this.isNonRetryableError(e))throw this.formatAPIError(e);if(9===n)throw this.callbacks.onRetryUpdate?.(null),this.formatAPIError(e);const r=Math.min(n,10),o=100*Math.pow(2,r),a=Math.max(o,1e3),s=Math.min(a,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await new Promise(e=>setTimeout(e,s))}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||this.abortController?.signal.aborted||e instanceof nt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ot||403===e?.status}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=e.message?.toLowerCase().includes("insufficient credits");if(t)return new Error("Insufficient credits");const n=e.message?.toLowerCase().includes("oauth authentication required");if(n)return e;if(e instanceof ot||403===e?.status)return e;let r="Error: ";return e.message?e.message.includes("Invalid 'Authorization' header")?r+='Authentication failed. Run "cmd login" to sign in again.':r+='Something went wrong. Type "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord.':e.toString?r+=e.toString():r+="Unknown error occurred",new Error(r)}async executeToolBlocks(e){const t=[],n=new Set;let r=!1;for(const o of e.toolBlocks){this.checkIfInterrupted();try{const e=await this.checkToolPermission(o);if(e.needsPermission&&!e.allowed){this.handlePermissionDenied(o),r=!0;break}const a=await this.executeSingleTool(o);t.push({type:"tool_result",tool_use_id:o.id,content:a}),n.add(o.id),this.showToolSuccess(o,a)}catch(e){const r=e instanceof Error?e.message:"Unknown error";t.push({type:"tool_result",tool_use_id:o.id,content:`Error: ${r}`,is_error:!0}),n.add(o.id),this.showToolError(o,r)}}return{toolResults:t,executedToolIds:n,permissionDenied:r}}async checkToolPermission(e){return["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.name,e.input)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=await executeTool(e.name,e.input,{onPermissionRequest:this.callbacks.onPermissionRequest,abortSignal:this.abortController?.signal,onFeedUpdate:this.callbacks.onFeedUpdate});this.checkIfInterrupted();const n=checkToolOutputTokensLimit(t,e.name),r=estimateTokens(n);return this.currentInteractionTokens+=r,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),n}handlePermissionDenied(e){const t=cn(e.name,e.input),n={..."edit_file"===e.name?e.input:{},permissionDenied:!0},r=Yt(e.name,t,n),o=en(r,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}showToolSuccess(e,t){let n="edit_file"===e.name?e.input:void 0;if("read_file"===e.name){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(n={...n||{},isTasteFile:!0,tasteCategory:e.category})}}const r={...e.input,...n?.isTasteFile?{isTasteFile:n.isTasteFile}:{},...n?.tasteCategory?{tasteCategory:n.tasteCategory}:{}},o=cn(e.name,r),a=Yt(e.name,o,n),s=en(a,t);this.callbacks.onFeedUpdate(s)}showToolError(e,t){const n=cn(e.name,e.input),r="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,o=Yt(e.name,n,r),a=en(o,tn(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let t="";for(const n of e.content)if("text"===n.type)t+=n.text;else if("server_tool_use"===n.type){if(t.trim()){const e=Kt(t.trim());this.callbacks.onFeedUpdate(e),t=""}const e=cn(n.name,n.input),r=Yt(n.name,e),o=Nt(n.name)?"Found 10 results":"Content fetched",a=en(r,o);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=Kt(t.trim());this.callbacks.onFeedUpdate(e)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}updateContextUsage(e){if(!("usage"in e))return;const t=e.usage;if(!t?.input_tokens)return;const n=calculateUsageFromResponse(t);this.contextTokensUsed=n,this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:jn}),this.checkAndCompactIfNeeded()}async checkAndCompactIfNeeded(){const e=Math.floor(17e4);if(this.contextTokensUsed>e){Kn.debug(`Context tokens (${this.contextTokensUsed}) exceeded threshold (${e}), triggering automatic compaction`);try{const e=await this.compactConversation({preserveCurrentInteraction:!0});Kn.debug(`Automatic compaction completed: removed ${e.messagesRemoved} messages, saved ${e.tokensSaved} tokens`)}catch(e){Kn.error(`Failed to automatically compact conversation: ${e}`)}}}};function Markdown({children:e,...t}){const n={...t};he({renderer:new ye(n),breaks:!0,gfm:!0});const r=fe(e);return R.createElement(L,null,r.toString().trim())}function AssistantMessage({content:e}){return R.createElement(U,null,R.createElement(L,null,a.nodejs),R.createElement(U,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},R.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage");var Qn={"Interrupted by user":"Interrupted by user","Insufficient credits":Ne};function UserMessage({content:e}){const t="Interrupted by user"===e,n="Insufficient credits"===e,r=e.startsWith("Error:"),o=t||n||r;let s=o&&Qn[e]||e;return R.createElement(U,null,R.createElement(L,{color:o?"red":"dim"},a.pointer),R.createElement(U,{marginLeft:1},R.createElement(L,{color:o?"red":void 0,dimColor:!o,wrap:"wrap"},s)))}__name(UserMessage,"UserMessage");var Zn="#6B7280";function truncateToolOutputForDisplay(e){const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),n=t.split("\n");if(n.length<=1)return t;const r=n.slice(0,1).join("\n");return n.length,r}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:a=2,dimDiff:s=!1,maxLines:i}){const c=we.diffLines(e,t);let l=0,d=0,u=0,m=0;c.forEach(e=>{e.added?(l+=e.count||1,m+=e.count||1):e.removed&&(d+=e.count||1,m+=e.count||1)});const g=[];c.forEach((e,t)=>{const n=e.value.split("\n").filter(e=>e);e.added||e.removed?n.forEach((n,r)=>{e.removed?(u++,g.push(R.createElement(U,{key:`${t}-${r}-removed`,width:"100%"},R.createElement(L,{color:"gray",dimColor:s},u.toString().padStart(3)," "),R.createElement(U,{backgroundColor:"#712F37"},R.createElement(L,{dimColor:s},"-"),R.createElement(L,{dimColor:s}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(R.createElement(U,{key:`${t}-${r}-added`,width:"100%"},R.createElement(L,{color:"gray",dimColor:s},u.toString().padStart(3)," "),R.createElement(U,{backgroundColor:"#325B30"},R.createElement(L,{dimColor:s},"+"),R.createElement(L,{dimColor:s}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:R.createElement(U,{flexDirection:"column"},o&&!r&&R.createElement(L,{color:"gray"},"Updated"," ",R.createElement(L,{color:"white",bold:!0},n)," ","with ",R.createElement(L,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",R.createElement(L,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&R.createElement(L,{color:"red"},"Rejected update to",R.createElement(L,{color:"red"},` ${n}`)),R.createElement(U,{flexDirection:"column",marginLeft:a},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=ln(e);return t?R.createElement(U,{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(U,{key:e.id||t,flexDirection:"row"},R.createElement(U,{width:2},R.createElement(L,{color:r},n)),R.createElement(L,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):R.createElement(L,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:i=!1}){const c="Thinking…"===e,l="Todos"===e,d="Edit"===e,u=!0===s?.isTasteFile,m=s?.tasteCategory,g=!0===s?.permissionDenied,p=!c&&t&&!u,h=!c&&!l&&!u,{name:f}=detectTerminal(),y="iTerm2"===f?"shift":"ctrl";let w,E;if(r)w="yellow",E="→";else if(o)w="red",E=a.nodejs;else if(c)w=Zn,E="✻";else if(l&&n){const e=ln(n),t=e?.every(e=>"completed"===e.status);w=t?"#22C55E":"#D4A017",E=a.nodejs}else w="#22C55E",E=a.nodejs;return R.createElement(U,null,c&&R.createElement(L,{color:w,italic:!0},E),R.createElement(U,{flexDirection:"column",marginLeft:c?1:0},R.createElement(U,null,c?R.createElement(L,{color:Zn,italic:!0},`${e} `):u?R.createElement(R.Fragment,null,R.createElement(L,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),R.createElement(L,null," ","Using your taste ",m?"package of ":"packages",m&&R.createElement(L,{bold:!0},m))):R.createElement(L,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),p&&R.createElement(L,null," ",R.createElement(Markdown,null,`(${t})`))),n&&!u&&R.createElement(U,{columnGap:1},h&&R.createElement(L,null,"⎿"," "),l?formatTodosForDisplay(n):c?R.createElement(U,{width:"100%",flexDirection:"column"},R.createElement(L,null," "),R.createElement(L,{color:Zn,wrap:"wrap",italic:!0},n)):d&&s?.oldValue&&s?.newValue?R.createElement(U,{flexDirection:"column"},(()=>{const e=i?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:g,permissionDenied:g,maxLines:e});return R.createElement(R.Fragment,null,n,r&&R.createElement(U,{marginTop:1},R.createElement(L,{dimColor:!0},"… (",o-10," more lines) (",`${y}+o to expand`,")")))})(),g&&n&&R.createElement(U,{marginTop:1},R.createElement(L,{color:"red",wrap:"wrap"},n))):R.createElement(U,{width:"100%"},R.createElement(L,{color:o?"red":"",wrap:"wrap"},i?n:R.createElement(R.Fragment,null,truncateToolOutputForDisplay(n),n.includes("\n")&&R.createElement(L,{dimColor:!0}," ","(",`${y}+o to expand`,")"))))),r&&R.createElement(U,{columnGap:1},R.createElement(L,null,"⎿"," "),R.createElement(L,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,a;return n?(o="yellow",a="→"):r?(o="red",a="✗"):(o="green",a="✓"),R.createElement(U,null,R.createElement(L,{color:o},a),R.createElement(U,{flexDirection:"column",marginLeft:1},R.createElement(U,null,R.createElement(L,{color:"gray"},"$ "),R.createElement(L,{color:o,bold:!0},e)),R.createElement(U,{columnGap:1},R.createElement(L,null,"⎿"," "),R.createElement(L,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}function SystemMessage({content:e}){return R.createElement(U,{flexDirection:"column"},R.createElement(L,{wrap:"wrap"},R.createElement(Markdown,null,e)))}function getTerminalWidth(){return process.stdout.columns||80}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage"),__name(SystemMessage,"SystemMessage"),__name(getTerminalWidth,"getTerminalWidth");var Xn=__name(()=>{const e=getTerminalWidth();return e>=70?" \n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n":e>=50?"\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n":tr},"getResponsiveCommandLogo"),er=__name(()=>getTerminalWidth()>=70?"# Welcome to Command Code. Coding Agent with taste by Langbase":"# Welcome to Command Code","getResponsiveCommandTagline"),tr="⌘ CMD\n";function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return R.createElement(U,null,R.createElement(L,{color:"red"},t?a.pointer:a.warning),R.createElement(U,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},R.createElement(L,{color:"red"},e)))}function InfoMessage({content:e}){return R.createElement(U,null,R.createElement(L,{dimColor:!0},a.info),R.createElement(U,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},R.createElement(L,{dimColor:!0},e)))}__name(ErrorMessage,"ErrorMessage"),__name(InfoMessage,"InfoMessage");var nr=R.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1})=>{const o=t?["header",...e]:e,a=er(),s=Xn();return getTerminalWidth(),R.createElement(O,{items:o,key:n,style:{width:"100%"}},e=>{if("header"===e)return R.createElement(U,{key:"header",marginBottom:1},R.createElement(pe,{name:"vice"},R.createElement(L,null,s),R.createElement(L,null,a)));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:sn(t.name||""),input:t.input,output:t.output||"",isPending:rn(t),hasError:nn(t),metadata:t.metadata,expandedOutput:r});case"bash":return R.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:rn(t),hasError:nn(t)});case"system":return R.createElement(SystemMessage,{content:t.input});case"info":return R.createElement(InfoMessage,{content:t.input});case"error":return R.createElement(ErrorMessage,{content:t.input});default:return R.createElement(R.Fragment,null)}})();return R.createElement(U,{key:t.id,marginBottom:1,width:"90%"},n)})}),rr=__name(({messages:e})=>0===e.length?null:R.createElement(U,{flexDirection:"column",marginBottom:1},R.createElement(U,{marginBottom:0},R.createElement(L,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>R.createElement(U,{key:t},R.createElement(L,{dimColor:!0},a.pointerSmall," "),R.createElement(L,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages"),or=["dim","dim2","normal","normal2","bright","bright2","brighter","brighter2","brightest","brightest","brighter2","brighter","bright2","bright","normal2","normal","dim2","dim"],ar=__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");function GlowIcon(){const[e,t]=F(0);return j(()=>{const e=setInterval(()=>{t(e=>(e+1)%or.length)},120);return()=>clearInterval(e)},[]),R.createElement(U,{paddingLeft:1,marginRight:1},R.createElement(L,{color:ar(or[e]),bold:!0},"⌘"))}__name(GlowIcon,"GlowIcon");var sr=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,a]=F(0),s=getTerminalWidth();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`}j(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),o=e>0?t:-t,s=setInterval(()=>{a(e=>{const t=e+o;return o>0&&t>=n||o<0&&t<=n?n:t})},100);return()=>clearInterval(s)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime,"formatTime");const i=s>70,c=s>40&&s<=70;return R.createElement(U,null,R.createElement(GlowIcon,null),R.createElement(U,{marginRight:1},R.createElement(L,{color:"#E4CCFF",wrap:"wrap"},e)),i?R.createElement(R.Fragment,null,R.createElement(U,{columnGap:1},R.createElement(L,{dimColor:!0},`(${formatTime(t)}`),R.createElement(L,{dimColor:!0},"•"),R.createElement(L,{color:"gray"},o.arrowDown),R.createElement(L,{dimColor:!0},`${formatToken(Math.round(r))}`),R.createElement(L,{dimColor:!0},"•"),R.createElement(U,{columnGap:1},R.createElement(L,{bold:!0,color:"gray"},"esc"),R.createElement(L,{dimColor:!0},"to interrupt)")))):c?R.createElement(U,{columnGap:1},R.createElement(L,{dimColor:!0},`(${formatToken(Math.round(r))})`)):R.createElement(R.Fragment,null))},"Status"),ir=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=F(process.cwd()),[a,s]=F([]),[i,c]=F(0),[l,d]=F(0),u=n.trim()?15:10,m=N((e,t=process.cwd())=>{if(!e.trim())return[];if(e.endsWith("/")){const n=E(t,e);try{const e=X(n),r=[];return e.forEach(e=>{const o=E(n,e);try{const e=ee(o),n=b(t,o);r.push({name:n,path:o,isDirectory:e.isDirectory()})}catch{}}),r.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),r.slice(0,50)}catch{}}if(e.includes("/")){const n=e.split("/"),r=n.pop()||"",o=E(t,n.join("/"));try{const e=X(o),n=[],a=r.toLowerCase();return e.forEach(e=>{const s=e.toLowerCase();if(!r||s.includes(a)){const r=E(o,e);try{const e=ee(r),o=b(t,r);n.push({name:o,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)),n.slice(0,50)}catch{}}const n=[],r=e.toLowerCase(),o=__name((e,a=0)=>{if(!(a>8))try{X(e).forEach(s=>{const i=E(e,s);try{const e=ee(i),c=b(t,i),l=c.toLowerCase();(s.toLowerCase().includes(r)||l.includes(r))&&n.push({name:c,path:i,isDirectory:e.isDirectory()}),e.isDirectory()&&(["node_modules"].includes(s)||o(i,a+1))}catch(e){}})}catch(e){}},"searchRecursively");return o(t),n.sort((e,t)=>{const n=e.name.toLowerCase(),o=t.name.toLowerCase(),a=n===r,s=o===r;if(a&&!s)return-1;if(!a&&s)return 1;const i=n.split("/").pop()||"",c=o.split("/").pop()||"",l=i.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)},[]),g=N(e=>{try{const t=X(e),n=[];"/"!==e&&n.push({name:"..",path:w(e),isDirectory:!0}),t.forEach(t=>{const r=E(e,t);try{const e=ee(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)),s(n),c(0),d(0)}catch{}},[]);j(()=>{if(n.trim()){const e=m(n);s(e),c(0),d(0)}else g(r)},[r,g,n,m]),B((r,s)=>{if(s.escape)t();else if(s.upArrow)c(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t});else if(s.downArrow)c(e=>{const t=Math.min(a.length-1,e+1);return t>=l+u&&d(t-u+1),t});else{if(s.rightArrow){const e=a[i];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(C(e.path)))}if(s.return){const t=a[i];if(!t)return;return void e(t.path)}}});const p=a.slice(l,l+u);return R.createElement(U,{flexDirection:"column",paddingLeft:1},R.createElement(U,{marginBottom:1,flexDirection:"column"},R.createElement(L,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),R.createElement(L,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===p.length?R.createElement(L,{color:"dim"},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):p.map((e,t)=>{const n=l+t,r=e.name;return R.createElement(L,{key:e.path,color:n===i?"white":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList");function loadCustomCommands(){const e=[],t=y.join(process.cwd(),".commandcode","commands"),n=y.join(k.homedir(),".commandcode","commands");function loadCommandsFromDirectory(t,n,r=""){if(J.existsSync(t))try{const o=J.readdirSync(t,{withFileTypes:!0});for(const a of o){const o=y.join(t,a.name);if(a.isDirectory())loadCommandsFromDirectory(o,n,r?`${r}/${a.name}`:a.name);else if(a.isFile()&&a.name.endsWith(".md")){const t=y.basename(a.name,".md"),s=J.readFileSync(o,"utf-8").trim();e.push({name:t,source:n,content:s,subdirectory:r})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(n,"user"),loadCommandsFromDirectory(t,"project"),e}function customCommandsToMenuItems(e){return e.map(e=>{const t=`/${e.name}`;let n;return n=e.subdirectory?"project"===e.source?`(project: ${e.subdirectory})`:`(user: ${e.subdirectory})`:"project"===e.source?"(project)":"(user)",{command:t,description:`${e.content.length>60?`${e.content.substring(0,57)}...`:e.content} ${n}`}})}function getCustomCommandContent(e){const t=loadCustomCommands(),n=e.startsWith("/")?e.substring(1):e,r=t.find(e=>e.name===n);return r?r.content:null}__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent");var cr=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/clear (reset, new)",description:"Clear the conversation history"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/agents",description:"Manage agent configurations"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/compact",description:"Compact the conversation history"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"}],lr=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=F(0),[a,s]=F(0),i=_(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...cr];if(!n)return e;const t=n.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let o=0;return n.startsWith("/"+t)?o+=100:n.includes(t)&&(o+=50),r.includes(t)&&(o+=25),{...e,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]),c=_(()=>{const e=a,t=Math.min(e+8,i.length);return i.slice(e,t)},[i,a]);return j(()=>{o(0),s(0)},[n]),B((n,c)=>{if(c.escape)t();else if(c.upArrow)o(e=>{const t=Math.max(0,e-1);return t<a&&s(t),t});else if(c.downArrow)o(e=>{const t=Math.min(i.length-1,e+1);return t>=a+8&&s(Math.max(0,t-8+1)),t});else if(c.return){const t=i[r];return void(t&&e(t.command))}}),0===i.length?R.createElement(U,{flexDirection:"column",paddingLeft:2},R.createElement(L,{color:"dim"},"No commands found")):(i.length,R.createElement(U,{flexDirection:"column",paddingLeft:1},R.createElement(U,{columnGap:4},R.createElement(U,{flexDirection:"column"},c.map((e,t)=>{const n=a+t;return R.createElement(L,{key:e.command,color:r===n?"white":"dim"},e.command)})),R.createElement(U,{flexDirection:"column"},c.map((e,t)=>{const n=a+t;return R.createElement(L,{key:e.command,color:r===n?"white":"dim"},e.description)})))))},"CommandMenu"),dr=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=F([]),[o,s]=F(0),[i,c]=F(!0);j(()=>{l()},[]);const l=__name(async()=>{c(!0);const e=await Mn.listSessions();r(e.slice(0,30)),c(!1)},"loadSessions");if(B((r,a)=>{a.escape?t():a.upArrow?s(e=>Math.max(0,e-1)):a.downArrow?s(e=>Math.min(n.length-1,e+1)):a.return&&n.length>0&&o<n.length&&e(n[o].id)}),i)return R.createElement(U,{flexDirection:"column",paddingLeft:2},R.createElement(L,{color:"gray"},"Loading sessions..."));if(0===n.length)return R.createElement(U,{flexDirection:"column",paddingLeft:2},R.createElement(L,{color:"gray"},"No previous sessions found"),R.createElement(L,{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),a=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${a}d ago`},"formatRelativeTime"),u=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return R.createElement(U,{flexDirection:"column",paddingLeft:1,width:"100%"},R.createElement(L,{color:"cyan",bold:!0},"Resume Session"),R.createElement(L,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),R.createElement(U,{marginTop:1}),R.createElement(U,{columnGap:2,marginBottom:1},R.createElement(U,{width:5},R.createElement(L,{color:"gray"}," ")),R.createElement(U,{width:13},R.createElement(L,{color:"gray"},"Modified")),R.createElement(U,{width:20},R.createElement(L,{color:"gray"},"Git Branch")),R.createElement(U,{width:11},R.createElement(L,{color:"gray"},"# Messages")),R.createElement(U,null,R.createElement(L,{color:"gray"},"Summary"))),R.createElement(U,{columnGap:2},R.createElement(U,{flexDirection:"column",width:5},n.map((e,t)=>R.createElement(L,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${a.pointer} ${t+1}.`:` ${t+1}.`))),R.createElement(U,{flexDirection:"column",width:13},n.map((e,t)=>R.createElement(L,{key:`mod-${e.id}`,color:o===t?"white":"gray"},d(e.lastModified)))),R.createElement(U,{flexDirection:"column",width:20},n.map((e,t)=>R.createElement(L,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),R.createElement(U,{flexDirection:"column",width:11},n.map((e,t)=>R.createElement(L,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),R.createElement(U,{flexDirection:"column"},n.map((e,t)=>R.createElement(L,{key:`summary-${e.id}`,color:o===t?"white":"gray"},u(e.firstMessage))))))},"SessionsResumeTable"),ur=__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(U,{paddingRight:1},R.createElement(L,{color:r(n),dimColor:!0},n.toFixed(1),"% context used (",t(e.current),"/",t(e.limit),")"))},"ContextUsage"),mr=__name(()=>R.createElement(U,{flexDirection:"column",paddingLeft:1},R.createElement(L,{color:"dim",bold:!0},"Available Shortcuts:"),R.createElement(U,{columnGap:4},R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"dim"},"! for bash mode"),R.createElement(L,{color:"dim"},"/ for commands"),R.createElement(L,{color:"dim"},"@ for file paths")),R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"dim"},"double tap esc to clear input"),R.createElement(L,{color:"dim"},"shift + ⏎ for newline"),R.createElement(L,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),gr=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:i,fileSearchQuery:c,setFileSearchQuery:l,onCommand:d,contextUsage:u,tasteLearning:m=!1,tasteUsage:g=!1,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,updateStatus:w,updateFailedInfo:E,currentProvider:v,showProviderInfo:C,isOAuthMode:T=!1,autoAcceptMode:k=!1})=>{const[A,P]=F(0),[S,x]=F(!1),[$,I]=F(!1),[D,j]=F(!1),[O,W]=F(!1),[z,G]=F(""),[q,H]=F(!1),[J,K]=F(null),[Y,Q]=F([]),[Z,X]=F([]),[ee,te]=F(""),[ne,re]=F(""),oe=M(!1),[ae,se]=F(!1),ie=N(()=>{n(""),I(!1),W(!1),G(""),H(!1),Q([]),X([]),te(""),se(!1),P(e=>e+1)},[n]),ce=N(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)},[]),le=N(()=>{const t=ce(e);n(t),P(e=>e+1)},[e,ce,n]);B(async(t,r)=>{if(getIsExpandToolShortcut(r,t))return oe.current=!0,n(e),void P(e=>e+1);if(!r.ctrl&&!r.meta&&!r.shift){if(""===t)return void ie();if(""===t)return void le()}if(r.meta&&r.delete)return oe.current=!0,void le();if(r.meta&&r.backspace)ie();else if(r.alt&&r.backspace)le();else{if(r.ctrl&&"w"===t)return oe.current=!0,void le();if(r.meta&&"w"===t)return oe.current=!0,void ie();if(r.meta&&"v"===t||r.ctrl&&"v"===t){if(r.ctrl&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();if(r){const e=`[Image#${Z.length+1}]`;X(e=>[...e,r]),n(t+e),P(e=>e+1)}return void(oe.current=!0)}}else{if((r.ctrl||r.meta)&&"u"===t)return oe.current=!0,void ie();if(r.ctrl&&t)switch(t.toLowerCase()){case"k":case"a":return void ie();case"z":return j(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100)}if(r.escape){if(q)return H(!1),n(ee),void P(e=>e+1);const e=Date.now(),t=500;return J&&e-J<t?(ie(),K(null)):(K(e),setTimeout(()=>K(null),t)),x(!1),void I(!1)}S&&(r.backspace||r.delete)&&0===e.length&&x(!1)}}});const de=N(async t=>{const r=processBracketedPaste(t);if(r.isPasteStart&&!ae){if(se(!0),re(e),!r.isPasteEnd)return;se(!1);const t=await detectClipboardImage();if(t){const r=`[Image#${Z.length+1}]`;X(e=>[...e,t]),n(e+r),P(e=>e+1)}else{const e=await detectClipboardText();if(e)if(e.length>100){const t=`[Text#${Y.length+1}]`;Q(t=>[...t,e]),n(ne+t),P(e=>e+1)}else n(ne+e),P(e=>e+1)}return}if(ae&&!r.isPasteEnd)return;if(ae&&r.isPasteEnd){se(!1);const e=await detectClipboardImage();if(e){const t=`[Image#${Z.length+1}]`;X(t=>[...t,e]),n(r.cleanedContent+t),P(e=>e+1)}else{const e=await detectClipboardText();if(e)if(e.length>100){const t=`[Text#${Y.length+1}]`;Q(t=>[...t,e]),n(ne+t),P(e=>e+1)}else n(ne+e),P(e=>e+1)}return}if(r.isPasteEnd&&!r.isPasteStart)return;if(oe.current)return void(oe.current=!1);const o=1===t.length,a=t.slice(-1);if(o){if("?"===a&&!S)return x(!0),n(""),void P(e=>e+1);if("!"===a&&!$)return x(!1),I(!0),n(""),void P(e=>e+1);"/"!==a||O||(W(!0),G(""))}if(O){const e=t.lastIndexOf("/");if(-1!==e){const n=t.substring(e+1);G(n)}}"@"!==a||s||(i(!0),l(""));const c=t.lastIndexOf("@");if(t.length<e.length&&-1!==c&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(c+1);!e.includes(" ")&&(i(!0),l(e))}if(s)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),l("");else{const n=t.substring(e+1);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),i(!1)}else l(n)}}S&&(t!==e||t.length<e.length)&&x(!1),0===t.length&&(I(!1),W(!1),G(""),H(!1),X([]),Q([]),l(""),te(""),se(!1)),n(t)},[S,e,n,s,i,$,ae,Z]),ue=N(async()=>{if(S)return void x(!1);let n=e.trim(),r=[];const o=Z.length>0,a=Y.length>0;if(!$&&o){const e=[];Z.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!$&&a){let e=n;Y.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:$?"bash":"user",images:r}),I(!1),W(!1),G(""),X([]),Q([])},[t,S,e,$,Z]),me=N(t=>{const r=b(process.cwd(),t);let o;if(s&&""!==c){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),i(!1),l(""),P(e=>e+1)},[n,i,e,s,c,l]),ge=N(()=>{i(!1),l("")},[i,l]),pe=N(t=>{"/resume"===t?(te(e),W(!1),G(""),H(!0),n(""),P(e=>e+1)):(W(!1),G(""),n(""),P(e=>e+1),d&&d(t))},[d,n,e]),he=N(()=>{W(!1),G(""),n(""),P(e=>e+1)},[n]),fe=N(e=>{H(!1),n(""),te(""),P(e=>e+1),d&&d(`/resume:${e}`)},[d]),ye=N(()=>{H(!1),n(ee),P(e=>e+1)},[ee]),we=_(()=>!S&&0===e.length&&!$&&!q,[S,e,$,O,q]),Ee=__name(()=>S||s||O||q||D?0:we||$?3:4,"getBottomMargin");return R.createElement(U,{width:"100%",flexDirection:"column",marginBottom:Ee()},!q&&R.createElement(U,{borderStyle:"round",borderRight:!1,borderLeft:!1,borderColor:$?"green":"gray",paddingY:0,width:"100%"},R.createElement(L,{color:$?"green":"dim"},$?"!":a.pointer),R.createElement(U,{flexGrow:1,paddingLeft:1},R.createElement(V,{key:A,value:e,placeholder:o,onChange:de,onSubmit:()=>{s||O||q||ue()},showCursor:r}))),S&&R.createElement(mr,null),D&&R.createElement(U,{paddingTop:1},R.createElement(L,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),s&&R.createElement(ir,{onSelectFile:me,onClose:ge,searchQuery:c}),O&&R.createElement(lr,{onSelectCommand:pe,onClose:he,searchQuery:z}),q&&R.createElement(dr,{onSelectSession:fe,onClose:ye}),we&&R.createElement(U,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1},R.createElement(U,null,k?R.createElement(U,{flexDirection:"row"},R.createElement(L,{color:"#E4CCFF"},"» accept edits on "),R.createElement(L,{dimColor:!0},"(shift+tab to toggle)")):R.createElement(L,{color:"dim"},"? for shortcuts")),R.createElement(U,{flexDirection:"row",columnGap:1},w&&R.createElement(U,null,R.createElement(L,null,R.createElement(L,null,a.tick," ","Command Code"," updated:"," "),R.createElement(L,{dimColor:!0},"v",w.updatedFrom),R.createElement(L,{dimColor:!0}," ",a.arrowRight," "),R.createElement(L,null,"v",w.updatedTo))),!w&&E&&R.createElement(R.Fragment,null,R.createElement(U,null,R.createElement(L,{color:"yellow",dimColor:!0},a.info," Update available:"," ",E.currentVersion," ",a.arrowRight," ",E.latestVersion)),(v||m||g||u)&&R.createElement(U,{marginLeft:1,marginRight:1},R.createElement(L,{dimColor:!0,color:"gray"},"•"))),C&&v&&R.createElement(R.Fragment,null,R.createElement(U,null,R.createElement(L,{color:"green",dimColor:!0},`${a.bullet} Provider: ${getProviderDisplayName(v)}`)),(u||T)&&R.createElement(U,{marginLeft:1,marginRight:1},R.createElement(L,{dimColor:!0,color:"gray"},"•"))),T&&R.createElement(R.Fragment,null,R.createElement(U,null,R.createElement(L,{color:"yellow",dimColor:!0},"internal mode (oauth)")),u&&R.createElement(U,{marginLeft:1,marginRight:1},R.createElement(L,{dimColor:!0,color:"gray"},"•"))),R.createElement(ur,{usage:u||null}))),$&&R.createElement(U,{paddingLeft:1},R.createElement(L,{color:"green"},"! for bash mode")),h&&p&&R.createElement(U,{paddingLeft:1},R.createElement(L,{color:"#E4CCFF"},"SHARED: ",p.url," (copied to clipboard)")),f&&R.createElement(U,{paddingLeft:1},R.createElement(L,{color:f.includes("NOT SHARED")?"red":"#E4CCFF"},f)),y&&R.createElement(U,{paddingLeft:1},R.createElement(L,{color:"#E4CCFF"},y)))},"InputBox"),pr=__name(()=>{const[e,t]=F("continuous learning"),n=M([]),r=M(0),o=M(null),a=M(!1);j(()=>{const e=__name(e=>"analyzing"===e.type?(a.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):a.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(a.current=!1,void(n.current.length>0?(r.current=0,s()):t("continuous learning"))):void 0,"handleNewEvent"),s=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const a="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,s()},a)},"cycleThroughNextEvent");return Vn.on("new-event",e),()=>{Vn.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const s=9+e.length+19>100;let i=e;if(s){const t=100;e.length>t&&(i=e.substring(0,t-3)+"...")}else{const t=72;e.length>t&&(i=e.substring(0,t-3)+"...")}return R.createElement(U,null,!s&&R.createElement(L,{color:"green"},"● taste: "),R.createElement(L,null,i),!s&&R.createElement(L,{dimColor:!0}," (ctrl+t to expand)"))},"LearningFeedMini"),hr=R.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:a,onSubmit:s,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:v,currentProvider:C,showProviderInfo:T,isOAuthMode:k,autoAcceptMode:A})=>{const[P,S]=F(0);return j(()=>{if(!t)return void S(0);const e=setInterval(()=>{S(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),R.createElement(U,{flexDirection:"column"},R.createElement(rr,{messages:e}),R.createElement(U,{flexDirection:"row",justifyContent:"space-between"},R.createElement(U,null,(t||n.isExecuting)&&R.createElement(sr,{tokens:m,timeElapsed:P,status:n.isExecuting?`Executing: ${n.currentCommand}`:r})),R.createElement(U,null,p&&R.createElement(pr,null))),R.createElement(gr,{input:o,setInput:a,onSubmit:s,placeholder:"Ask your question...",showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:v,currentProvider:C,showProviderInfo:T,isOAuthMode:k,autoAcceptMode:A}))}),fr=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=z(),[r,o]=F([]),[s,i]=F(0),[c,l]=F(!0),[d,u]=F(0),m=30;j(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await Mn.listSessions();o(e),l(!1)},"loadSessions");if(B((t,o)=>{o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t}):o.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=d+m&&u(t-m+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),c)return R.createElement(U,{flexDirection:"column",paddingLeft:2,paddingTop:1},R.createElement(L,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),a=Math.floor(n/864e5),s=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:a<7?`${a} day${a>1?"s":""} ago`:1===s?"1 week ago":`${s} weeks ago`},"formatRelativeTime"),h=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"gray"},"No sessions available"));const f=r.slice(d,d+m),y=d;return R.createElement(U,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&R.createElement(U,{marginBottom:1},R.createElement(L,{color:"dim"},"Showing ",d+1,"-",Math.min(d+m,r.length)," ","of ",r.length," sessions",d>0&&" (↑ for more)",d+m<r.length&&" (↓ for more)")),R.createElement(U,{columnGap:2,marginBottom:1},R.createElement(U,{width:7},R.createElement(L,{color:"gray"}," ")),R.createElement(U,{width:13},R.createElement(L,{color:"gray"},"Modified")),R.createElement(U,{width:11},R.createElement(L,{color:"gray"},"# Messages")),R.createElement(U,{width:20},R.createElement(L,{color:"gray"},"Git Branch")),R.createElement(U,null,R.createElement(L,{color:"gray"},"Summary"))),R.createElement(U,{columnGap:2},R.createElement(U,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${a.pointer} ${n+1}.`:` ${n+1}.`)})),R.createElement(U,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`mod-${e.id}`,color:s===n?"white":"gray"},p(e.lastModified))})),R.createElement(U,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),R.createElement(U,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),R.createElement(U,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return R.createElement(L,{key:`summary-${e.id}`,color:s===n?"white":"gray"},h(e.firstMessage))}))))},"SessionTable");function RetryMessage({attempt:e}){const[t,n]=F(0);if(j(()=>{if(null===e)return;const t=setInterval(()=>{n(e=>(e+1)%4)},500);return()=>clearInterval(t)},[e]),null===e)return null;const r=".".repeat(t).padEnd(3," ");return R.createElement(U,{marginBottom:1},R.createElement(L,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}__name(RetryMessage,"RetryMessage");var yr=__name(({onTrust:e,onExit:t})=>{const{exit:n}=z(),[r,o]=F(1),s=process.cwd().replace(process.env.HOME||"","~");return B((a,s)=>{s.upArrow||s.downArrow?o(1===r?2:1):s.return?1===r?e():(t(),n()):"1"===a?e():("2"===a||s.escape||s.ctrl&&"c"===a)&&(t(),n())}),R.createElement(U,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1},R.createElement(L,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),R.createElement(U,{marginTop:1},R.createElement(L,{color:"gray"},s)),R.createElement(U,{marginTop:1,flexDirection:"column"},R.createElement(L,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),R.createElement(U,{marginTop:1},R.createElement(L,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),R.createElement(U,{marginTop:1,flexDirection:"column"},R.createElement(U,null,R.createElement(L,{color:1===r?"cyan":"gray"},1===r?a.pointer:" "," 1. Yes, proceed")),R.createElement(U,null,R.createElement(L,{color:2===r?"cyan":"gray"},2===r?a.pointer:" "," 2. No, exit"))))},"TrustPrompt"),wr=class extends me{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||y.join(e,".commandcode","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 P.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.autoApprove&&(void 0!==t.permissions.autoApprove.create&&(this.config.autoApprove.create=t.permissions.autoApprove.create),void 0!==t.permissions.autoApprove.update&&(this.config.autoApprove.edit=t.permissions.autoApprove.update),void 0!==t.permissions.autoApprove.delete&&(this.config.autoApprove.delete=t.permissions.autoApprove.delete)),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=y.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=y.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?Array.isArray(e.args)?e.args.join(" "):e.args:""}`.trim()}isTrustedCommand(e){return!!["ls","ls -la","ls -l","ls -R","pwd","grep","tree","find","stat","file","dirname","basename","grep","git status","git log","git diff","git branch"].some(t=>e===t||!!e.startsWith(t+" "))||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=y.join(this.projectRoot,".commandcode"),t=y.join(e,"settings.local.json");try{await P.mkdir(e,{recursive:!0});let n={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await P.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 P.writeFile(t,JSON.stringify(n,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const t=y.join(this.projectRoot,".commandcode"),n=y.join(t,"settings.local.json"),r=`Bash(${e.split(" ")[0]}:*)`;try{let e;await P.mkdir(t,{recursive:!0});try{const t=await P.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 P.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},Er=__name((e={})=>{const[t,n]=F(null),[r,o]=F(null),[a,s]=F(!1);return j(()=>{const t=e.projectRoot||process.cwd(),r=new wr(t);return r.on("permission-request",(t,n)=>{o(t),s(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),s(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:N(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:N(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:N(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),s(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),s(!1)}},[t]),clearSessionPermissions:N(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:N(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:N((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:N(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:a,service:t}},"usePermissions"),br=__name(({request:e,onResponse:t})=>{const[n]=F(0),r=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, for this session only",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],o=__name(e=>{const n=r.find(t=>t.value===e.value);n&&t(n)},"handleSelect"),s=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),i=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const t=y.basename(e.filePath),n=y.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(U,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0,color:"yellow"},`${c()} ${"edit"===e.action?i():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&R.createElement(U,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:i(),marginLeft:0}).diffContent),R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0},"Do you want to ",s()," ",R.createElement(L,{color:"cyan"},i()),"?")),R.createElement(Ee,{items:r.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:"cyan"},e?a.pointer:" "),itemComponent:({label:e,isSelected:t})=>R.createElement(L,{color:t?"cyan":"white"},e.includes("(")?R.createElement(R.Fragment,null,e.split("(")[0],R.createElement(L,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),vr=__name(({request:e,onResponse:t})=>{const[n]=F(0),r=[{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:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],o=__name(e=>{const n=r.find(t=>t.value===e.value);n&&t(n)},"handleSelect"),s=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"",n=t?`${e.command} ${t}`:e.command;return n.length>60?n.substring(0,57)+"...":n},"getCommandDisplay");return R.createElement(U,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0,color:"yellow"},"Execute Shell Command")),R.createElement(U,{marginBottom:1},R.createElement(L,{bold:!0},"Command Code needs to execute ",R.createElement(L,{color:"cyan"},s()),".")),e.workingDirectory&&R.createElement(U,{marginBottom:1},R.createElement(L,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&R.createElement(U,{marginBottom:1},R.createElement(L,{color:"gray",italic:!0},e.description)),R.createElement(Ee,{items:r.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:"cyan"},e?a.pointer:" "),itemComponent:({label:e,isSelected:t})=>R.createElement(L,{color:t?"cyan":"white"},e)}))},"ShellPermissionPrompt"),Cr=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole"),Tr=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=F(!1),[a,s]=F(!0);j(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{s(!1)}},"loadSettings")()},[]),B((t,n)=>{if(!n.return&&" "!==t)return n.escape?(Cr(),void e()):void 0;i()});const i=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return a?R.createElement(U,{key:n,borderStyle:"round",borderColor:"blue",padding:1,flexDirection:"column"},R.createElement(L,{color:"blue",bold:!0},"Taste Settings"),R.createElement(L,{dimColor:!0},"Loading configuration...")):R.createElement(U,{key:n,borderStyle:"round",borderColor:"gray",padding:1,flexDirection:"column"},R.createElement(L,{bold:!0},"Taste Learning"),R.createElement(L,{dimColor:!0},"Configure taste learning preferences for this project"),R.createElement(U,{marginTop:1}),R.createElement(U,{justifyContent:"space-between"},R.createElement(L,null,"Taste learning",R.createElement(L,{dimColor:!0}," - Learn from your interactions")),R.createElement(L,{color:r?"green":"gray"},r?"enabled":"disabled")),R.createElement(U,{marginTop:1}),R.createElement(L,{dimColor:!0},"Taste data stored in .commandcode/taste/"),R.createElement(L,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig"),kr=__name(({onClose:e})=>{const[t,n]=F(Vn.getEvents());B((t,n)=>{n.ctrl&&"t"===t&&(Cr(),e())},{isActive:!0}),j(()=>{const e=__name(()=>{n(Vn.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return Vn.on("new-event",e),Vn.on("cleared",t),()=>{Vn.off("new-event",e),Vn.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored","updated"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase(),n=t[2],r={learned:"Learned",upgraded:"Reinforced",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:r,content:n}}return{type:null,label:null,content:e}},"formatLearningMessage"),s=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),i=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails");return R.createElement(U,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},R.createElement(U,{flexDirection:"column",marginBottom:1},R.createElement(pe,{name:"vice"},R.createElement(L,null,Xn()),R.createElement(L,null,er()))),R.createElement(U,{marginBottom:1,width:"100%",justifyContent:"space-between"},R.createElement(U,null,R.createElement(L,{bold:!0},"Learning Feed"),R.createElement(L,{dimColor:!0}," - Real-time taste learning activity")),R.createElement(L,{dimColor:!0},"Press ctrl+t to close")),R.createElement(U,{flexDirection:"column"},0===t.length?R.createElement(U,null,R.createElement(L,{dimColor:!0},"No learning events yet...")):R.createElement(U,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r}=o(e.message),a="moved"===t?i(e.details):null,c="upgraded"===t?s(r):null;return R.createElement(U,{key:e.id,marginBottom:1},R.createElement(U,{flexDirection:"column"},R.createElement(U,null,R.createElement(L,{backgroundColor:"green",color:"#FFFFFF",bold:!0},` ${n} `),a?R.createElement(L,{dimColor:!0}," (",a.fullPath,")"):e.details?R.createElement(L,{dimColor:!0}," (",e.details,")"):null),R.createElement(U,null,R.createElement(L,{dimColor:!0},"⎿"," "),a?R.createElement(R.Fragment,null,R.createElement(L,null,a.category," package ("),R.createElement(L,{dimColor:!0},a.oldPath),R.createElement(L,null," → ",a.newPath),R.createElement(L,null,")")):c?R.createElement(R.Fragment,null,R.createElement(L,null,c.text," ("),R.createElement(L,{dimColor:!0},c.oldPercent,"%"),R.createElement(L,null," → "),R.createElement(L,{color:c.diff>0?"green":"red"},c.newPercent,"%"),R.createElement(L,null,")")):R.createElement(L,null,r))))}return R.createElement(U,{key:e.id,marginBottom:1},R.createElement(L,{dimColor:!0},a.pointerSmall," ",e.message))}))))},"LearningFeedFull"),Ar=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");B((e,n)=>{n.escape&&t()});const a=n?r.findIndex(e=>e.value===n):0,s=n&&-1===a;return R.createElement(U,{flexDirection:"column",paddingX:0,width:"100%"},R.createElement(U,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},R.createElement(U,null,R.createElement(L,{bold:!0},"Select AI Provider")),n&&R.createElement(U,{flexDirection:"row"},R.createElement(L,{dimColor:!0},"Current: "),R.createElement(L,{color:"green"},getProviderDisplayName(n)),s&&R.createElement(L,{color:"yellow"}," [OAuth enforced]"))),R.createElement(U,{marginBottom:0},R.createElement(L,{dimColor:!0},"Available Providers:")),R.createElement(Ee,{items:r,onSelect:o,initialIndex:a>=0?a:0,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"cyan":"gray",bold:e},` ${t}`)}),R.createElement(U,{marginTop:1},R.createElement(L,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector"),Pr=__name(({onClose:e})=>{const[t,n]=F([]),[r,o]=F(0),[a,s]=F(!0),[i,c]=F(null);j(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),s(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),s(!1)}},"loadMemoryFiles")()},[]);const l=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(B((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&l(d[r]),"1"===t&&d[0]&&l(d[0]),"2"===t&&d[1]&&l(d[1]))}),a)return R.createElement(U,{paddingLeft:1,paddingTop:1},R.createElement(L,{color:"dim"},"Loading memory files..."));if(i)return R.createElement(U,{paddingLeft:1,paddingTop:1},R.createElement(L,{color:"red"},"❌ ",i));const u=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return R.createElement(U,{flexDirection:"column",width:"100%",borderStyle:"round",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},R.createElement(U,null,R.createElement(L,{color:"white",bold:!0},"Select memory to edit:")),R.createElement(U,{columnGap:4,marginTop:1},R.createElement(U,{flexDirection:"column"},u.map((e,t)=>R.createElement(L,{key:t,color:r===t?"white":"dim"},r===t?"> ":" ",e.label))),R.createElement(U,{flexDirection:"column"},u.map((e,t)=>R.createElement(L,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector"),Sr=class{static{__name(this,"TasteManager")}static async initializeProject(){const e=process.cwd(),t=f.join(e,".commandcode","taste");await A.mkdir(t,{recursive:!0});const n=f.join(t,"taste.md");try{await A.access(n)}catch{await A.writeFile(n,"# Taste (Continuously Learned by CommandCode)\n\n")}}static async isInitialized(){const e=process.cwd(),t=f.join(e,".commandcode","taste");try{return await A.access(t),!0}catch{return!1}}},xr=__name(({staticKey:e})=>R.createElement(O,{items:[{staticKey:e}],key:e},()=>R.createElement(L,{key:e},"\0")),"Responsive"),$r=__name(()=>y.join(k.homedir(),".commandcode","agents"),"getRootAgentDir"),Ir=__name(()=>y.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Dr=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=F("idle"),[a,s]=F(""),i=[...Un.map(e=>e.name),...Ln.map(e=>e.name)],c=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void s("Agent configuration is incomplete");o("saving");try{const n="personal"===e.location?$r():Ir();await P.mkdir(n,{recursive:!0});const r=`${e.agentType}.md`,o=y.join(n,r),a=Array.from(e.selectedTools).map(e=>Wn[e]||e).join(", "),s=0===e.selectedTools.size?"none":e.selectedTools.size===i.length?'"*"':JSON.stringify(a),c=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${s}\n---\n\n${e.sysPrompt}\n`;await P.writeFile(o,c,"utf-8"),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),s(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");B((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||c()});const l=Array.from(e.selectedTools).map(e=>Wn[e]||e).join(", "),d="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return R.createElement(U,{flexDirection:"column",gap:1},R.createElement(U,{flexDirection:"column"},R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"Name:"),R.createElement(L,{color:"gray"},e.agentType)),R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"Location:"),R.createElement(L,{color:"gray"},d)),R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"Tools:"),R.createElement(L,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===i.length?"*":l))),R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"Description"),R.createElement(L,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),R.createElement(L,{color:"gray"},e.ccToolDefinition),R.createElement(U,{gap:1},R.createElement(L,{color:"white",bold:!0},"System Prompt:")),R.createElement(L,{color:"gray"},e.sysPrompt),!n&&R.createElement(U,{marginTop:1},"idle"===r&&R.createElement(U,{gap:1},R.createElement(L,{color:"green",dimColor:!0},"Press"),R.createElement(L,{color:"green",bold:!0},"Enter"),R.createElement(L,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===r&&R.createElement(L,{color:"yellow"},"Saving agent..."),"saved"===r&&R.createElement(L,{color:"green"},"✓ ",a),"error"===r&&R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"red"},"✗ Error: ",a),R.createElement(L,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),Rr=__name(({agent:e,onBack:t,setRevalidateAgent:n})=>{const[r,o]=F("menu"),a=[...Un.map(e=>e.name),...Ln.map(e=>e.name)];let s=new Set;if("*"===e.tools||'"*"'===e.tools)s=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>zn[e]||e);s=new Set(t)}const i={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:s},c=__name(e=>{"back"===e.value?t():"view"===e.value?o("view"):"edit"===e.value?o("edit"):"delete"===e.value&&o("delete")},"handleMenuSelect");if(B((e,n)=>{n.escape&&("menu"===r?t():o("menu")),n.return&&"view"===r&&o("menu")}),"view"===r)return R.createElement(U,{flexDirection:"column"},R.createElement(Dr,{config:i,onSaveComplete:()=>o("menu"),viewOnly:!0}),R.createElement(U,{marginTop:1},R.createElement(L,{color:"gray"},"Press Enter to go back")));if("edit"===r)return R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"yellow"},"Edit functionality coming soon..."),R.createElement(L,{color:"gray"},"Press Esc to go back"));if("delete"===r){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],a=__name(async r=>{if("confirm-delete"===r.value)try{await P.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return R.createElement(U,{flexDirection:"column",gap:1},R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"red"},"Delete agent"),R.createElement(L,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),R.createElement(U,null,R.createElement(Ee,{items:r,onSelect:a,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"white":"gray"},` ${t}`)})))}return R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"white",bold:!0},e.name),R.createElement(U,{marginTop:1},R.createElement(Ee,{items:[{label:"1. View agent",value:"view"},{label:"2. Delete agent",value:"delete"},{label:"3. Back",value:"back"}],onSelect:c,indicatorComponent:({isSelected:e})=>R.createElement(L,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"white":"gray"},` ${t}`)})),R.createElement(U,{marginTop:1},R.createElement(L,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Fr=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=F([]),[o,a]=F([]),[s,i]=F(!0),[c,l]=F(!1),[d,u]=F(null),[m,g]=F(!1),p=__name(()=>y.join(k.homedir(),".commandcode","agents"),"getRootAgentDir"),h=__name(()=>y.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),f=__name(async(e,t)=>{try{l(!1);const n=(await P.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=y.join(e,n),o=await P.readFile(r,"utf-8"),{data:a,content:s}=le(o);let i=a.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:a.name||n.replace(".md",""),description:a.description||"",tools:i,sysPrompt:s.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");j(()=>{__name(async()=>{i(!0);const[e,t]=await Promise.all([f(p(),"personal"),f(h(),"project")]);r(e),a(t),i(!1)},"loadAgents")()},[c]);const w=[{label:"Create new agent",value:"create_new_agent"}];n.forEach(e=>{w.push({label:e.name,value:e.filePath})}),o.forEach(e=>{w.push({label:e.name,value:e.filePath})});const E=n.length>0||o.length>0,b=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...n,...o].find(e=>e.filePath===t.value);e&&(u(e),g(!0))}},"handleAgentSelect");if(s)return R.createElement(L,{color:"gray"},"Loading agents...");if(m&&d)return R.createElement(Rr,{agent:d,onBack:()=>{g(!1),u(null)},setRevalidateAgent:l});const v=__name(({isSelected:e,label:t})=>{const r=w.find(e=>e.label===t),a=r?.value||"",s=n[0]?.filePath===a,i=o[0]?.filePath===a;return R.createElement(U,{flexDirection:"column"},s&&n.length>0&&R.createElement(U,{marginTop:1,marginLeft:2},R.createElement(L,{color:"white"},"User agents (~/",".commandcode","/","agents",")")),i&&o.length>0&&R.createElement(U,{marginTop:1,marginLeft:2},R.createElement(L,{color:"white"},"Project agents")),R.createElement(U,null,R.createElement(L,{color:"white"},e?">":" "),R.createElement(L,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return R.createElement(U,{flexDirection:"column"},R.createElement(U,{flexDirection:"column",marginBottom:1},R.createElement(L,{color:"white",bold:!0},"Agents"),E?R.createElement(L,{color:"gray"},n.length+o.length," agents"):R.createElement(L,{color:"gray"},"No agents found")),t&&R.createElement(U,{flexDirection:"column",marginBottom:1},R.createElement(L,{color:"green",dimColor:!0},"Created agent: ",t)),R.createElement(Ee,{items:w,onSelect:b,indicatorComponent:()=>null,itemComponent:v}),!E&&R.createElement(U,{flexDirection:"column",marginTop:1},R.createElement(L,{color:"gray"},"No agents found. Create specialized subagents that Command Code can delegate to."),R.createElement(L,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools."),R.createElement(L,{color:"gray"},"Try creating: Code Reviewer, Code Simplifier, Security Reviewer, Tech Lead, or UX Reviewer.")))},"ManageAgents"),jr=__name(({onSelect:e})=>R.createElement(Ee,{items:[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>R.createElement(L,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector"),Mr=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:a,onCCToolDefinitionChange:s,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=F(!1),[m,g]=F(!1),p=N(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[d,a]),h=N(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||m){if(!m||t.isPasteEnd){if(m&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[m,s]);return"agentType"===e?R.createElement(R.Fragment,null,R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(Wn).some(e=>ue(e)===ue(t))||Object.keys(Wn).some(e=>ue(e)===ue(t)))&&R.createElement(L,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name.")),R.createElement(V,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=ue(t);Object.values(Wn).some(t=>ue(t)===e)||Object.keys(Wn).some(t=>ue(t)===e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?R.createElement(R.Fragment,null,R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"white"},"Enter the system prompt for your agent:"),R.createElement(L,{color:"gray"},"Be comprehensive for best results.")),R.createElement(V,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?R.createElement(R.Fragment,null,R.createElement(L,{color:"white"},"When should ","Command Code"," use this agent?"),R.createElement(V,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&l()},onChange:h,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow"),Nr=__name(({onSelect:e})=>R.createElement(Ee,{items:[{label:"1. Generate with Command Code (recommended)",value:"recommended"},{label:"2. Manual configuration",value:"manual"}],onSelect:t=>{"recommended"!==t.value&&"manual"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>R.createElement(L,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>R.createElement(L,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector"),_r=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=F(!1),[c,l]=F(0),d=N(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[s,t]);return R.createElement(U,{flexDirection:"column"},r?R.createElement(U,null,R.createElement(GlowIcon,null),R.createElement(L,{color:"white"},"Generating agent from description...")):R.createElement(V,{key:c,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:d,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&R.createElement(U,{marginTop:1},R.createElement(L,{color:"red"},`${a.warning} ${o}`)))},"RecommendedFlow"),Or=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,a]=F(!1),[s,i]=F(0),c=_(()=>[...Un.map(e=>e.name),...Ln.map(e=>e.name)],[]),l=_(()=>[{name:"All tools",tools:c},{name:"Read-only tools",tools:c.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:c.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:c.filter(e=>"shell_command"===e)},{name:"Search tools",tools:c.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:c.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[c]),d=_(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),c.forEach(t=>{e.push({type:"tool",value:t})})):(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,l,e,c]),u=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=l.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${o?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${Wn[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),m=u.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return B((e,c)=>{if(c.upArrow)i(e=>{const t=e-1;return t<0?m.length-1:t});else if(c.downArrow)i(e=>{const t=e+1;return t>=m.length?0:t});else if(c.return||" "===e){const e=m[s];if(e){const s=d[e.value];if(!s)return;"continue"===s.type?r():"toggle"===s.type?(a(!o),i(0)):"category"===s.type?n(s.value):"tool"===s.type&&t(s.value)}}}),R.createElement(U,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===s;if("divider"===e.type)return R.createElement(U,{key:`divider-${t}`},R.createElement(L,{color:"gray"}," ",e.label));if("spacer"===e.type)return R.createElement(U,{key:`spacer-${t}`,height:1});if("label"===e.type)return R.createElement(U,{key:`label-${t}`},R.createElement(L,{color:"gray"}," ",e.label));const o="continue"===e.type;return R.createElement(U,{key:`item-${t}`},R.createElement(L,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),R.createElement(U,{marginTop:1},e.size===c.length&&R.createElement(L,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&R.createElement(L,{color:"gray"},e.size," tools selected"),0===e.size&&R.createElement(L,{color:"gray"},"No tools selected")))},"ToolsSelector"),Ur=__name(({onComplete:e})=>{const[t,n]=F("location"),[r,o]=F(!1),[a,s]=F(null),[i,c]=F("agentType"),l=_(()=>[...Un.map(e=>e.name),...Ln.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=F(d()),g=__name(t=>{n("location"),c("agentType"),m(d()),e(t)},"resetToDefaults"),p=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===u.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===i)return"Agent type (identifier)";if("sysPrompt"===i)return"System prompt";if("ccToolDefinition"===i)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),h=__name(e=>{m({...u,location:e}),n("method")},"handleLocationSelect"),f=__name(e=>{m({...u,method:e}),n("configuration")},"handleMethodSelect"),y=__name(async()=>{try{s(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===je&&(r=await Me.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const a={[Se]:t.toString()};r&&(a[xe]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new dt({baseUrl:i}),l=await c.post({headers:a,endpoint:De.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription}});m({...u,agentType:ue(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof nt&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?s(Ne):s("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),w=__name(()=>{m({...u,agentType:ue(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),b=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),v=__name(()=>{n("summary")},"handleToolsComplete"),C=__name(e=>{const t=new Set(u.selectedTools);t.has(e)?t.delete(e):t.add(e),m({...u,selectedTools:t})},"handleToggleTool"),T=__name(e=>{const t=[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(u.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),m({...u,selectedTools:n})},"handleToggleCategory");return R.createElement(U,{flexDirection:"column",gap:1},R.createElement(U,{flexDirection:"column"},R.createElement(L,{color:"white",bold:!0},"Create new agent"),R.createElement(L,{color:"gray"},p())),R.createElement(U,null,"location"===t&&R.createElement(jr,{onSelect:h}),"method"===t&&R.createElement(Nr,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&R.createElement(_r,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:a,onSubmit:y}),"configuration"===t&&"manual"===u.method&&R.createElement(U,{flexDirection:"column",gap:1},R.createElement(Mr,{step:i,agentType:u.agentType,sysPrompt:u.sysPrompt,ccToolDefinition:u.ccToolDefinition,onAgentTypeChange:e=>m({...u,agentType:e}),onSysPromptChange:e=>m({...u,sysPrompt:e}),onCCToolDefinitionChange:e=>m({...u,ccToolDefinition:e}),onAgentTypeSubmit:w,onSysPromptSubmit:E,onCCToolDefinitionSubmit:b})),"tools"===t&&R.createElement(Or,{selectedTools:u.selectedTools,onToggleTool:C,onToggleCategory:T,onComplete:v}),"summary"===t&&R.createElement(Dr,{config:u,onSaveComplete:g})))},"AgentNew"),Lr=__name(({onCancel:e})=>{const[t,n]=F(null),[r,o]=F(null),a=__name(e=>{n(e.value),o(null)},"handleSelect");return B((t,n)=>{n.escape&&e()}),R.createElement(U,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"round",flexDirection:"column"},null===t&&R.createElement(Fr,{handleSelect:a,createdAgentName:r}),"create_new_agent"===t&&R.createElement(Ur,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r=["create","edit","delete","execute","shellCommands"];for(const e of r)n.setAutoApprove(e,t)}__name(applyAutoAcceptMode,"applyAutoAcceptMode");var{setText:Br}=ge,Wr=__name(({resume:e=!1,continue:t=!1,trust:n=!1,updateStatus:r,updateFailedInfo:o})=>{const{exit:a}=z(),[s,i]=F(""),[c,l]=F("Ready..."),[d,u]=F(null),[m,g]=F(r);j(()=>{if(m){const e=setTimeout(()=>{g(null)},3e4);return()=>clearTimeout(e)}},[m]);const{stdout:p}=G(),[h,f]=F(!1),[y,w]=F(!1),[E,b]=F(!1),[v,C]=F(!1),[T,k]=F(!1),[A,P]=F(!1),[S,x]=F(null),[$,I]=F(null),[D,N]=F(!1),[_,O]=F(!1),W=M(null),[V,q]=F(0),[H,J]=F(!1),{executeBash:K,executionState:Y}=dn(),[Q,Z]=F(""),[X,ee]=F([]),[te,ne]=F(!1),[re,oe]=F([]),[ae,se]=F(crypto.randomUUID()),[ie,ce]=F(!1),[le,de]=F(!1),[ue,me]=F(!1),[ge,pe]=F(!1),[he,fe]=F(!0),[ye,we]=F(!1),[Ee,be]=F(0),[ve,Ce]=F(null),[Te,ke]=F(null),[Ae,Pe]=F(null),Se=M(!1),xe=M(Ae);j(()=>{xe.current=Ae},[Ae]);const[$e,Ie]=F(!1),[Re,Fe]=F(""),[je,Ne]=F(!1),[_e,Oe]=F(!1),Ue=__name(async()=>{try{const e=await isTasteLearningEnabled();Ne(e),e&&await Sr.initializeProject()}catch(e){}},"loadTasteStatus"),Le=__name(async()=>{const e=await getConfiguredProvider();I(e);const t=await isOAuthEnforced();N(t)},"loadCurrentProvider"),Be=M([]),We=M(null),[ze,Ge]=F(null),{requestShellPermission:Ve,service:qe,respondToPrompt:He,clearSessionPermissions:Je,setEnabled:Ke}=Er({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{Ge({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),We.current&&l("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Ge({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),We.current&&l("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?l("Permission granted"):l("Permission denied")},"onPermissionResponse")});async function getBillingLink(){if(Te)return Te;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return ke(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return ke(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}j(()=>{qe&&applyAutoAcceptMode({enabled:_e,service:qe})},[_e,qe]),j(()=>{(async()=>{if(await Mn.isProjectInitialized())if(pe(!0),fe(!1),Ue(),Le(),t){const e=await Mn.listSessions();if(e.length>0){const t=e[0];at(t.id)}}else e&&ce(!0);else if(n)if(await Mn.initializeProject(),pe(!0),fe(!1),Ue(),Le(),t){const e=await Mn.listSessions();if(e.length>0){const t=e[0];at(t.id)}}else e&&ce(!0);else me(!0),fe(!1)})()},[e,t,n,a]),j(()=>{Be.current=re},[re]),j(()=>{(async()=>{if($&&"anthropic"===$&&D)try{await Me.getValidAccessToken()||l("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){l("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[$,D]),j(()=>{if(!te)return;const e=setInterval(()=>{l(an())},7e3);return()=>clearInterval(e)},[te]),j(()=>()=>{W.current&&clearTimeout(W.current)},[]),B((e,t)=>{if(!(E||v||T||S||A)){if(t.ctrl&&"c"===e&&a(),t.ctrl&&"t"===e)return Cr(),P(e=>!e),void q(e=>e+1);if(t.shift&&t.tab)Oe(e=>!e);else{if(getIsExpandToolShortcut(t,e))return Cr(),J(e=>!e),void q(e=>e+1);if(t.escape)if(ze)He({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),ze.resolve(!1),Ge(null),l("Permission denied");else if(te&&We.current){We.current.interrupt(!0),ne(!1),l("Interrupted by user");const e=Xt("Interrupted by user");ee(t=>[...t,e])}t.meta||t.ctrl}}}),j(()=>{const e=__name(()=>{Cr(),q(e=>e+1)},"handleResize");if(p)return p.on("resize",e),()=>{p.off("resize",e)}},[p]),j(()=>{We.current||!ge||ie||le||(We.current=new Yn({onFeedUpdate:__name(e=>{ee(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Be.current];return Be.current=[],oe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{be(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ce(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{u(e)},"onRetryUpdate"),onProviderChange:__name(e=>{I(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&qe){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",n={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${e}`};return qe.requestShellPermission(n).then(e=>e.allowed)}if(qe){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`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return qe.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=xe.current;return e?{sessionId:ae,secret:e.secret}:null},"getShareInfo")},ae),(async()=>{await tt()})())},[ae,ie,le,ge]),__name(getBillingLink,"getBillingLink");const Ye=__name(async({role:e,input:t,images:n})=>{if(t.length)if(m&&g(null),be(0),"bash"===e){if(Se.current)return;Se.current=!0;const e=Qt(t);ee([...X,e]),i(""),await K(t,e=>{ee(e)},()=>{Cr(),q(e=>e+1)}),Se.current=!1}else{if(te)return oe(e=>[...e,t]),void i("");if(Se.current)return;Se.current=!0,ne(!0),l(an()),i("");try{We.current&&await We.current.sendMessage(t,n)}catch(e){if("Interrupted by user"===e?.message||e?.message?.toLowerCase().includes("interrupt")||e?.message?.toLowerCase().includes("abort")||"InterruptedError"===e?.name||"AbortError"===e?.name||"ECONNABORTED"===e?.code);else if("Insufficient credits"===e.message){l("Insufficient credits");const e=await getBillingLink(),t=Xt(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);ee(e=>[...e,t])}else if(e.message.startsWith("Error:")){l("Error");const t=Xt(e.message);ee(e=>[...e,t])}else{l("Error");const t=e.message||"An unexpected error occurred",n=Xt(t);ee(e=>[...e,n])}}finally{ne(!1),"Interrupted by user"!==c&&"Permission denied"!==c&&"Insufficient credits"!==c&&l("Ready..."),Se.current=!1}}},"handleSubmit"),Qe=__name(()=>{const e=`**Command Code v0.0.4-beta.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${cr.filter(e=>"/help"!==e.command).map(e=>`**${e.command}** - ${e.description}`).join("\n")}`;ee(t=>[...t,Zt(e)])},"handleHelpCommand"),Ze=__name(async()=>{if(ee([]),Cr(),Oe(!1),Pe(null),Ie(!1),Fe(""),We.current){const e=We.current.getSessionManager();e&&await e.deleteShareInfo(),We.current=null;const t=crypto.randomUUID();se(t),Je(),We.current=new Yn({onFeedUpdate:__name(e=>{ee(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Be.current];return Be.current=[],oe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{be(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ce(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{u(e)},"onRetryUpdate"),onProviderChange:__name(e=>{I(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&qe){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",n={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${e}`};return qe.requestShellPermission(n).then(e=>e.allowed)}if(qe){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`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return qe.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=xe.current;return e?{sessionId:t,secret:e.secret}:null},"getShareInfo")},t)}q(e=>e+1),Ce(null),be(0)},"handleClearCommand"),Xe=__name(async()=>{if(We.current)if(We.current.isRequestInProgress())ee(e=>[...e,Jt("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{l("Compacting conversation...");const e=await We.current.compactConversation();Cr(),q(e=>e+1);const t=e.messagesRemoved>0?`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`:"Conversation is already compact.";ee(e=>[...e,Jt(t)]),l("Ready..."),Ce({current:We.current.getContextTokensUsed()||0,limit:jn})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;ee(e=>[...e,Xt(t)]),l("Ready...")}else ee(e=>[...e,Jt("No active conversation to compact.")])},"handleCompactCommand"),et=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await at(t)}switch(e){case"/exit":a();break;case"/clear (reset, new)":await Ze();break;case"/help":Qe();break;case"/share":nt();break;case"/unshare":ot();break;case"/taste":b(!0);break;case"/provider":C(!0);break;case"/memory":k(!0);break;case"/init":rt();break;case"/agents":w(!0);break;case"/compact":await Xe();break;default:const t=getCustomCommandContent(e);t&&await Ye({input:t,role:"user"})}},"handleCommand"),tt=__name(async()=>{const e=We.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&Pe({url:t.url,secret:t.secret})}},"loadShareInfo"),nt=__name(async()=>{if(ae){if(Ae)return await Br(Ae.url),l(""),Ie(!0),void setTimeout(()=>{Ie(!1)},3e3);try{l("Creating share link...");const e=We.current?.getMessages()||[],t=Gn.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new dt({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:De.ALPHA.SHARE.CREATE,body:{sessionId:ae,messages:t}}),o={url:r.url,secret:r.secret};Pe(o);const a=We.current?.getSessionManager();a&&await a.saveShareInfo({url:r.url,secret:r.secret}),await Br(r.url),l(""),Ie(!0),setTimeout(()=>{Ie(!1)},5e3)}catch(e){l(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else l("No active session to share")},"handleShareCommand"),rt=__name(async()=>{try{const e=process.cwd(),t=`Created AGENTS.md at ${await initProjectMemory(e)}. You can now edit it with /memory or open it in your editor.`;ee(e=>[...e,Jt(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;ee(e=>[...e,Jt(t)])}},"handleInitCommand"),ot=__name(async()=>{if(ae){if(!Ae)return Fe("NOT SHARED: Session is not currently shared"),void setTimeout(()=>Fe(""),5e3);try{l("Removing share link...");const e=new dt({baseUrl:getApiBaseUrl()});await e.delete({endpoint:De.ALPHA.SHARE.DELETE,body:{sessionId:ae,secret:Ae.secret}});const t=We.current?.getSessionManager();t&&await t.deleteShareInfo(),Fe("UNSHARED: Sharing has stopped"),l(""),Pe(null),setTimeout(()=>{Fe("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;l(t),setTimeout(()=>l(""),5e3)}}else l("No active session to unshare")},"handleUnshareCommand"),at=__name(async e=>{try{ee([]),We.current=null,Oe(!1),se(e),ce(!1),de(!0),await new Promise(e=>setTimeout(e,100)),We.current=new Yn({onFeedUpdate:__name(e=>{ee(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Be.current];return Be.current=[],oe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{be(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ce(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{u(e)},"onRetryUpdate"),onProviderChange:__name(e=>{I(e)},"onProviderChange"),getShareInfo:__name(()=>{const t=xe.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const t=await We.current.loadSession(e);await tt(),ee(t),Cr(),q(e=>e+1)}catch(e){console.error("Failed to load session:",e),ce(!0),se(crypto.randomUUID())}},"handleSelectSession"),st=__name(async()=>{ee([]),We.current=null,Oe(!1),se(crypto.randomUUID()),ce(!1),de(!1)},"handleNewSession"),it=__name(async()=>{try{await Mn.initializeProject(),me(!1),e?(console.log("No conversations found to resume."),we(!0),a()):(pe(!0),Ue(),Le())}catch(e){console.error("Failed to initialize project:",e),me(!1),we(!0),a()}},"handleTrust"),ct=__name(()=>{a()},"handleNoTrust"),lt=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void x({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),I(e),C(!1);const n=getProviderDisplayName(e);l(`Provider set to ${n}`),W.current&&clearTimeout(W.current),O(!0),W.current=setTimeout(()=>{O(!1),W.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),l("Failed to set provider"),C(!1)}},"handleProviderSelect"),ut=__name(()=>{C(!1)},"handleProviderCancel"),mt=__name(()=>{if(S){x(null),C(!1),I(S.provider);const e=getProviderDisplayName(S.provider);l(`${e} authentication successful`),W.current&&clearTimeout(W.current),O(!0),W.current=setTimeout(()=>{O(!1),W.current=null},5e3)}},"handleAuthSuccess"),gt=__name(()=>{x(null)},"handleAuthCancel");if(ye)return null;if(ue)return R.createElement(R.Fragment,null,R.createElement(xr,{staticKey:V}),R.createElement(yr,{onTrust:it,onExit:ct}));if(he)return null;if(ie)return R.createElement(fr,{onSelectSession:at,onNewSession:st});if(!ge)return null;if(ze){if("shell_command"===ze.toolName){const e=ze.params;return R.createElement(U,{flexDirection:"column",width:"100%"},R.createElement(nr,{staticKey:V,feed:X,showHeader:!0,expandedToolOutput:H}),R.createElement(U,{marginY:1},R.createElement(vr,{request:e,onResponse:e=>{He(e);const t="no"!==e.value;ze.resolve(t),Ge(null),l(t?"Shell command allowed":"Shell command denied")}})))}{const e={action:ze.toolName.includes("edit")?"edit":ze.toolName.includes("write")?"create":ze.toolName.includes("delete")?"delete":"edit",filePath:ze.params.filePath||ze.params.file_path||ze.params.path||ze.params.absolutePath||ze.params.notebook_path||"unknown",description:`Allow ${ze.toolName} operation`,oldContent:"edit_file"===ze.toolName?ze.params.oldContent:void 0,newContent:"edit_file"===ze.toolName?ze.params.newContent:void 0};return R.createElement(U,{flexDirection:"column",width:"100%"},R.createElement(nr,{staticKey:V,feed:X,showHeader:!0,expandedToolOutput:H}),R.createElement(U,{marginY:1},R.createElement(br,{request:e,onResponse:e=>{He(e);const t="no"!==e.value;ze.resolve(t),Ge(null),l(t?"File operation allowed":"File operation denied")}})))}}return A?R.createElement(kr,{onClose:()=>{P(!1),q(e=>e+1)}}):E?R.createElement(R.Fragment,null,R.createElement(xr,{staticKey:V}),R.createElement(U,{flexDirection:"column",width:"100%"},R.createElement(U,{marginBottom:1},R.createElement(L,{dimColor:!0},"Press Esc to return to conversation")),R.createElement(Tr,{onClose:()=>b(!1),onSettingsChange:Ue,staticKey:V}))):R.createElement(U,{flexDirection:"column",width:"100%"},R.createElement(nr,{staticKey:V,feed:X,showHeader:!0,expandedToolOutput:H}),R.createElement(RetryMessage,{attempt:d}),!v&&!S&&!T&&!y&&R.createElement(hr,{queuedMessages:re,isProcessing:te,executionState:Y,status:c,input:s,setInput:i,onSubmit:Ye,showFileList:h,setShowFileList:f,fileSearchQuery:Q,setFileSearchQuery:Z,onCommand:et,outputTokens:Ee,contextUsage:ve,tasteLearning:je,shareInfo:Ae,showShareNotification:$e,unshareNotificationMessage:Re,updateStatus:m,updateFailedInfo:o,currentProvider:$,showProviderInfo:_,isOAuthMode:D,autoAcceptMode:_e}),v&&R.createElement(U,{marginY:1},R.createElement(Ar,{onSelect:lt,onCancel:ut,currentProvider:$})),y&&R.createElement(U,{marginY:1},R.createElement(Lr,{onCancel:()=>w(!1)})),T&&R.createElement(U,{marginY:1},R.createElement(Pr,{onClose:()=>k(!1)})),S&&R.createElement(U,{marginY:1},R.createElement(S.Component,{onSuccess:mt,onCancel:gt})))},"InteractiveCLI"),zr=__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 Mn.isProjectInitialized()&&0===(await Mn.listSessions()).length&&(console.log("No conversations found to resume."),process.exit(0)),W(R.createElement(Wr,{resume:e.resume,continue:e.continue,trust:e.trust,updateStatus:t,updateFailedInfo:n}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})},"interactive"),{red:Gr,yellow:Vr}=te,qr=__name((e="ERROR: ",t,n=!0,r=!0)=>{if(t){if(console.log(),n?(console.log(`${ve.error} ${Gr(e)}`),console.log(`${ve.error} ${Gr("ERROR →")} ${t.name}`),console.log(`${ve.info} ${Gr("REASON →")} ${t.message}`),console.log(`${ve.info} ${Gr("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${ve.warning} ${Vr(e)}\n`),!r)return!1;process.exit(0)}},"handleError"),Hr=__name(()=>{process.on("unhandledRejection",e=>{qr(be`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(),t="win32"===process.platform,r=Le();if(!e){const e=er(),a=Xn();console.log(te.white(a)),console.log(te.dim(`${e} ${r?`env: (${r.replace("--","")})`:""}`)),console.log(""),console.log(`${o.warning} Authentication required to use Command Code.`),console.log("");const s=Ce.createInterface({input:process.stdin,output:process.stdout});try{const e=await s.question(`Would you like to sign in now? ${te.dim("(y/n)")}: `);s.close();const a=e.trim().toLowerCase();if(""!==a&&"y"!==a&&"yes"!==a)return console.log(""),console.log(`${o.info} You can authenticate later by running: ${t?"command-code":"cmd"} login`),!1;console.log(""),console.log(`${o.arrowUp} Running: ${t?"command-code":"cmd"} login`),console.log("");try{return n(`${t?"command-code":"cmd"} login ${r}`,{stdio:"inherit",cwd:process.cwd()}),await getAuthKey()?(console.log(""),console.log(`${o.tick} Authentication successful! Starting Command Code...`),console.log(""),!0):(console.log(""),console.log(`${o.cross} Authentication failed. Please try again with: ${t?"command-code":"cmd"} login`),!1)}catch(e){return console.log(""),console.log(`${o.cross} Login command failed. Please run: ${t?"command-code":"cmd"} login`),!1}}catch(e){return s.close(),console.log(""),console.log(`${o.info} Authentication cancelled. You can authenticate later with: ${t?"command-code":"cmd"} login`),!1}}return!0}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var Jr=__name(()=>{const e=[];for(const t of process.argv)"-v"===t?e.push("--version"):"-CRUD"===t?e.push("--crud"):"-CRU"===t?e.push("--cru"):"-C"===t?e.push("--create"):"-R"===t?e.push("--read"):"-U"===t?e.push("--update"):"-D"===t?e.push("--delete"):"-T"===t?e.push("--trust"):e.push(t);process.argv=e},"preprocessCustomFlags");async function updateProjectPermissions(e){const t=process.cwd(),n=f.join(t,".commandcode"),r=f.join(n,"settings.local.json");try{await A.mkdir(n,{recursive:!0});const t=await loadOrCreateSettings(r);updatePermissionsInSettings({settings:t,permissions:e}),await saveSettings({settingsPath:r,settings:t})}catch(e){throw new Error(`Failed to update project permissions: ${e instanceof Error?e.message:String(e)}`)}}async function loadOrCreateSettings(e){try{const t=parseJSON(await A.readFile(e,"utf-8"))||{permissions:{allow:[],deny:[],autoApprove:{}}};return t.permissions||(t.permissions={allow:[],deny:[]}),t.permissions.autoApprove||(t.permissions.autoApprove={}),t}catch{return{permissions:{allow:[],deny:[],autoApprove:{}}}}}function updatePermissionsInSettings(e){const{settings:t,permissions:n}=e;void 0!==n.create&&(t.permissions.autoApprove.create=n.create),void 0!==n.read&&(t.permissions.autoApprove.read=n.read),void 0!==n.update&&(t.permissions.autoApprove.update=n.update),void 0!==n.delete&&(t.permissions.autoApprove.delete=n.delete)}async function saveSettings(e){const{settingsPath:t,settings:n}=e;await A.writeFile(t,JSON.stringify(n,null,2),"utf-8")}async function handleCrudFlags(e){if(!(e.crud||e.cru||e.create||e.read||e.update||e.delete))return;await Mn.initializeProject();const t={};e.crud&&(t.create=!0,t.read=!0,t.update=!0,t.delete=!0),e.cru&&(t.create=!0,t.read=!0,t.update=!0,t.delete=!1),e.create&&(t.create=!0),e.read&&(t.read=!0),e.update&&(t.update=!0),e.delete&&(t.delete=!0),await updateProjectPermissions(t)}async function migrateUserDirectory(){const e=k.homedir(),t=y.join(e,".command-code"),n=y.join(e,".commandcode");if(!J.existsSync(t))return{success:!0,message:"User directory migration not needed (old directory does not exist)",skipped:!0};if(J.existsSync(n))return console.warn("Both ~/.command-code and ~/.commandcode exist. Manual intervention required."),console.warn("Please manually merge or remove ~/.command-code/"),{success:!1,message:"Both old and new directories exist. Manual intervention required."};try{J.renameSync(t,n);const e=y.join(n,"config.json");if(J.existsSync(e)){const t=J.readFileSync(e,"utf-8"),n=JSON.parse(t);delete n.tasteUsage,J.writeFileSync(e,JSON.stringify(n,null,2))}return{success:!0,message:"User directory migrated successfully"}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("User directory migration failed:",t),console.error("Please manually rename ~/.command-code to ~/.commandcode"),{success:!1,message:`User directory migration failed: ${t}`}}}async function migrateProjectDirectory(e){const{projectRoot:t}=e,n=y.join(t,".command-code"),r=y.join(t,".commandcode");if(!J.existsSync(n))return{success:!0,message:"Project directory migration not needed (old directory does not exist)",skipped:!0};if(J.existsSync(r))return console.warn(`Both .command-code and .commandcode exist in ${t}`),console.warn("Manual intervention required. Please manually merge or remove .command-code/"),{success:!1,message:"Both old and new directories exist. Manual intervention required."};try{return J.renameSync(n,r),{success:!0,message:"Project directory migrated successfully"}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("Project directory migration failed:",t),console.error("Please manually rename .command-code to .commandcode"),{success:!1,message:`Project directory migration failed: ${t}`}}}async function migrateDirectories(e){const{projectRoot:t}=e,n=await migrateUserDirectory(),r=await migrateProjectDirectory({projectRoot:t}),o=n.skipped,a=r.skipped;return o&&a||n.success&&r.success||console.warn("\n⚠️ Some migrations failed. See messages above."),{userResult:n,projectResult:r}}__name(updateProjectPermissions,"updateProjectPermissions"),__name(loadOrCreateSettings,"loadOrCreateSettings"),__name(function createDefaultPermissionsStructure(){return{allow:[],deny:[]}},"createDefaultPermissionsStructure"),__name(updatePermissionsInSettings,"updatePermissionsInSettings"),__name(saveSettings,"saveSettings"),__name(handleCrudFlags,"handleCrudFlags"),__name(migrateUserDirectory,"migrateUserDirectory"),__name(migrateProjectDirectory,"migrateProjectDirectory"),__name(migrateDirectories,"migrateDirectories");var Kr=getPackageJson(),Yr=process.cwd();global.COMMAND_CODE_CWD=Yr;var Qr=new ke("CommandCode");Hr();var Zr=__name(()=>{const e=process.argv.slice(2);return!e.includes("--skip-update-check")&&0===e.length},"shouldAutoUpdate");(async()=>{if(Jr(),await migrateDirectories({projectRoot:Yr}),Zr()&&(process.env.NODE_NO_WARNINGS="1",(await performAutoUpdate({onProgress:__name(e=>{process.stdout.write("\r"+e)},"onProgress")})).success)){process.stdout.write("\r");const e=process.argv[1]?.includes("command-code")?"command-code":"cmd",t=r(e,["--skip-update-check"],{stdio:"inherit",detached:!1,shell:!0,env:{...process.env,NODE_NO_WARNINGS:"1"}});await new Promise(()=>{t.on("exit",e=>{process.exit(e||0)})})}const n=new e;async function commanderAction(e){await checkAuthAndPromptLogin()||process.exit(1),await handleCrudFlags({crud:e.crud,cru:e.cru,create:e.create,read:e.read,update:e.update,delete:e.delete});const t={};switch(e.trust&&(t.trust=!0),!0){case e.resume:zr({resume:!0,...t});break;case e.continue:zr({continue:!0,...t});break;default:zr(t)}}__name(commanderAction,"commanderAction"),n.name(Kr.name).description(Kr.description||"Command Code — Coding Agent with taste by Langbase").version(Kr.version,"-v, --version","output the version number").option("-r, --resume","Resume a conversation").option("-c, --continue","Continue the last conversation").option("-T, --trust","Auto-trust project (skip initial permission prompt)").option("--crud","Enable all CRUD permissions (shortcut: -CRUD)").option("--cru","Enable Create, Read, Update (no Delete) (shortcut: -CRU)").option("--create","Enable Create permission (shortcut: -C)").option("--read","Enable Read permission (shortcut: -R)").option("--update","Enable Update permission (shortcut: -U)").option("--delete","Enable Delete permission (shortcut: -D)").addOption(new t(Ae).hideHelp()).addOption(new t(Pe).hideHelp()).action(commanderAction).allowUnknownOption().allowExcessArguments(),n.addCommand(Xe),n.addCommand(Qe),n.addCommand(ut),n.addCommand(Ct),n.addCommand(createTasteCommand()),n.addCommand(qe),n.addCommand(He),n.addCommand(Je),n.hook("preAction",()=>{Qr.debug("Command starting...")}),n.hook("postAction",()=>{Qr.debug("Command completed.")}),n.parse()})();