command-code 0.10.16 → 0.10.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import*as e from"path";import t,{relative as n,dirname as r,join as o,isAbsolute as s,resolve as a,basename as i}from"path";import{fileURLToPath as c,pathToFileURL as l}from"url";import d,{z as u}from"zod";import*as m from"os";import g,{tmpdir as p}from"os";import*as h from"fs";import f,{existsSync as y,readFileSync as E,promises as w,constants as b,readdirSync as S,statSync as k,createReadStream as C}from"fs";import{execSync as v,exec as T,spawn as A}from"child_process";import*as P from"fs/promises";import x,{mkdir as I,writeFile as R,readFile as $,unlink as D}from"fs/promises";import*as N from"crypto";import F,{randomUUID as L}from"crypto";import O,{useState as _,useRef as M,useEffect as U,useCallback as j,useMemo as B}from"react";import{Box as W,Text as H,Static as z,render as G,useStdout as q,useInput as V,useApp as K}from"ink";import J from"chalk";import Y from"strip-ansi";import Q from"picocolors";import Z from"sharp";import X from"open";import ee from"@opentelemetry/sdk-node";import te from"@opentelemetry/exporter-trace-otlp-http";import ne from"@opentelemetry/resources";import re from"@opentelemetry/semantic-conventions";import oe from"@opentelemetry/sdk-trace-node";import{trace as se,SpanStatusCode as ae,context as ie}from"@opentelemetry/api";import{v4 as ce}from"uuid";import*as le from"net";import de from"net";import{promisify as ue}from"util";import"dotenv/config";import me from"dedent";import ge from"log-symbols";import pe,{mainSymbols as he}from"figures";import fe from"readline/promises";import{Command as ye,Option as Ee}from"commander";import*as we from"@clack/prompts";import{cancel as be,select as Se,isCancel as ke,note as Ce,confirm as ve,password as Te}from"@clack/prompts";import Ae from"ink-spinner";import*as Pe from"http";import xe from"ora";import Ie from"@crosscopy/clipboard";import Re from"gray-matter";import{minimatch as $e}from"minimatch";import{glob as De}from"glob";import{quote as Ne}from"shell-quote";import{MessageStream as Fe}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import Le from"@sindresorhus/slugify";import{EventEmitter as Oe}from"events";import _e from"strip-json-comments";import*as Me from"readline";import Ue from"ink-select-input";import je from"ignore";import Be from"ink-gradient";import{Marked as We}from"marked";import He from"marked-terminal";import*as ze from"diff";import Ge from"semver";import qe from"open-editor";import Ve from"ink-text-input";import*as Ke from"process";var Je,Ye,Qe,Ze,Xe,et,tt,nt,rt,ot,st,at,it,ct,lt,dt,ut,mt,gt,pt,ht,ft,yt=Object.defineProperty,Et=Object.getOwnPropertyNames,__name=(e,t)=>yt(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[Et(e)[0]])(e=0)),t},wt=__esm({"../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/esm_shims.js"(){}}),bt=__esm({"src/utils/telemetry/constants.ts"(){wt(),Je="https://api.axiom.co/v1/traces",Ye="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",Qe="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",Ze="xaat-add69148-8f73-4833-921d-bc843285c95f",Xe="command-code-cli",et="command_code_cli_tracing",tt=["apikey","api_key","api-key","token","secret","authorization","auth","password","passwd","credential","auth_key","authkey","access_token","access-token","refresh_token","refresh-token","client_secret","clientsecret","private_key","privatekey","bearer","key"],nt=["content","body"],rt=200,ot=1e3}});function getStudioAuthUrl(e){return"local"===e?"http://localhost:3000/settings/api":"staging"===e?"https://staging.commandcode.ai/settings/api":"https://commandcode.ai/settings/api"}var St,kt,Ct=__esm({"../shared/src/constants.ts"(){wt(),at="--xco",it={INTERNAL_TEAM_FLAG_HEADER:`x-${(st="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage"},ct={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"},DEVREL_THREAD:{CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",DATA:"/alpha/devrel-thread/data",UPDATE:"/alpha/devrel-thread/update"},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",DELETE:"/beta/taste/packages/:namespace/:packageName"}}},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"},PROFILE:{GET:"/internal/profile/:login",PACKAGES:"/internal/profile/:login/packages",PACKAGE_GET:"/internal/profile/:login/packages/:packageName",PACKAGE_DOWNLOAD:"/internal/profile/:login/packages/:packageName/download",FOLLOWERS:"/internal/profile/:login/followers",FOLLOWING:"/internal/profile/:login/following"},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"},FOLLOW:"/internal/orgs/:orgId/follow",FOLLOWERS:"/internal/orgs/:orgId/followers"},USER:{SETTINGS:"/internal/user/settings",AVATAR:"/internal/user/avatar",FOLLOW:"/internal/users/:userId/follow",FOLLOWERS:"/internal/users/:userId/followers",FOLLOWING:"/internal/users/:userId/following"},USAGE:{LIST:"/internal/usage",SUMMARY:"/internal/usage/summary"},TASTE:{PACKAGES:{LIST:"/internal/taste/packages",BATCH:"/internal/taste/packages",GET:"/internal/taste/packages/:namespace/:packageName",FILES:"/internal/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/internal/taste/packages/:namespace/:packageName/download",DELETE:"/internal/taste/packages/:namespace/:packageName",UPDATE:"/internal/taste/packages/:namespace/:packageName/update",STAR:"/internal/taste/packages/:namespace/:packageName/star",PIN:"/internal/taste/packages/:namespace/:packageName/pin"}}}},lt={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")},PACKAGES:{FILES:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+/download")}},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_-]+"),FOLLOW:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/followers")},USER:{FOLLOW:new RegExp("/internal/users/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/users/[a-zA-Z0-9-]+/followers"),FOLLOWING:new RegExp("/internal/users/[a-zA-Z0-9-]+/following")},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"),UPDATE:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/update"),STAR:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/star"),PIN:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/pin")}}}},Object.values(lt.ALPHA.TASTE),Object.values(lt.BETA.TASTE_PACKAGES),ct.ALPHA.GENERATE,ct.ALPHA.AGENT.GENERATE,ct.ALPHA.WHOAMI,ct.ALPHA.NAMESPACES,ct.ALPHA.SHARE.CREATE,ct.ALPHA.SHARE.DELETE,ct.ALPHA.SHARE.APPEND,ct.ALPHA.DEVREL_THREAD.CREATE,ct.ALPHA.DEVREL_THREAD.DELETE,ct.ALPHA.DEVREL_THREAD.UPDATE,ct.ALPHA.TASTE.LEARN,ct.ALPHA.TASTE.DELETE,ct.ALPHA.TASTE.GET,ct.ALPHA.TASTE.UPDATE,Object.values(ct.BETA.TASTE.PACKAGES),ct.INTERNAL.ADMIN.USERS,ct.INTERNAL.ADMIN.ORGS,ct.INTERNAL.ADMIN.ENTITY_TYPE,ct.INTERNAL.USER.AVATAR,ct.INTERNAL.USER.SETTINGS,ct.INTERNAL.API_KEYS.LIST,ct.INTERNAL.API_KEYS.CREATE,ct.INTERNAL.API_KEYS.DELETE,ct.INTERNAL.USAGE.LIST,ct.INTERNAL.USAGE.SUMMARY,ct.INTERNAL.ADMIN.GRANT_CREDITS,ct.INTERNAL.ADMIN.GRANT_ORG_CREDITS,ct.INTERNAL.BILLING.CREDITS.GET,ct.INTERNAL.BILLING.CUSTOMERS.GET,ct.INTERNAL.BILLING.CUSTOMERS.UPSERT,ct.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,ct.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,ct.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,ct.INTERNAL.BILLING.CUSTOMERS.INVOICES,ct.INTERNAL.BILLING.SUBSCRIPTIONS.GET,ct.INTERNAL.ORGS.LIST,ct.INTERNAL.ORGS.GET,ct.INTERNAL.ORGS.CREATE,ct.INTERNAL.ORGS.UPDATE,ct.INTERNAL.ORGS.DELETE,ct.INTERNAL.ORGS.MEMBERS.LIST,ct.INTERNAL.ORGS.MEMBERS.ADD,ct.INTERNAL.ORGS.MEMBERS.UPDATE,ct.INTERNAL.ORGS.MEMBERS.REMOVE,ct.INTERNAL.ORGS.INVITATIONS.LIST,ct.INTERNAL.ORGS.INVITATIONS.SEND,ct.INTERNAL.ORGS.INVITATIONS.ACCEPT,ct.INTERNAL.ORGS.INVITATIONS.CANCEL,ct.INTERNAL.TASTE.PACKAGES.LIST,Object.values(lt.INTERNAL.ORGS),Object.values(lt.INTERNAL.USER),Object.values(lt.INTERNAL.TASTE.PACKAGES),dt={INTERNAL:{PROFILE:{GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+"),PACKAGES:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages"),FOLLOWING:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/following"),FOLLOWERS:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/followers"),PACKAGE_GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+"),PACKAGE_DOWNLOAD:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+/download")}}},Object.values(dt.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl"),ut={ANTHROPIC:"anthropic"},d.enum(["owner","admin","member"]),mt={LEARN_TASTE:"learn-taste",TASTE:"taste",TERMINAL_SETUP:"terminal-setup"},(gt={SONNET_4_5:{id:"claude-sonnet-4-5-20250929",label:"Default",name:"Sonnet 4.5",description:"recommended"},OPUS_4_5:{id:"claude-opus-4-5-20251101",label:"Opus 4.5",name:"Opus 4.5",description:""},OPUS_4_6:{id:"claude-opus-4-6",label:"Opus 4.6",name:"Opus 4.6",description:""}}).SONNET_4_5.id,gt.OPUS_4_5.id,gt.OPUS_4_6.id,pt=gt.SONNET_4_5.id,new Set([].map(e=>e.toLowerCase())),ht=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],ft={TIER_1_THRESHOLD:.5,TIER_2_THRESHOLD:.8,TIER_3_THRESHOLD:.9,TIER_1_KEEP_COUNT:20,TIER_2_KEEP_COUNT:10,KEEP_RECENT_TOKENS:3e4}}}),vt=__esm({"src/utils/env.ts"(){wt(),St=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),kt=__name(()=>{const e=St();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag")}});function getAuthDir(){return t.join(g.homedir(),".commandcode")}function getAuthFile(e){const n=e??St(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??St(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var Tt=__esm({"src/utils/auth/auth-paths.ts"(){wt(),Ct(),vt(),__name(getAuthDir,"getAuthDir"),__name(getAuthFile,"getAuthFile"),__name(getConfigFile,"getConfigFile")}});function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${g.platform()}-${g.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return f.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 v("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return v("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){try{const e=v("git branch -r",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]});return e.includes("origin/main")?"main":e.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=v("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),n=t.filter(e=>e.startsWith(" M")).length,r=t.filter(e=>e.startsWith("A ")).length,o=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,a=[];return n>0&&a.push(`M ${n}`),r>0&&a.push(`A ${r}`),o>0&&a.push(`D ${o}`),s>0&&a.push(`?? ${s}`),a.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=v("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).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("ghostty"===t)return{name:"Ghostty",type:"ghostty",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}var At,Pt,xt,It,Rt,$t,Dt=__esm({"src/utils/environment.ts"(){wt(),__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")}}),Nt=__esm({"src/auth/index.ts"(){wt(),Ct(),vt(),(e=>{e.OAuth=u.object({type:u.literal("oauth"),refresh:u.string(),access:u.string(),expires:u.number()}),e.ApiKey=u.object({type:u.literal("api"),key:u.string()}),e.Info=u.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const n=__name(()=>t.join(g.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=St(),r="local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json";return t.join(n(),r)},"getAuthFile");async function get(e){try{const t=await x.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await x.mkdir(o,{recursive:!0});let a={};try{const e=await x.readFile(s,"utf-8");a=JSON.parse(e)}catch{}a[e]=t,await x.writeFile(s,JSON.stringify(a,null,2)),await x.chmod(s,384)}async function remove(e){const t=r();try{const n=await x.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await x.unlink(t):(await x.writeFile(t,JSON.stringify(r,null,2)),await x.chmod(t,384))}catch{}}async function list2(){try{const e=await x.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")})(At||(At={}))}}),Ft=__esm({"src/utils/constants.ts"(){wt(),Ct(),Pt="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing",xt='OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.',It=">"}}),Lt=__esm({"src/auth/anthropic.ts"(){wt(),Nt(),Ft(),rr(),(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 F.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return F.createHash("sha256").update(e).digest("base64url")}function generateState(){return F.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),o=generateState();return{url:`https://claude.ai/oauth/authorize?${new URLSearchParams({code:"true",client_id:t,response_type:"code",redirect_uri:r,scope:"org:create_api_key user:profile user:inference",code_challenge:n,code_challenge_method:"S256",state:o}).toString()}`,verifier:e,state:o}}async function exchangeCodeForTokens(e,o,s){const a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:s})});if(!a.ok){const e=await a.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:_n.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const i=await a.json();await At.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 At.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 trackError({error:sanitizeErrorForTelemetry({error:new Error("OAuth token refresh failed"),label:"token_refresh_failed"}),context:{component:_n.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await At.remove("anthropic");const o=await r.json();return await At.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 trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:_n.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await At.remove("anthropic")}}}async function getValidAccessToken(){const e=await At.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")})(Rt||(Rt={}))}});function isWordBoundary(e){return!e||0===e.length||$t.test(e)}function findPreviousWordBoundary(e,t){if(!e||t<=0)return 0;let n=Math.min(t,e.length);for(;n>0&&isWordBoundary(e[n-1]||"");)n--;for(;n>0&&!isWordBoundary(e[n-1]||"");)n--;return n}function findNextWordBoundary(e,t){if(!e)return 0;if(t>=e.length)return e.length;let n=Math.max(0,t);for(;n<e.length&&isWordBoundary(e[n]||"");)n++;for(;n<e.length&&!isWordBoundary(e[n]||"");)n++;return n}function deleteWordBackwards(e,t){if(!e||t<=0)return{text:e||"",cursor:0};const n=findPreviousWordBoundary(e,t);return{text:e.slice(0,n)+e.slice(t),cursor:n}}function clampCursor(e,t){return Math.max(0,Math.min(e,t))}function findLineStart(e,t){if(!e||t<=0)return 0;for(let n=Math.min(t,e.length)-1;n>=0;n--)if("\n"===e[n])return n+1;return 0}function findLineEnd(e,t){if(!e)return 0;if(t>=e.length)return e.length;for(let n=Math.max(0,t);n<e.length;n++)if("\n"===e[n])return n;return e.length}function moveCursorUp(e,t){if(!e)return 0;const n=findLineStart(e,t);if(0===n)return t;const r=t-n,o=n-1,s=findLineStart(e,o),a=o-s;return s+Math.min(r,a)}function moveCursorDown(e,t){if(!e)return 0;const n=findLineStart(e,t),r=findLineEnd(e,t);if(r===e.length)return t;const o=t-n,s=r+1,a=findLineEnd(e,s)-s;return s+Math.min(o,a)}function insertTextAt(e,t,n){const r=e||"",o=clampCursor(t,r.length);return{text:r.slice(0,o)+n+r.slice(o),cursor:o+n.length}}function deleteCharBefore(e,t){return!e||t<=0?{text:e||"",cursor:0}:{text:e.slice(0,t-1)+e.slice(t),cursor:t-1}}function deleteCharAt(e,t){return!e||t>=e.length?{text:e||"",cursor:t}:{text:e.slice(0,t)+e.slice(t+1),cursor:t}}var Ot,_t,Mt,Ut,jt,Bt,Wt,Ht,zt,Gt,qt,Vt=__esm({"src/utils/text-navigation.ts"(){wt(),$t=/\s|[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/,__name(isWordBoundary,"isWordBoundary"),__name(findPreviousWordBoundary,"findPreviousWordBoundary"),__name(findNextWordBoundary,"findNextWordBoundary"),__name(deleteWordBackwards,"deleteWordBackwards"),__name(clampCursor,"clampCursor"),__name(findLineStart,"findLineStart"),__name(findLineEnd,"findLineEnd"),__name(moveCursorUp,"moveCursorUp"),__name(moveCursorDown,"moveCursorDown"),__name(insertTextAt,"insertTextAt"),__name(deleteCharBefore,"deleteCharBefore"),__name(deleteCharAt,"deleteCharAt")}});function isWordLeftSequence(e){return!!Ot.has(e)||!!Gt.test(e)}function isWordRightSequence(e){return!!_t.has(e)||!!qt.test(e)}function isHomeSequence(e){return Mt.has(e)}function isEndSequence(e){return Ut.has(e)}function isForwardDeleteSequence(e){return jt.has(e)}function isDeleteWordSequence(e){return Bt.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===Wt.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===Wt.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===Wt.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===Wt.CTRL_U}function isAltP(e){return zt.has(e)}function isCtrlKey({inputChar:e,key:t,letter:n,ctrlCode:r}){return!(!t.ctrl||e.toLowerCase()!==n.toLowerCase())||void 0!==r&&e.charCodeAt(0)===r}var Kt=__esm({"src/utils/keyboard-sequences.ts"(){wt(),Ot=new Set(["","b","","",""]),_t=new Set(["","f","","",""]),Mt=new Set(["","[1~","[7~","OH"]),Ut=new Set(["","[4~","[8~","OF"]),jt=new Set(["[3~"]),Bt=new Set(["",""]),Wt={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},Ht={ALT_P:112,ALT_P_NO_META:960},zt=new Set([String.fromCharCode(27,Ht.ALT_P),String.fromCharCode(Ht.ALT_P_NO_META),""]),Gt=/^\x1b\[1;[359]D$/,qt=/^\x1b\[1;[359]C$/,__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(isAltP,"isAltP"),__name(isCtrlKey,"isCtrlKey")}});function processWordLeft(e,t){return{value:e,cursor:findPreviousWordBoundary(e,t),handled:!0}}function processWordRight(e,t){return{value:e,cursor:findNextWordBoundary(e,t),handled:!0}}function processLineStart(e,t){return{value:e,cursor:findLineStart(e,t),handled:!0}}function processLineEnd(e,t){return{value:e,cursor:findLineEnd(e,t),handled:!0}}function processDeleteWord(e,t){const n=deleteWordBackwards(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processDeleteToEnd(e,t){const n=findLineEnd(e,t);return{value:e.slice(0,t)+e.slice(n),cursor:t,handled:!0}}function processDeleteToStart(e,t){const n=findLineStart(e,t);return{value:e.slice(0,n)+e.slice(t),cursor:n,handled:!0}}function processForwardDelete(e,t){const n=deleteCharAt(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processBackspace(e,t){const n=deleteCharBefore(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processCursorLeft(e,t,n){return n?t<=0?{value:e,cursor:t,handled:!0}:{value:e,cursor:t-1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorRight(e,t,n){return n?t>=e.length?{value:e,cursor:t,handled:!0}:{value:e,cursor:t+1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorUp(e,t,n){return n?{value:e,cursor:moveCursorUp(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorDown(e,t,n){return n?{value:e,cursor:moveCursorDown(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCharacterInput(e,t,n){const r=n.replace(/[\x00-\x1F\x7F]|\x1b.*/g,"");if(0===r.length)return{value:e,cursor:t,handled:!1};const o=insertTextAt(e,t,r);return{value:o.text,cursor:o.cursor,handled:!0}}function processRawInput(e,t,n){return isWordLeftSequence(e)?processWordLeft(t,n):isWordRightSequence(e)?processWordRight(t,n):isHomeSequence(e)?processLineStart(t,n):isEndSequence(e)?processLineEnd(t,n):isCtrlA(e)?processLineStart(t,n):isCtrlE(e)?processLineEnd(t,n):isDeleteWordSequence(e)?processDeleteWord(t,n):isCtrlK(e)?processDeleteToEnd(t,n):isCtrlU(e)?processDeleteToStart(t,n):isForwardDeleteSequence(e)?processForwardDelete(t,n):{value:t,cursor:n,handled:!1}}function isIgnoredKey(e,t){return!(!t.ctrl||"c"!==e)||!!t.tab||!(!t.shift||!t.tab)}function processInkInput(e,t,n,r,o){const s=t;return s.meta&&t.leftArrow?processLineStart(n,r):s.meta&&t.rightArrow?processLineEnd(n,r):s.meta&&"b"===e?processWordLeft(n,r):s.meta&&"f"===e?processWordRight(n,r):t.ctrl&&"a"===e?processLineStart(n,r):t.ctrl&&"e"===e?processLineEnd(n,r):t.ctrl&&"w"===e?processDeleteWord(n,r):t.ctrl&&"k"===e?processDeleteToEnd(n,r):t.ctrl&&"u"===e?processDeleteToStart(n,r):t.leftArrow?processCursorLeft(n,r,o):t.rightArrow?processCursorRight(n,r,o):t.upArrow?processCursorUp(n,r,o):t.downArrow?processCursorDown(n,r,o):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!s.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}var Jt,Yt,Qt,Zt=__esm({"src/components/text/input-handlers.ts"(){wt(),Vt(),Kt(),__name(processWordLeft,"processWordLeft"),__name(processWordRight,"processWordRight"),__name(processLineStart,"processLineStart"),__name(processLineEnd,"processLineEnd"),__name(processDeleteWord,"processDeleteWord"),__name(processDeleteToEnd,"processDeleteToEnd"),__name(processDeleteToStart,"processDeleteToStart"),__name(processForwardDelete,"processForwardDelete"),__name(processBackspace,"processBackspace"),__name(processCursorLeft,"processCursorLeft"),__name(processCursorRight,"processCursorRight"),__name(processCursorUp,"processCursorUp"),__name(processCursorDown,"processCursorDown"),__name(processCharacterInput,"processCharacterInput"),__name(processRawInput,"processRawInput"),__name(isIgnoredKey,"isIgnoredKey"),__name(processInkInput,"processInkInput")}});function startEarlyInputCapture(){Jt||(Jt=!0,Yt=[],Qt=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&Yt.push(t)},"earlyInputHandler"),process.stdin.on("data",Qt))}function stopEarlyInputCapture(){Jt&&Qt&&(process.stdin.off("data",Qt),Qt=null,Jt=!1)}function consumeBufferedInput(){const e=Yt.join("");return Yt=[],e}function hasBufferedInput(){return Yt.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("")||e.startsWith(""))}var Xt=__esm({"src/utils/early-input-buffer.ts"(){wt(),Jt=!1,Yt=[],Qt=null,__name(startEarlyInputCapture,"startEarlyInputCapture"),__name(stopEarlyInputCapture,"stopEarlyInputCapture"),__name(consumeBufferedInput,"consumeBufferedInput"),__name(hasBufferedInput,"hasBufferedInput"),__name(isControlSequenceToSkip,"isControlSequenceToSkip")}});function useCursorState({value:e,focus:t,showCursor:n}){const[r,o]=_((e||"").length),s=M(r),a=M(e);U(()=>{s.current=r},[r]),U(()=>{const i=a.current;if(a.current=e,e===i)return;if(!t)return;if(!n)return;const c=(e||"").length,l=(i||"").length;(Math.abs(c-l)>1||r>c)&&(o(c),s.current=c)},[e,t,n,r]);const i=j(e=>{o(e),s.current=e},[]);return{cursor:r,setCursor:i,cursorRef:s}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o}){const s=M(!1);U(()=>{if(!e)return;const a=process.stdin,i=__name(e=>{const s=processRawInput(e.toString(),t.current,n.current);if(!s.handled)return;o(!0);const a=clampCursor(s.cursor,s.value.length);r(s.value,a),setTimeout(()=>o(!1),0)},"handleRawInput");if(a.on("data",i),!s.current&&hasBufferedInput()){s.current=!0;const e=consumeBufferedInput();e&&i(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",i)}},[e,t,n,r,o])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){V((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void a?.(n.current);const c=processInkInput(e,i,n.current,r.current,t);if(!c.handled)return;const l=clampCursor(c.cursor,c.value.length);s(c.value,l)},{isActive:e})}function useSyncedRef(e){const t=M(e);return U(()=>{t.current=e},[e]),t}var en=__esm({"src/components/text/hooks.ts"(){wt(),Vt(),Zt(),Xt(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef")}});function renderPlaceholder(e,t){return t?0===e.length?J.inverse(" "):J.inverse(e[0])+J.grey(e.slice(1)):J.grey(e)}function renderValue(e,t,n){if(!n)return e;if(0===e.length)return J.inverse(" ");let r="";for(let n=0;n<e.length;n++)n===t?"\n"===e[n]?r+=J.inverse(" ")+"\n":r+=J.inverse(e[n]):r+=e[n];return t===e.length&&(r+=J.inverse(" ")),r}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(Y(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",c=0,l=!0;for(const e of a){const t=Y(e).length;c+t>(l?s:o)&&c>0&&(i+="\n"+r,c=n,l=!1),i+=e,c+=t}return i}function getDisplayValue(e,t,n,r,o){const s=r&&o;return t&&0===e.length?renderPlaceholder(t,s):renderValue(e,n,s)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}var tn=__esm({"src/components/text/render-utils.ts"(){wt(),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue")}});function createStdinUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n.current(r),t.current=r)}}function createInkUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n(r),t.current=r)}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:a,onCursorChange:i,prefix:c="",prefixColor:l}){const d=M(!1),u=useSyncedRef(e),m=useSyncedRef(s),{cursor:g,setCursor:p,cursorRef:h}=useCursorState({value:e,focus:n,showCursor:o});O.useEffect(()=>{i?.(g)},[g,i]);const f=j(createStdinUpdateHandler(p,u,m),[p,u,m]),y=j(()=>createInkUpdateHandler(p,u,s),[p,u,s])(),E=j(e=>{d.current=e},[]),w=j(()=>d.current,[]);useRawStdinHandler({focus:n,valueRef:u,cursorRef:h,onUpdate:f,setHandled:E}),useInkInputHandler({focus:n,showCursor:o,valueRef:u,cursorRef:h,isHandledByStdin:w,onUpdate:y,onSubmit:a});const{stdout:b}=q(),S=b?.columns??80,k=getMaskedValue(e,r),C=wrapWithIndent(__name(()=>{if(!c)return"";if(!l)return c;const e={white:Q.white,green:Q.green,red:Q.red,blue:Q.blue,yellow:Q.yellow,cyan:Q.cyan,magenta:Q.magenta,gray:Q.gray,grey:Q.gray}[l];return e?e(c):c},"getColoredPrefix")()+getDisplayValue(k,t,g,o,n),S,c?.length??0);return O.createElement(H,{wrap:"wrap"},C)}var nn=__esm({"src/components/text/text-input.tsx"(){wt(),en(),tn(),Vt(),__name(createStdinUpdateHandler,"createStdinUpdateHandler"),__name(createInkUpdateHandler,"createInkUpdateHandler"),__name(TextInput,"TextInput")}});async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=Z(n),s=await o.metadata();if(!s.width||!s.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const a=1200;let i,c,{width:l,height:d}=s;(l>a||d>a)&&(l>d?(d=Math.round(d*a/l),l=a):(l=Math.round(l*a/d),d=a)),t.includes("png")&&s.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}}var rn=__esm({"src/utils/image-compression.ts"(){wt(),__name(compressImageForSharing,"compressImageForSharing")}});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}}var on=__esm({"src/utils/clipboard-image.ts"(){wt(),rn(),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText")}});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,o,s=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");if(s=s.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){r=e.slice(0,t.index);const s=e.slice(t.index+t[0].length);if(n){const e=s.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(o=s.slice(0,e.index))}else o=s}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:s,textBeforePaste:r,pastedContent:o}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}var sn,an,cn,ln,dn=__esm({"src/utils/bracketed-paste.ts"(){wt(),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode")}});function getIcon(e){if(cn[e])return cn[e];const t=e.split(":")[0];return cn[t]?cn[t]:cn.default}function formatTime(e){return`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}`}function parseMessage(e){const t=e.match(/^\[([^\]]+)\]\s*(.*)/);return t?{category:t[1],text:t[2]}:{category:"",text:e}}function showStartup(){if(!ln){ln=!0;try{h.mkdirSync(sn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${an}\n════════════════════════════════════════════════════════════════\n\n`;h.appendFileSync(an,t,"utf-8")}catch{}}}function dlog(e,t){if("true"===process.env.DEBUG){showStartup();try{const n=formatTime(new Date),{category:r,text:o}=parseMessage(e);let s;if(r){s=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${o}`}else s=`${n} ${cn.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",h.appendFileSync(an,s,"utf-8")}catch{}}}function dlogSection(e){if("true"===process.env.DEBUG){showStartup();try{const t=`\n──── ${e} ${"─".repeat(Math.max(0,50-e.length))}\n`;h.appendFileSync(an,t,"utf-8")}catch{}}}var un,mn=__esm({"src/utils/dlog.ts"(){wt(),sn=e.join(m.homedir(),".commandcode","logs"),an=e.join(sn,"command.log"),cn={Startup:">",CLI:"$",Config:"#",Auth:"@",Onboarding:"*",LearningAgent:"&",Import:"<",API:"~",Sessions:"+",Observer:"!",Flow:"^",Handler:">",Helper:"-",Codex:"+",UI:"|",Hook:"%",ObserverAPI:"~",ContextEngine:"~",Updater:"^",default:"-"},__name(getIcon,"getIcon"),__name(formatTime,"formatTime"),__name(parseMessage,"parseMessage"),ln=!1,__name(showStartup,"showStartup"),"true"===process.env.DEBUG&&showStartup(),__name(dlog,"dlog"),__name(dlogSection,"dlogSection")}});async function loadUserConfig(){try{const e=getConfigFile();return parseJSON(await P.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();h.writeFileSync(t,JSON.stringify(e,null,2)),h.chmodSync(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t=await loadUserConfig(),n=getConfiguredModel(),r={...t,...e,model:e.model??n};await saveUserConfig(r)}async function isTasteLearningEnabled(){return(await loadUserConfig()).tasteLearning??!0}async function setTasteLearning(e){const{tasteLearning:t}=e;await updateUserConfig({tasteLearning:t})}async function isOAuthEnforced(){if(null!==un)return un;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),un=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),un=!0,!0;const e=await loadUserConfig();return(un=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),un}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error(xt)}function getConfiguredModel(){try{const e=getConfigFile();return(parseJSON(h.readFileSync(e,"utf-8"))||{}).model??pt}catch{return pt}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}var gn,pn,hn=__esm({"src/utils/user-config.ts"(){wt(),Ct(),Tt(),Ft(),mn(),yn(),En(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),un=null,__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel")}}),fn=__esm({"src/components/anthropic-auth.tsx"(){wt(),nn(),Lt(),Ft(),on(),dn(),hn(),gn=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=_(""),[s,a]=_(null),[i,c]=_(!1),[l,d]=_(null),[u,m]=_(!0),[g,p]=_(!1),[h,f]=_(!1);U(()=>{const{url:e,verifier:t,state:n}=Rt.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=j(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||h){if(!h||t.isPasteEnd){if(h&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}o(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}},[h]);V((e,n)=>{if(n.escape&&t(),u&&!g)if("y"!==e&&"Y"!==e)"n"!==e&&"N"!==e||t();else{if(!s)return;X(s.url).then(()=>{p(!0),m(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),p(!0),m(!1)})}});const E=__name(async()=>{if(r.trim()&&s&&!i){c(!0),d(null);try{const t=r.split("#")[0].trim();await Rt.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),c(!1),n&&n(t)}}},"handleSubmit");return u&&!g?O.createElement(W,{flexDirection:"column"},O.createElement(W,{marginBottom:1},O.createElement(H,{bold:!0,color:"cyan"},"Anthropic Authentication")),O.createElement(W,{marginBottom:1},O.createElement(H,null,"Open the Anthropic auth page?",O.createElement(H,{dimColor:!0}," (Y/n)")))):O.createElement(W,{flexDirection:"column"},O.createElement(W,{marginBottom:1},O.createElement(H,{bold:!0,color:"cyan"},"Anthropic Authentication")),O.createElement(W,{marginBottom:1},O.createElement(H,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),O.createElement(W,{marginBottom:1},O.createElement(H,{dimColor:!0},"After authorizing, copy the code and paste it below:")),l&&O.createElement(W,{marginBottom:1},O.createElement(H,{color:"red"},"Error: ",l)),O.createElement(W,null,O.createElement(H,null,"Authorization code: "),O.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:y,onSubmit:E,placeholder:"Paste code here..."})),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function getProviderDisplayName(e){if(!e)return"None";const t=pn[e];return t?.displayName||e}function getProviderConfig(e){return pn[e]}function isInternalTeamFlagPresent(){return process.argv.includes(st)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(at)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(h.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(pn).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var yn=__esm({"src/utils/provider-config.ts"(){wt(),Ct(),Lt(),fn(),Tt(),En(),pn={"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:gn,checkAuth:__name(async()=>!!await Rt.getValidAccessToken(),"checkAuth")}},__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalTeamFlagPresent,"isInternalTeamFlagPresent"),__name(isInternalTeamDisableFlagPresent,"isInternalTeamDisableFlagPresent"),__name(isInternalTeamFlagEnforced,"isInternalTeamFlagEnforced"),__name(getProviderOptions,"getProviderOptions")}});function isInternalTeamDisableOAuthFlagPresent(){return process.argv.includes(at)}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=getConfigFile(),t=await x.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,s=isInternalTeamFlagPresent();return isInternalTeamDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):s||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)}function formatTime2(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function formatTokens(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}var En=__esm({"src/utils/utils.ts"(){wt(),Tt(),Dt(),yn(),hn(),Ct(),__name(isInternalTeamDisableOAuthFlagPresent,"isInternalTeamDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut"),__name(formatTime2,"formatTime"),__name(formatTokens,"formatTokens")}});function isLocalDevelopmentBuild(){try{const e=process.argv[1];if(!e)return!1;if(e.includes("/usr/local/bin/dmd"))return!0;const t=f.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var wn=__esm({"src/utils/is-local-dev.ts"(){wt(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":St()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return Qe;case"local":return Ze;default:return Ye}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(h.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var bn=__esm({"src/utils/telemetry/config.ts"(){wt(),Tt(),En(),vt(),wn(),bt(),bt(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}});function getPackageJson(){const e=import.meta.url,t=c(e),n=r(t);return JSON.parse(E(o(n,"./../package.json"),"utf8"))}var Sn,kn,Cn,vn,Tn,An,Pn=__esm({"src/utils/package.ts"(){wt(),__name(getPackageJson,"getPackageJson")}});function createAxiomExporter(){return new kn({url:Je,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":et}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return Cn({[vn]:Xe,[Tn]:e.version,"process.executable.name":t,"process.runtime.name":"node","process.runtime.version":process.version,"process.pid":process.pid})}function createTelemetrySDK(){const e=createAxiomExporter(),t=createServiceResource();return new Sn({resource:t,spanProcessors:[new An(e)],autoDetectResources:!1})}var xn,In,Rn,$n,Dn,Nn=__esm({"src/utils/telemetry/sdk-factory.ts"(){wt(),bt(),bn(),Pn(),({NodeSDK:Sn}=ee),({OTLPTraceExporter:kn}=te),({resourceFromAttributes:Cn}=ne),({ATTR_SERVICE_NAME:vn,ATTR_SERVICE_VERSION:Tn}=re),({SimpleSpanProcessor:An}=oe),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function generateSessionId(){return`sess_${ce().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return N.createHash("sha256").update(e).digest("hex").substring(0,12)}function getCliVersion(){try{const e=getPackageJson();if("string"==typeof e.version&&""!==e.version.trim())return e.version}catch{}return"unknown"}function buildSessionAttributes(e){const{sessionId:t,projectPath:n,gitBranch:r,cliVersion:o}=e;return{"session.id":t,"session.start_time":(new Date).toISOString(),"session.project_hash":hashPath(n),"session.branch_hash":r?hashPath(r):"unknown","session.cli_version":o,"session.platform":`${m.platform()}-${m.arch()}`,"session.node_version":process.version}}function startSession(){Dn={},In=null,Rn=null,xn=generateSessionId(),$n=Date.now();try{const e=se.getTracer(Xe),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:xn,projectPath:n,gitBranch:r,cliVersion:t});In=e.startSpan("session:cli",{attributes:o}),Rn=In.spanContext(),In.end()}catch{In=null,Rn=null}return xn}function getTraceId(){return Rn?Rn.traceId:null}function getSessionContext(){return Rn?se.setSpanContext(ie.active(),Rn):ie.active()}function endSession(e={}){const{status:t="success"}=e;if(Rn&&$n){const e=se.getTracer(Xe),n=Date.now()-$n,r=se.setSpanContext(ie.active(),Rn),o=e.startSpan("session:end",{attributes:{"session.id":xn||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Dn}},r);"error"===t?o.setStatus({code:ae.ERROR}):o.setStatus({code:ae.OK}),o.end()}In=null,Rn=null,xn=null,$n=null,Dn={}}var Fn=__esm({"src/utils/telemetry/session.ts"(){wt(),bt(),Pn(),Dt(),xn=null,In=null,Rn=null,$n=null,Dn={},__name(generateSessionId,"generateSessionId"),__name(hashPath,"hashPath"),__name(getCliVersion,"getCliVersion"),__name(buildSessionAttributes,"buildSessionAttributes"),__name(startSession,"startSession"),__name(getTraceId,"getTraceId"),__name(getSessionContext,"getSessionContext"),__name(endSession,"endSession")}});function setSpanStatus(e,t){"error"===t?e.setStatus({code:ae.ERROR}):e.setStatus({code:ae.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=se.getTracer(Xe),o=getSessionContext();return r.startSpan(t,{attributes:n},o)}function endSpan(e){const{span:t,status:n="success"}=e;setSpanStatus(t,n),t.end()}function recordError(e){const{span:t,error:n,additionalAttributes:r}=e;if(t.recordException(n),t.setStatus({code:ae.ERROR,message:n.message}),t.setAttribute("error.type",n.name),t.setAttribute("error.message",n.message),n.stack&&t.setAttribute("error.stack",n.stack),r)for(const[e,n]of Object.entries(r))void 0!==n&&t.setAttribute(e,n)}var Ln=__esm({"src/utils/telemetry/spans.ts"(){wt(),bt(),Fn(),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});function isSecretKey(e){const t=e.toLowerCase();return tt.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return nt.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString(e){return e.length<=rt?e:`${e.substring(0,rt-3)}...`}function normalizeError(e){return e instanceof Error?e:new Error(String(e))}function sanitizeErrorForTelemetry(e){const{error:t,label:n="error"}=e,r=new Error(n);return r.name=t.name||"Error",r}function sanitizeValue(e){const{value:t,key:n,visited:r}=e;if(isContentKey(n)||isSecretKey(n))return"[redacted]";if(null==t)return t;if("string"==typeof t)return t.length>rt?truncateString(t):t;if("number"==typeof t||"boolean"==typeof t)return t;if("object"==typeof t){if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map((e,t)=>sanitizeValue({value:e,key:String(t),visited:r}));const e={};for(const[n,o]of Object.entries(t))e[n]=sanitizeValue({value:o,key:n,visited:r});return e}return"[Unsupported]"}function sanitizeParams(e){const t=new WeakSet;t.add(e);const n={};for(const[r,o]of Object.entries(e))n[r]=sanitizeValue({value:o,key:r,visited:t});return n}function sanitizeEndpoint(e){return e.split("?")[0]}var On=__esm({"src/utils/telemetry/sanitization.ts"(){wt(),bt(),__name(isSecretKey,"isSecretKey"),__name(isContentKey,"isContentKey"),__name(safeStringify,"safeStringify"),__name(truncateString,"truncateString"),__name(normalizeError,"normalizeError"),__name(sanitizeErrorForTelemetry,"sanitizeErrorForTelemetry"),__name(sanitizeValue,"sanitizeValue"),__name(sanitizeParams,"sanitizeParams"),__name(sanitizeEndpoint,"sanitizeEndpoint")}});function createTrackingHandle(e){const{span:t,startTime:n,durationAttr:r,statusAttr:o}=e;return{span:t,end:__name(e=>{const s=Date.now()-n;if(t.setAttribute(r,s),"status"in e)t.setAttribute(o,e.status),e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r,errorBody:o}=e;if(t.setAttribute("http.status_code",n),o){const e="string"==typeof o?o:safeStringify(o);t.setAttribute("http.response_body",e.substring(0,ot))}r?(recordError({span:t,error:r}),endSpan({span:t,status:"error"})):endSpan({span:t,status:n>=400?"error":"success"})}},"end")}}function trackToolStart(e){const{toolName:t,params:n}=e;return createTrackingHandle({span:createSpan({name:`tool:${t}`,attributes:{"tool.name":t,"tool.params":safeStringify(n?sanitizeParams(n):{})}}),startTime:Date.now(),durationAttr:"tool.duration_ms",statusAttr:"tool.status"})}function trackError(e){const{error:t,context:n}=e,r=normalizeError(t),{component:o,heading:s,code:a,...i}=n,c={"error.type":r.name,"error.message":r.message,"error.component":o,"error.heading":s};void 0!==a&&(c["error.code"]=String(a));for(const[e,t]of Object.entries(i))null!=t&&(c[e]="object"==typeof t?safeStringify(t):String(t));const l=createSpan({name:`error:${r.name}`,attributes:c});recordError({span:l,error:r}),l.end()}function trackAPICallStart(e){const{method:t,endpoint:n}=e,r=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${r}`,attributes:{"http.method":t,"http.url":r}}),startTime:Date.now(),durationAttr:"http.duration_ms",statusAttr:"http.status"})}function getSupportId(){const e=getTraceId();return e?`req_${e}`:"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,nodeVersion:s,platform:a,arch:i}=e,c={"whoami.node_version":s,"whoami.platform":a,"whoami.arch":i,"whoami.os":`${a}-${i}`};t&&(c["whoami.user_name"]=t),n&&(c["whoami.user_id"]=n),r&&(c["whoami.org_login"]=r),o&&(c["whoami.org_id"]=o),endSpan({span:createSpan({name:"whoami",attributes:c}),status:"success"})}var _n,Mn,Un,jn=__esm({"src/utils/telemetry/events.ts"(){wt(),Ln(),Fn(),bt(),On(),On(),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(trackError,"trackError"),__name(trackAPICallStart,"trackAPICallStart"),__name(getSupportId,"getSupportId"),__name(systemInfo,"systemInfo")}}),Bn=__esm({"src/utils/telemetry/components.ts"(){wt(),_n={AUTH_FLOW:"auth-flow",ANTHROPIC_OAUTH:"anthropic-oauth",ANTHROPIC_CLIENT:"anthropic-client",UNHANDLED_REJECTION:"unhandled-rejection",UNCAUGHT_EXCEPTION:"uncaught-exception",SESSION_MANAGER:"session-manager",UPDATE_COMMAND:"update-command",LEARN_TASTE_COMMAND:"learn-taste-command",LEARNING_AGENT:"learning-agent",TASTE_REMOTE_STORAGE:"taste-remote-storage",CHECKPOINT_MANAGER:"checkpoint-manager",FILE_HISTORY:"file-history",API_REQUEST:"api-request",CONTEXT_ENGINE:"context-engine",CLI_ERROR_HANDLER:"cli-error-handler"}}});function initTelemetry(){if(Un)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(Mn=createTelemetrySDK()).start(),Un=!0,!0}catch{return Mn=null,Un=!1,!1}}async function shutdownTelemetry(){if(Mn&&Un)try{endSession(),await Mn.shutdown()}catch{}finally{Mn=null,Un=!1}}function shutdownTelemetrySync(){if(Un)try{endSession()}catch{}}function isTelemetryInitialized(){return Un}var Wn,Hn,zn,Gn,qn,Vn,Kn,Jn,Yn,Qn,Zn,Xn,er,tr,nr,rr=__esm({"src/utils/telemetry/telemetry.ts"(){wt(),Nn(),bn(),Fn(),Ln(),jn(),Bn(),Mn=null,Un=!1,__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized")}}),or=__esm({"src/components/vscode-context/ipc-client.ts"(){wt(),mn(),Wn=t.join(g.homedir(),".commandcode","ide"),Hn=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),zn=__name(e=>{if("win32"===process.platform)return null;try{const t=v(`ps -o ppid= -p ${e}`,{encoding:"utf-8",timeout:1e3}),n=parseInt(t.trim(),10);return Number.isNaN(n)||n<=1?null:n}catch{return null}},"getParentPid"),Gn=__name((e,t,n=zn)=>{const r=new Map;for(const t of e)r.set(t.session.pid,t);let o=t;for(let e=0;e<10&&null!==o;e++){const e=r.get(o);if(e)return e;o=n(o)}return null},"findAncestorSession"),qn=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),Vn=__name((e,n)=>{try{f.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{f.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),Kn=__name((e,n={})=>{const{sessionDir:r=Wn,parentPidFn:o=zn,startPid:s=process.ppid}=n;try{if(!f.existsSync(r))return null;const n=`${e}-`,a=f.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),i=[];for(const e of a)try{const n=t.join(r,e),o=JSON.parse(f.readFileSync(n,"utf-8"));if(!Hn(o.pid)){Vn(n,r);continue}i.push({session:o,file:e})}catch{continue}if(0===i.length)return null;const c=Gn(i,s,o);if(c)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:c.session.socketPath,ideName:c.session.ideName}),c.session.socketPath;const l=process.cwd();let d=null,u=0;for(const{session:e}of i)for(const n of e.workspaceFolders)(l===n||l.startsWith(n+t.sep))&&n.length>u&&(d=e,u=n.length);return d&&dlog("[VSCode:IPC] Discovered session via workspace match",{socketPath:d.socketPath,ideName:d.ideName}),d?.socketPath??null}catch{return null}},"discoverSocketPath"),Jn=__name(()=>{const e=qn();return e?Kn(e):null},"resolveSocketPath"),Yn=__name(()=>({type:"request",id:L(),payload:{action:"getContext"}}),"createContextRequest"),Qn=__name(e=>{if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&!!["request","response","error"].includes(t.type)&&"object"==typeof t.payload&&null!==t.payload},"isValidIPCMessage"),Zn=__name((e,t)=>{try{const n=JSON.parse(e.toString());return Qn(n)?"response"!==n.type||n.id!==t?null:n.payload:(dlog("[VSCode:IPC] Invalid message structure"),null)}catch{return null}},"parseResponse"),Xn=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??Jn()}get isConnected(){return this.connected}async connect(e=2e3){if(!this.socketPath)return dlog("[VSCode:IPC] No socket path resolved"),!1;const t=this.socketPath;return dlog("[VSCode:IPC] Connecting to socket",{path:t,timeout:e}),new Promise(n=>{const r=__name(()=>{this.socket?.off("error",o)},"cleanup"),o=__name(e=>{clearTimeout(s),r(),this.connected=!1,dlog("[VSCode:IPC] Connection error",{error:e.message}),n(!1)},"handleError"),s=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),r(),this.socket?.destroy(),n(!1)},e);try{this.socket=de.connect(t),this.socket.on("connect",()=>{clearTimeout(s),r(),this.connected=!0,dlog("[VSCode:IPC] Connected successfully"),this.socket.on("close",()=>{this.connected=!1}),this.socket.on("error",()=>{this.connected=!1}),n(!0)}),this.socket.on("error",o)}catch(e){clearTimeout(s),r(),dlog("[VSCode:IPC] Connection exception",{error:e}),n(!1)}})}async getContext(e=5e3){const t=this.socket;if(!t||!this.connected)return dlog("[VSCode:IPC] Cannot get context - not connected"),null;const n=Yn();return dlog("[VSCode:IPC] Requesting context",{requestId:n.id}),new Promise(r=>{const o=__name(()=>{t.off("data",a),t.off("error",i)},"cleanup"),s=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),o(),r(null)},e),a=__name(e=>{clearTimeout(s),o();const t=Zn(e,n.id);t?dlog("[VSCode:IPC] Context received",{hasActiveFile:!!t.activeFile,hasSelection:!!t.selection,openFilesCount:t.openFiles.length}):dlog("[VSCode:IPC] Invalid response received"),r(t)},"handleData"),i=__name(e=>{clearTimeout(s),o(),dlog("[VSCode:IPC] Socket error during request",{error:e.message}),r(null)},"handleError");t.on("data",a),t.on("error",i);try{t.write(JSON.stringify(n)+"\n"),dlog("[VSCode:IPC] Request sent")}catch(e){clearTimeout(s),o(),dlog("[VSCode:IPC] Failed to send request",{error:e}),r(null)}})}disconnect(){this.socket&&(dlog("[VSCode:IPC] Disconnecting"),this.socket.end(),this.socket=null,this.connected=!1)}static async isAvailable(e=1e3){const t=new _VSCodeIPCClient;if(!t.socketPath)return dlog("[VSCode:IPC] Availability check",{available:!1,reason:"no socket path"}),!1;const n=await t.connect(e);return t.disconnect(),dlog("[VSCode:IPC] Availability check",{available:n}),n}}}}),sr={};function getVsixPath(){try{const e=t.dirname(c(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return f.existsSync(n)?n:null}catch{return null}}async function getExtensionStatus(e){if(!e)return{installed:!1,version:null,connected:!1};const[t,n]=await Promise.all([checkInstalled(e),Xn.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await er(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp(`${tr}@([\\d.]+)`,"i"));return n?{installed:!0,version:n[1]}:{installed:!1,version:null}}catch{return{installed:!1,version:null}}}async function installExtension(e){if(!e)return{success:!1,error:"No IDE detected"};const t=getVsixPath();if(!t)return{success:!1,error:"VSIX not bundled"};try{return await er(`${e} --install-extension "${t}" --force`,{timeout:3e4}),dlog(`[IDE] Extension installed for ${e}`),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function installExtensionAsync(e){e&&installExtension(e).catch(()=>{})}async function isAutoInstallEnabled(){try{return!1!==(await loadUserConfig()).autoInstallExtension}catch{return!0}}async function ensureExtensionInstalled(){if(process.env.CI)return;const e=qn();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:J.green("✔"),installed:J.green("✔"),needs_reload:J.yellow("◌"),failed:J.red("✖"),not_in_ide:J.yellow("◌")},n={connected:`Connected to ${e.ide}`,installed:`Installed for ${e.ide}`,needs_reload:`${e.ide} extension needs reload`,failed:e.ide?`${e.ide} install failed`:"Install failed",not_in_ide:"Not in IDE"};return["",`${t[e.status]} ${n[e.status]}`,...(e.details??[]).map(e=>J.dim(` ${e}`)),""]}async function runIDESetup(){const e=qn(),t=e?nr[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new Xn,r=await n.connect(500);if(n.disconnect(),r)return{status:"connected",ide:t};const{installed:o}=await checkInstalled(e);return o?{status:"needs_reload",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:(await installExtension(e)).success?{status:"installed",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:{status:"failed",ide:t,details:[`Make sure "${e}" is available in your PATH.`,"Then run /ide to retry installation."]}}((e,t)=>{for(var n in t)yt(e,n,{get:t[n],enumerable:!0})})(sr,{detectIDE:()=>qn,ensureExtensionInstalled:()=>ensureExtensionInstalled,formatSetupResult:()=>formatSetupResult,getExtensionStatus:()=>getExtensionStatus,installExtension:()=>installExtension,installExtensionAsync:()=>installExtensionAsync,isAutoInstallEnabled:()=>isAutoInstallEnabled,runIDESetup:()=>runIDESetup});var ar=__esm({"src/utils/ide-installer.ts"(){wt(),or(),mn(),hn(),er=ue(T),tr="commandcode.commandcode-vscode",__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled"),nr={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"},__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup")}});wt(),wt();var ir=process.argv.includes("-d")||process.argv.includes("--debug");ir&&(process.env.DEBUG="true"),ir||(process.removeAllListeners("warning"),process.on("warning",()=>{})),wt(),wt(),rr();var{red:cr,yellow:lr,dim:dr}=J,ur=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:o=!0,skipTelemetry:s=!1}=e;if(n){if(s||trackError({error:sanitizeErrorForTelemetry({error:n,label:"cli_error"}),context:{component:_n.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${ge.error} ${cr(t)}`),console.log(`${ge.error} ${cr("ERROR →")} ${n.name}`),console.log(`${ge.info} ${cr("REASON →")} ${n.message}`),console.log(`${ge.info} ${cr("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${ge.info} ${dr(`Request ID: ${e}`)}`),console.log(`${dr(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${ge.warning} ${lr(t)}\n`);if(!o)return!1;process.exit(0)}},"handleError");function handleUnhandledErrors(){process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:_n.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),ur({heading:me`CRITICAL: Unhandled Promise Rejection!
3
- This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:t,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})}),process.on("uncaughtException",e=>{trackError({error:sanitizeErrorForTelemetry({error:e,label:"uncaught_exception"}),context:{component:_n.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),ur({heading:me`CRITICAL: Uncaught Exception!
4
- This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}async function findAvailablePort(e=5959,t=10){for(let n=0;n<t;n++){const t=e+n;if(await checkPortAvailable(t))return t}throw new Error(`No available port found after ${t} attempts starting from port ${e}`)}async function checkPortAvailable(e){return new Promise(t=>{const n=le.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}rr(),__name(handleUnhandledErrors,"handleUnhandledErrors"),wt(),wt(),Ct(),wt(),wt(),Ct(),wt(),wt(),wt(),wt(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable");var mr=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}};function createAuthServer(e,t){let n,r;const o=new Promise((e,t)=>{n=e,r=t}),s=Pe.createServer((e,o)=>{const a=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],i=e.headers.origin||"",c=a.includes(i)?i:a[0];if(o.setHeader("Access-Control-Allow-Origin",c),o.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type"),o.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return o.writeHead(204),void o.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return o.writeHead(404),void o.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return o.writeHead(405),void o.end(JSON.stringify(e))}let l="";e.on("data",t=>{l+=t.toString(),l.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(l);if(e.error){const t=e,n={success:!0};return o.writeHead(200),o.end(JSON.stringify(n)),"access_denied"===t.error?r(new mr(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void s.close()}const a=e;if(!(a.apiKey&&a.state&&a.userId&&a.userName&&a.keyName)){const e={success:!1,error:"Missing required fields"};return o.writeHead(400),void o.end(JSON.stringify(e))}if(a.state!==t){const e={success:!1,error:"Invalid state token"};return o.writeHead(403),void o.end(JSON.stringify(e))}const i={success:!0};o.writeHead(200),o.end(JSON.stringify(i)),n(a),s.close()}catch{const e={success:!1,error:"Invalid JSON"};o.writeHead(400),o.end(JSON.stringify(e))}}),e.on("error",()=>{o.writeHead(500),o.end(JSON.stringify({success:!1,error:"Request error"}))})});return s.on("error",e=>{r(e)}),s.listen(e,"127.0.0.1"),{server:s,waitForCallback:o}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}function generateStateToken(){return N.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await X(e),!0}catch(e){return console.error("[CLI Auth] Failed to open browser:",e instanceof Error?e.message:"Unknown error"),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"browser_open_failed"}),context:{component:_n.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(St()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer"),vt(),Tt(),rr(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl");var gr=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}};async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await P.mkdir(t,{recursive:!0,mode:448});const r=JSON.stringify({apiKey:e.apiKey,userId:e.userId,userName:e.userName,keyName:e.keyName,authenticatedAt:e.authenticatedAt},null,2);await P.writeFile(n,r,{mode:384}),await P.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await P.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}function getApiBaseUrl(){const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials"),wt(),__name(getApiBaseUrl,"getApiBaseUrl"),Ct(),rr();var pr=12e4;async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${ct.ALPHA.WHOAMI}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});return 401===n.status?{valid:!1,error:"invalid_key"}:n.ok?{valid:!0,user:await n.json()}:(process.env.DEBUG&&console.error(`API key validation failed with status ${n.status}`),{valid:!1,error:"server_error"})}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"apikey_validation_network_error"}),context:{component:_n.AUTH_FLOW,heading:"API key validation network error"}}),process.env.DEBUG&&console.error("API key validation network error:",e),{valid:!1,error:"network_error"}}}function sanitizeApiKey(e){const t=String.fromCharCode(27),n=e.replaceAll(t+"[200~","").replaceAll(t+"[201~","").replaceAll("[200~","").replaceAll("[201~","");return Array.from(n).filter(e=>{const t=e.charCodeAt(0);return t>31&&127!==t}).join("").trim()}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:o=pr}=e,[s,a]=_("initializing"),[i,c]=_("Starting authentication..."),[l,d]=_(""),[u,m]=_(null),g=M(null),p=M(!1),h=M(!1),f=M(null),y=M(t),E=M(n),w=M(r);U(()=>{y.current=t,E.current=n,w.current=r});const b=j(()=>{f.current&&(clearTimeout(f.current),f.current=null),g.current&&(stopServer(g.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),g.current=null)},[]),S=j(()=>{h.current||(h.current=!0,p.current=!0,b(),w.current())},[b]),k=j((e,t)=>{h.current||(h.current=!0,b(),y.current(e,t))},[b]),C=j((e,t)=>{h.current||(h.current=!0,b(),E.current(e,t))},[b]),v=j(async e=>{const t=sanitizeApiKey(e);if(!t)return;a("validating"),c("Validating API key...");const n=await validateApiKey(t);if(p.current)return;if(h.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return a("invalid_key"),c(e),void(f.current=setTimeout(()=>{p.current||h.current||(a("manual_entry"),c("Paste a valid API key below.")),f.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(h.current)return;await storeCredentials(e),a("success"),k(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:_n.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),c("Failed to save API key. Please try again."),a("manual_entry")}},[k]);return U(()=>{let e=!0;return __name(async()=>{if(!p.current)try{const t=await findAvailablePort(5959,10);if(!e||p.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);m(r);const{server:s,waitForCallback:i}=createAuthServer(t,n);if(g.current=s,!e||p.current)return void await stopServer(s);a("waiting_browser"),c("Opening browser for authentication...");const l=await openBrowser(r);if(!e||p.current)return;if(!l)return b(),c("Could not open browser. Paste your API key below."),void a("manual_entry");c("Complete login in your browser...");const d=new Promise((e,t)=>{setTimeout(()=>{t(new gr("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([i,d]);if(!e||p.current)return;if(h.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(h.current)return;if(await storeCredentials(n),!e||p.current||h.current)return;a("browser_success"),k(n,"browser")}catch(t){if(h.current)return;if(!e||p.current)return;if(t instanceof mr)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:_n.AUTH_FLOW,heading:"Authorization denied by user"}}),a("denied"),void C("denied","Authorization denied by user.");b(),t instanceof gr&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:_n.AUTH_FLOW,heading:"Browser auth timed out"}}),c("Browser auth timed out. Paste your API key below.")):(trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_failed"}),context:{component:_n.AUTH_FLOW,heading:"Browser auth failed"}}),c("Browser auth failed. Paste your API key below.")),a("manual_entry")}}catch(t){if(h.current)return;if(!e||p.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:_n.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),b(),a("manual_entry"),c("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,b()}},[o,k,C,b]),{authState:s,statusMessage:i,browserUrl:u,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:v,cancel:S,hasCompleted:h.current}}function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){switch(e){case"waiting_browser":return"Authorize in browser, or paste API key here";case"invalid_key":return"That key was invalid. Try again.";default:return"Paste your API key and press Enter"}}function getAuthUrlLabel(e){return"waiting_browser"===e?"Authenticating via:":"Get your API key from:"}__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow"),wt(),nn(),Ct(),vt(),wt(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel");var hr=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const a=__name(()=>{switch(e){case"initializing":case"waiting_browser":case"validating":default:return O.createElement(Ae,{type:"dots"});case"browser_success":case"success":return O.createElement(H,{color:"green"},pe.tick);case"denied":case"invalid_key":return O.createElement(H,{color:"red"},pe.cross);case"manual_entry":return O.createElement(H,{color:"yellow"},pe.arrowDown);case"error":return O.createElement(H,{color:"red"},pe.warning)}},"getStatusIcon"),i=__name(()=>getAuthStatusColor(e),"getStatusColor");if("browser_success"===e||"success"===e||"denied"===e)return null;const c="initializing"===e||"waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,l=n&&("waiting_browser"===e||"manual_entry"===e);return O.createElement(W,{flexDirection:"column",paddingY:1},O.createElement(W,{marginBottom:1},O.createElement(W,{marginRight:1},a()),O.createElement(H,{color:i()},t)),c&&O.createElement(W,{flexDirection:"column"},O.createElement(W,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?"yellow":"gray",paddingX:1},O.createElement(H,{dimColor:!0},"API Key: "),O.createElement(W,{flexGrow:1},O.createElement(TextInput,{value:r,onChange:o,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},getAuthHelpText(e))),l&&O.createElement(W,{marginTop:1,flexDirection:"column"},O.createElement(H,{dimColor:!0},getAuthUrlLabel(e)),O.createElement(H,{color:"cyan",dimColor:!0},n||getStudioAuthUrl(St())))),"validating"===e&&O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"initializing"===e||"invalid_key"===e)&&O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Ctrl+C to cancel")))},"AuthFlowUI"),fr=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a,cancel:i}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return V((e,t)=>{t.ctrl&&"c"===e&&i()}),O.createElement(hr,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey");function heading({text:e,sub:t,dim:n,green:r}){const o=t?` ${t}`:"";return r?`${Q.bgGreen(Q.black(` ${e} `))}${o}`:n?`${Q.bgBlack(Q.white(` ${e} `))}${o}`:`${Q.bold(Q.bgCyan(Q.black(` ${e} `)))}${o}`}async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=Rt.createAuthorizationUrl(),r=await ve({message:"Open the Anthropic auth page?"});if(ke(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await X(e),console.log(),console.log(Q.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(Q.dim(" Open this URL in your browser:")),console.log(),console.log(Q.cyan(` ${e}`)),console.log(),console.log(Q.yellow(" Copy your authorization code and paste it below.")),console.log());const o=await Te({message:"Paste your authorization code:",mask:"*"});if(ke(o))return{success:!1,error:"No API key provided"};if(!o.trim())return{success:!1,error:"No authorization code provided"};const s=o.split("#")[0].trim();return await Rt.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}Ft(),vt(),wt(),__name(heading,"heading"),yn(),hn(),wt(),Lt(),__name(performAnthropicAuth,"performAnthropicAuth"),wt();var yr=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},Er=class extends Error{static{__name(this,"AuthorizationDeniedError")}constructor(e){super(e),this.name="AuthorizationDeniedError"}};async function readAuthFile(e){try{const t=getAuthFile(e),n=await x.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async function getAuthKey(e){const t=await readAuthFile(e);return t&&t.apiKey||null}async function checkAuthStatus(e){const t=await readAuthFile(e);return t&&t.apiKey?{authenticated:!0,apiKey:t.apiKey,userName:t.userName}:{authenticated:!1,apiKey:null}}async function statusAction(){const e=xe("Checking authentication status...").start();try{const t=St(),n=await checkAuthStatus(t);n.error&&(e.fail(Q.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(Q.red("Not authenticated")),console.log(""),console.log(`${Q.dim("Run")} ${Q.cyan("cmd auth login")} ${Q.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${Q.green(pe.tick)} ${Q.bold("Authenticated")} with ${Q.cyan("Command Code")}`),n.userName&&console.log(`${Q.dim("Logged in as")} ${Q.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(Q.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}wt(),Ct(),Tt(),vt(),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction");var wr=new ye("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction),br=__name(({message:e})=>O.createElement(O.Fragment,null,O.createElement(H,{color:"cyan"},O.createElement(Ae,{type:"dots"})),O.createElement(H,null," ",e)),"LoadingIndicator"),Sr=__name(({message:e})=>O.createElement(O.Fragment,null,O.createElement(H,{color:"green"},pe.tick),O.createElement(H,null," ",e)),"SuccessIndicator"),kr=__name(({children:e})=>O.createElement(W,{flexDirection:"column"},O.createElement(H,null," "),O.createElement(W,null,e)),"StatusContainer");function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,a]=_("loading"),[i,c]=_(null);return U(()=>{n().then(e=>{c(e),a(o?"success":"done")})},[n,o]),U(()=>{if("done"===s&&null!==i&&r(i),"success"===s&&null!==i){const e=setTimeout(()=>r(i),100);return()=>clearTimeout(e)}},[s,i,r]),"done"===s?null:O.createElement(kr,null,"loading"===s?O.createElement(br,{message:e}):O.createElement(Sr,{message:t}))}async function checkExistingAuth(e){const t=await checkAuthStatus(e);return t.authenticated?{isAuthenticated:!0,userName:t.userName}:{isAuthenticated:!1}}function getAuthFileName(e){return"local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json"}function isGenericUserName(e){return!e||"API Key"===e}function isGenericUserNameForOutro(e){return isGenericUserName(e)||"Manual API Key"===e}function formatUserDisplay(e,t=!1){return(t?isGenericUserNameForOutro(e):isGenericUserName(e))?t?" successfully":"":` as ${Q.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${Q.green(pe.tick)} ${Q.bold("Already logged in")}${t}`,"",`${Q.dim("Run")} ${Q.cyan("cmd")} ${Q.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${Q.green(pe.tick)} ${Q.bold("Logged in")}${n}`,"",`${Q.dim("API key stored in")} ${Q.cyan(`~/.commandcode/${t}`)}`,`${Q.dim("Run")} ${Q.cyan("cmd")} ${Q.dim("to get started.")}`].join("\n")}function isLoginSuccess(e){return e.success}function isLoginDenied(e){return"denied"===e.reason}function isLoginCancelled(e){return"cancelled"===e.reason}function createLoginError(e){return isLoginDenied(e)?new Er(e.message):isLoginCancelled(e)?new yr(e.message):new Error(e.message)}function processLoginResult(e){return isLoginSuccess(e)?{success:!0,userName:e.config?.userName}:{success:!1,error:createLoginError(e)}}function needsProviderSelection(e){return e.length>1}function getDefaultProvider(e){return e[0]?.value??""}function isAnthropicProvider(e){return"anthropic"===e}function isUserCancellation(e){return e instanceof yr||e instanceof Er}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),we.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await Se({message:"Select provider",options:e});if(ke(t))throw be(`${pe.cross} No provider selected.`),new yr("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){be(`${pe.cross} ${e}`)}function showAnthropicAuthNote(){Ce("Command Code authentication complete. Now authenticating with Anthropic...")}function printMessage(e){console.log(""),console.log(e),console.log("")}function renderTaskWithSpinner(e,t,n,r=!0){return new Promise(o=>{const s=__name(e=>{a(),o(e)},"handleComplete"),{unmount:a}=G(O.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:s,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=G(O.createElement(fr,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__name(isGenericUserName,"isGenericUserName"),__name(isGenericUserNameForOutro,"isGenericUserNameForOutro"),__name(formatUserDisplay,"formatUserDisplay"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(isLoginSuccess,"isLoginSuccess"),__name(isLoginDenied,"isLoginDenied"),__name(isLoginCancelled,"isLoginCancelled"),__name(createLoginError,"createLoginError"),__name(processLoginResult,"processLoginResult"),__name(needsProviderSelection,"needsProviderSelection"),__name(getDefaultProvider,"getDefaultProvider"),__name(isAnthropicProvider,"isAnthropicProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage,"getErrorMessage"),__name(showAuthIntro,"showAuthIntro"),__name(promptProviderSelection,"promptProviderSelection"),__name(selectProvider,"selectProvider"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(showAnthropicAuthNote,"showAnthropicAuthNote"),__name(printMessage,"printMessage"),__name(renderTaskWithSpinner,"renderTaskWithSpinner"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow");var Cr=__name(({env:e,onComplete:t})=>{const[n,r]=_("checking"),[o,s]=_(null);return U(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),U(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),O.createElement(kr,null,"checking"===n&&O.createElement(br,{message:"Checking authentication status..."}),"logged_in"===n&&O.createElement(Sr,{message:"Authenticated"}),"not_logged_in"===n&&O.createElement(Sr,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=G(O.createElement(Cr,{env:e,onComplete:e=>{n(),t(e)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function saveConfigWithSpinner(e){await renderTaskWithSpinner("Saving configuration...","Configuration saved",()=>updateUserConfig({provider:e}),!0)}async function executeLoginFlow(){const e=processLoginResult(await runLoginWithApiKeyFlow());if(!e.success)throw showLoginCancelMessage(e.error.message),e.error;return e.userName}async function handleAnthropicAuth(e){isAnthropicProvider(e)&&(showAnthropicAuthNote(),await performAnthropicAuth())}async function finalizeLogin(e,t,n){await saveConfigWithSpinner(e),printMessage(buildSuccessMessage(t,getAuthFileName(n)))}async function runLogin(){const e=St(),t=await checkAuthWithSpinner(e);if(t.isAuthenticated)return printMessage(buildAlreadyLoggedInMessage(t.userName)),!0;showAuthIntro();const n=await executeLoginFlow();let r="command-code";return isInternalTeamFlagEnforced()&&(r=await selectProvider(),await handleAnthropicAuth(r)),await finalizeLogin(r,n,e),!0}async function loginAction(){try{await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${pe.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleAnthropicAuth,"handleAnthropicAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var vr=new ye("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction);async function safeRemoveFile(e,t){try{return await x.unlink(e),{existed:!0}}catch(e){return"ENOENT"===e.code?{existed:!1}:{existed:!0,warning:`Could not remove ${t}: ${e.message}`}}}function collectWarnings(...e){return e.map(e=>e.warning).filter(e=>void 0!==e)}async function performLogout(){try{const e=await safeRemoveFile(getAuthFile(),"auth file"),t=collectWarnings(e);return{success:!0,wasAuthenticated:e.existed,warnings:t}}catch(e){return{success:!1,wasAuthenticated:!1,warnings:[],error:e instanceof Error?e.message:"Unknown error"}}}wt(),wt(),Tt(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout");var Tr=__name(()=>O.createElement(O.Fragment,null,O.createElement(H,{color:"cyan"},O.createElement(Ae,{type:"dots"})),O.createElement(H,null," Logging out...")),"LoadingIndicator"),Ar=__name(()=>O.createElement(O.Fragment,null,O.createElement(H,{color:"green"},pe.tick),O.createElement(H,null," Logged out")),"SuccessIndicator"),Pr=__name(({errorMessage:e})=>O.createElement(O.Fragment,null,O.createElement(H,{color:"red"},pe.cross),O.createElement(H,{color:"red"}," Logout failed: ",e)),"ErrorIndicator"),xr=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return O.createElement(Tr,null);case"success":return O.createElement(Ar,null);case"error":return O.createElement(Pr,{errorMessage:t})}},"StatusDisplay"),Ir=__name(({onComplete:e})=>{const[t,n]=_("loading"),[r,o]=_(""),[s,a]=_(null);return U(()=>{performLogout().then(e=>{a(e),e.success?n("success"):(o(e.error||"Unknown error"),n("error"))})},[]),U(()=>{if(("success"===t||"error"===t)&&s){const t=setTimeout(()=>e(s),100);return()=>clearTimeout(t)}},[t,s,e]),O.createElement(W,{flexDirection:"column"},O.createElement(H,null," "),O.createElement(W,null,O.createElement(xr,{status:t,errorMessage:r})))},"LogoutSpinner");function printWarnings(e){e.length>0&&(console.warn(Q.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(Q.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=G(O.createElement(Ir,{onComplete:n=>{t(),e(n)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction");var Rr=new ye("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction);vt(),Tt(),new ye("auth").description("Manage authentication with Command Code").addCommand(vr).addCommand(Rr).addCommand(wr),wt(),Ct();var $r="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",Dr="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n";function getMaxLineWidth(e){return Math.max(...e.split("\n").map(e=>e.length))}__name(getMaxLineWidth,"getMaxLineWidth");var Nr=getMaxLineWidth($r),Fr=getMaxLineWidth(Dr),Lr=Nr+1,Or=Fr+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var _r=__name(e=>{const t=e??getTerminalWidth();return t>=Lr?$r:t>=Or?Dr:Mr},"getResponsiveCommandLogo"),Mr="⌘ CMD\n",Ur=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),jr=__name(e=>{console.log(J.white(_r())),console.log(""),console.log(`${pe.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),Br=__name(async e=>{const t=fe.createInterface({input:process.stdin,output:process.stdout});try{const n=await t.question(e);return t.close(),{answer:n,cancelled:!1}}catch{return t.close(),{answer:"",cancelled:!0}}},"promptYesNo"),Wr=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.log(""),console.log(`${pe.cross} Authentication failed. Please try again with: cmd login`),!1)}catch{return!1}},"attemptLogin"),Hr=__name(()=>{console.log(""),console.log(`${pe.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),zr=__name(()=>{console.log(""),console.log(`${pe.info} Authentication cancelled. You can authenticate later with: cmd login`)},"showCancelledMessage");async function checkAuthAndPromptLogin(){try{if(await getAuthKey())return!0;jr(kt());const{answer:e,cancelled:t}=await Br(`Would you like to sign in now? ${J.dim("(y/n)")}: `);return t?(zr(),!1):Ur(e)?(console.log(""),Wr()):(Hr(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin"),wt(),wt(),Ct(),wt();var Gr=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(!t.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const n=t.relative(this.projectRoot,e);if(!n.startsWith("../../../"))return n.startsWith("../")?n:`./${n}`}catch(e){}if(this.options.useHomeShorthand&&e.startsWith(this.homeDir))return e.replace(this.homeDir,"~");const n=t.basename(e);return t.dirname(e),this.isUserPath(e)?`<user-home>/${t.relative(this.homeDir,e)}`:`<system-path>/${n}`}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))}};wt(),wt();var qr=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 Vr({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Kr(e,o,n,r);case 401:return new Jr(e,o,n,r);case 403:return new Yr(e,o,n,r);case 404:return new Qr(e,o,n,r);case 409:return new Zr(e,o,n,r);case 422:return new Xr(e,o,n,r);case 429:return new eo(e,o,n,r);default:return e>=500?new to(e,o,n,r):new _APIError(e,o,n,r)}}},Vr=class extends qr{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)}},Kr=class extends qr{static{__name(this,"BadRequestError")}status=400},Jr=class extends qr{static{__name(this,"AuthenticationError")}status=401},Yr=class extends qr{static{__name(this,"PermissionDeniedError")}status=403},Qr=class extends qr{static{__name(this,"NotFoundError")}status=404},Zr=class extends qr{static{__name(this,"ConflictError")}status=409},Xr=class extends qr{static{__name(this,"UnprocessableEntityError")}status=422},eo=class extends qr{static{__name(this,"RateLimitError")}status=429},to=class extends qr{static{__name(this,"InternalServerError")}};rr();var no=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}),o=trackAPICallStart({method:e.method,endpoint:t});let s;try{s=await this.makeRequest({url:n,options:e,headers:r})}catch(e){const t=new Vr({cause:e instanceof Error?e:void 0});throw o.end({statusCode:0,error:t}),t}if(!s.ok){const{error:e}=await this.handleErrorResponse({response:s});throw o.end({statusCode:s.status,error:e}),e}return o.end({statusCode:s.status}),e.stream?s.body:s.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const s=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return o&&clearTimeout(o),s}catch(e){throw o&&clearTimeout(o),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};return e.headers.forEach((e,t)=>{n[t]=e}),{error:qr.generate(e.status,t,e.statusText,n),errorBody:t}}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"})}};Lt(),wt(),Lt(),wt(),wt(),wt(),wt();var ro=u.object({name:u.string().min(1,"Skill name is required").max(64,"Skill name must be 64 characters or less").regex(/^[a-z0-9-]+$/,"Skill name must contain only lowercase letters, numbers, and hyphens").refine(e=>!e.startsWith("-")&&!e.endsWith("-"),"Skill name cannot start or end with a hyphen").refine(e=>!e.includes("--"),"Skill name cannot contain consecutive hyphens"),description:u.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:u.string().optional(),compatibility:u.array(u.string()).optional(),metadata:u.record(u.string(),u.any()).optional(),"allowed-tools":u.array(u.string()).optional()});function getPersonalSkillsDir(){return t.join(g.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return t.join(process.cwd(),".commandcode","skills")}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await x.access(n);const e=(await x.readdir(n,{withFileTypes:!0})).filter(e=>e.isDirectory());return(await Promise.all(e.map(async e=>{try{const r=t.join(n,e.name,"SKILL.md");await x.access(r);const o=await x.readFile(r,"utf-8"),{data:s}=Re(o),a=ro.parse(s);return{name:a.name,description:a.description,filePath:r}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}async function loadAllSkillSummaries(){const[e,t]=await Promise.all([loadSkillSummariesFromDirectory({dir:getPersonalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir()})]);return{personal:e,project:t}}function escapeXML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function generateSkillsXML(e){const{personal:n,project:r}=e,o=[...n,...r];return 0===o.length?"":`<available_skills>\n${o.map(e=>{const n=t.normalize(e.filePath);return`<skill>\n<name>\n${escapeXML(e.name)}\n</name>\n<description>\n${escapeXML(e.description)}\n</description>\n<location>\n${escapeXML(n)}\n</location>\n</skill>`}).join("\n")}\n</available_skills>`}function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}u.object({name:u.string(),description:u.string(),license:u.string().optional(),compatibility:u.array(u.string()).optional(),metadata:u.record(u.string(),u.any()).optional(),"allowed-tools":u.array(u.string()).optional(),content:u.string(),filePath:u.string()}),u.object({name:u.string(),description:u.string(),filePath:u.string()}),Ct(),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),wt(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),wt(),wt(),wt(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath"),wt();var oo=u.object({absolutePath:u.string().describe("The absolute path to the file to read"),offset:u.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:u.number().optional().describe("Optional number of lines to read")});u.object({content:u.union([u.string(),u.instanceof(Buffer)]),contentType:u.enum(["text","binary"]),fileType:u.string(),size:u.number(),linesRead:u.number().optional()});var so=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};async function readFileContent(t){const{absolutePath:n,offset:r,limit:o}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new so("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=e.normalize(n);try{await P.access(s,h.constants.F_OK|h.constants.R_OK)}catch{throw new so(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await P.stat(s)).isFile())throw new so("Path does not point to a file","NOT_A_FILE");const a=getFileType(s),i=isBinaryFile(a);if(void 0!==r&&void 0===o||void 0===r&&void 0!==o)throw new so("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new so("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new so("Limit must be > 0","INVALID_LIMIT");try{if(i){const e=await P.readFile(s);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==r&&void 0!==o){const e=await readTextFileLines(s,r,o);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await P.readFile(s,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof so)throw e;throw new so(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var ao={".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(t){const n=e.extname(t).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",...ao}[n]||"unknown"}function isBinaryFile(e){return Object.values(ao).includes(e)}async function readTextFileLines(e,t,n){const r=(await P.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),a=r.slice(o,s);return{content:a.join("\n"),linesRead:a.length}}async function processFileReferences(t){const n=[];let r=t;const o=[...t.matchAll(/@([^\s@]+)/g)];for(const t of o){const o=t[0],s=t[1];try{const t=e.isAbsolute(s)?s:e.resolve(process.cwd(),s),a=await readFileContent({absolutePath:t});if("binary"===a.contentType)continue;const i=String(a.content),c=e.relative(process.cwd(),t),l=1e5;if(i.length>l){n.push({token:o,resolvedPath:t,content:"",tooLarge:!0});const e=`${c}`;r=r.replace(o,e);continue}n.push({token:o,resolvedPath:t,content:i});const d=`{${c}: ${i}}`;r=r.replace(o,d)}catch(e){continue}}return{displayContent:t,processedContent:r,fileReferences:n}}function reconstructContent(t,n){let r=t;for(const t of n){const n=`{${e.relative(process.cwd(),t.resolvedPath)}: ${t.content}}`;r=r.replace(t.token,n)}return r}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),wt(),wt();var io="read_file",co="edit_file",lo="write_file",uo="read_directory",mo="read_multiple_files",go="grep",po="shell_command",ho="think",fo="todo_write",yo="ask_user_question",Eo="kill_shell",wo="web_search",bo="web_fetch",So=__name(e=>e===wo,"isWebSearchTool");function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",o=e.relative(n,t);return o.startsWith("..")?r&&t.startsWith(r)?t.replace(r,"~"):t:""===o?e.basename(t):o}function replacePathsInText(t){if(!t||"string"!=typeof t)return t;let n=t;return n=n.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,t=>e.isAbsolute(t)?toRelativePath(t):t),n=n.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),n}wt(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText");var ko=u.object({id:u.string(),timestamp:u.number(),type:u.literal("image"),source:u.object({type:u.enum(["base64","url"]),media_type:u.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:u.string()})}),Co=u.object({id:u.string(),timestamp:u.number(),input:u.string(),output:u.string().optional(),metadata:u.record(u.string(),u.any()).optional(),images:u.array(ko).optional().default([])}),vo=Co.extend({role:u.literal("user")}),To=Co.extend({role:u.literal("assistant")}),Ao=Co.extend({role:u.literal("tool"),name:u.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),Po=Co.extend({role:u.literal("bash"),command:u.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),xo=Co.extend({role:u.literal("system")}),Io=Co.extend({role:u.literal("error")}),Ro=Co.extend({role:u.literal("info")}),$o=Co.extend({role:u.literal("taste-onboarding")}),Do=Co.extend({role:u.literal("command-result"),hasError:u.boolean().optional(),details:u.string().optional()}),No=Co.extend({role:u.literal("ide-status"),status:u.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:u.string().nullable(),details:u.array(u.string()).optional()}),Fo=u.discriminatedUnion("role",[vo,To,Ao,Po,xo,Io,Ro,$o,Do,No]),Lo=__name((e,t)=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),Oo=__name(e=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e}),"createInfoEntry"),_o=__name(e=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),Mo=__name((e,t,n)=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Uo=__name(e=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),jo=__name(e=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Bo=__name(e=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),Wo=__name(()=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Ho=__name((e,t=!1,n)=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),zo=__name((e,t,n)=>Fo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),Go=__name(({name:e,input:t})=>{const n=Date.now();return Fo.parse({id:crypto.randomUUID(),timestamp:n,role:"tool",name:e,input:t,output:void 0,metadata:{isAgent:!0,status:"running",startTime:n,tokensUsed:0}})},"createAgentToolEntry"),qo=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return Fo.parse(n)},"updateEntryWithOutput"),Vo=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),Ko=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),Jo=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),Yo=["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…"],Qo=__name(()=>Yo[Math.floor(Math.random()*Yo.length)],"getRandomLLMStatus"),Zo=__name(e=>{switch(e){case io:return"Read";case co:return"Edit";case lo:return"Write";case uo:return"List";case mo:return"Read Multiple";case go:return"Search";case po:return"Shell";case fo:return"Todos";case ho:return"Thinking…";case wo:return"Web Search";case bo:return"Web Fetch";case yo:return"Question";case"explore":return"Explore";case Eo:return"Kill Shell";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),Xo=__name((e,t)=>{try{switch(e){case io:case lo:const e=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(e);case co:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case uo:return toRelativePath(t.path||"directory");case go:const n=t.path||"files";return`"${t.pattern}" in ${toRelativePath(n)}`;case po: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 fo:let r;try{r="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=es(r);return`${e?e.length:0} items`}catch{return"items"}case ho:return t.content||"planning";case mo:const o=t.include||[];return Array.isArray(o)?o.join(", "):"multiple files";case wo:return t.query||"search";case bo:return t.url||"fetch";case yo:return"User answered questions";case Eo:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";default:{let e=t?.messages||[];if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return JSON.stringify(t||{})}if(Array.isArray(e)&&e.length>0&&e[0]&&"object"==typeof e[0]&&"content"in e[0]){const t=e[0].content;if("string"==typeof t){const e=t.trim(),n=e.indexOf("."),r=n>0?e.slice(0,n):e;return r.length>80?r.slice(0,80)+"...":r}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),es=__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");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")}wt(),wt(),wt(),__name(formatOutput,"formatOutput");var ts={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=oo.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while reading file`}},"execute")};wt(),wt();var ns=u.object({filePath:u.string().describe("The absolute path to the file to edit"),oldValue:u.string().describe("The text to replace"),newValue:u.string().describe("The new text to insert"),replacementCount:u.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:u.boolean().optional().describe("Whether to replace all occurrences (default: false)")});u.object({path:u.string(),replacementsCount:u.number(),oldContent:u.string(),newContent:u.string()}),u.object({name:u.string(),message:u.string(),code:u.string().optional()}),wt(),wt(),wt();var rs=u.object({backupFileName:u.string().nullable(),version:u.number().int().positive(),backupTime:u.string().datetime()}),os=u.object({messageId:u.string().uuid(),trackedFileBackups:u.record(u.string(),rs),timestamp:u.string().datetime()});u.object({type:u.literal("file-history-snapshot"),messageId:u.string().uuid(),snapshot:os,isSnapshotUpdate:u.boolean()}),u.object({maxFileSize:u.number().int().positive().default(10485760),retentionDays:u.number().int().positive().default(30)});var ss=class extends Error{static{__name(this,"CheckpointError")}code;constructor(e,t){super(e),this.name="CheckpointError",this.code=t}};function getPathHash(e){const{filePath:t}=e;return`${F.createHash("sha256").update(t).digest("hex").slice(0,16)}-${t.length}`}function getBackupFileName(e){const{filePath:t,version:n}=e;return`${getPathHash({filePath:t})}@v${n}`}function getCommandCodeBasePath(){return t.join(g.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:n}=e;return t.join(getCommandCodeBasePath(),"file-history",n)}function getBackupFilePath(e){const{sessionId:n,backupFileName:r}=e;return t.join(getFileHistoryPath({sessionId:n}),r)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await x.statfs(t);return e.bavail*e.bsize}catch{return-1}}async function hasEnoughDiskSpace(e){const{fileSizeBytes:t,targetPath:n}=e,r=2*t,o=await getAvailableDiskSpace({targetPath:n});return-1===o||o>=r}async function ensureDirectoryExists(e){const{dirPath:t}=e;await x.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await x.writeFile(r,n);const e=await x.stat(r),o="string"==typeof n?Buffer.byteLength(n,"utf-8"):n.length;if(e.size!==o)throw new Error(`Write verification failed: expected ${o} bytes, got ${e.size}`);await x.rename(r,t)}catch(e){try{await x.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await x.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await x.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function truncateString2(e){const{text:t,maxLength:n}=e;return t.length<=n?t:n<=3?t.slice(0,n):t.slice(0,n-3)+"..."}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60),a=Math.floor(s/24);return a>0?`${a}d ago`:s>0?`${s}h ago`:o>0?`${o}m ago`:"just now"}function getFileName(e){const{filePath:n}=e;return t.basename(n)}function isWithinRetentionPeriod(e){const{timestamp:t,retentionDays:n}=e,r=new Date(t).getTime();return Date.now()-r<=24*n*60*60*1e3}wt(),wt(),Ct(),__name(getPathHash,"getPathHash"),__name(getBackupFileName,"getBackupFileName"),__name(getCommandCodeBasePath,"getCommandCodeBasePath"),__name(getFileHistoryPath,"getFileHistoryPath"),__name(getBackupFilePath,"getBackupFilePath"),__name(getAvailableDiskSpace,"getAvailableDiskSpace"),__name(hasEnoughDiskSpace,"hasEnoughDiskSpace"),__name(ensureDirectoryExists,"ensureDirectoryExists"),__name(atomicWriteFile,"atomicWriteFile"),__name(getFileSizeBytes,"getFileSizeBytes"),__name(fileExists,"fileExists"),__name(getCurrentTimestamp,"getCurrentTimestamp"),__name(truncateString2,"truncateString"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod"),rr();var as={maxFileSize:10485760,retentionDays:30},is=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...as,...n},this.status={enabled:!0,pausedReason:null,pausedAt:null},this.trackedState={files:new Map,versions:new Map},this.noticeDismissed=!1}getStatus(){return{...this.status}}getTrackedState(){return{files:new Map(this.trackedState.files),versions:new Map(this.trackedState.versions)}}shouldShowPausedNotice(){return null!==this.status.pausedReason&&!this.noticeDismissed}dismissPausedNotice(){this.noticeDismissed=!0}async checkAndResumeIfPossible(){if("disk_full"===this.status.pausedReason){const e=getFileHistoryPath({sessionId:this.sessionId});await hasEnoughDiskSpace({fileSizeBytes:104857600,targetPath:e})&&(this.status.pausedReason=null,this.status.pausedAt=null,this.noticeDismissed=!1)}}async backupFile(e){const{filePath:t}=e;if(await this.checkAndResumeIfPossible(),this.status.pausedReason)return{success:!1,backup:null,skipped:!0,skipReason:"disk_full"};if(!await fileExists({filePath:t})){const e=1,n={backupFileName:null,version:e,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,n),this.trackedState.versions.set(t,e),{success:!0,backup:n,skipped:!0,skipReason:"new_file"}}const n=await getFileSizeBytes({filePath:t});if(n>this.config.maxFileSize)return{success:!1,backup:null,skipped:!0,skipReason:"file_too_large"};const r=getFileHistoryPath({sessionId:this.sessionId});if(!await hasEnoughDiskSpace({fileSizeBytes:n,targetPath:r}))return this.status.pausedReason="disk_full",this.status.pausedAt=getCurrentTimestamp(),this.noticeDismissed=!1,{success:!1,backup:null,skipped:!0,skipReason:"disk_full"};try{const e=await x.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,o=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const s=getBackupFilePath({sessionId:this.sessionId,backupFileName:o});await atomicWriteFile({filePath:s,content:e});const a={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,a),this.trackedState.versions.set(t,n),{success:!0,backup:a,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:_n.FILE_HISTORY,heading:"File backup failed"}}),{success:!1,backup:null,skipped:!0,skipReason:"read_error"}}}async restoreFile(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName)return void(await fileExists({filePath:t})&&await x.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new ss(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:_n.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await x.readFile(r);await atomicWriteFile({filePath:t,content:o})}async verifyRestoreOperation(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName){if(!await fileExists({filePath:t}))return{canRestore:!0};try{return await x.access(t,x.constants.W_OK),{canRestore:!0}}catch{return{canRestore:!1,error:"Cannot delete file: permission denied"}}}const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});return await fileExists({filePath:r})?{canRestore:!0}:{canRestore:!1,error:`Backup file missing: ${n.backupFileName}`}}getTrackedFileBackups(){const e={};for(const[t,n]of this.trackedState.files)e[t]=n;return e}loadTrackedState(e){const{trackedFileBackups:t}=e;this.trackedState.files.clear(),this.trackedState.versions.clear();for(const[e,n]of Object.entries(t))this.trackedState.files.set(e,n),this.trackedState.versions.set(e,n.version)}async cleanupOrphanedBackups(e){const{referencedBackups:t}=e,n=getFileHistoryPath({sessionId:this.sessionId});let r=0;try{const e=await x.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await x.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await x.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}};wt(),rr();var cs=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new is({sessionId:t,config:r}),this.sessionStore=n||null,this.snapshots=[],this.config={maxFileSize:r?.maxFileSize||10485760,retentionDays:r?.retentionDays||30}}getFileHistoryManager(){return this.fileHistoryManager}setSessionStore(e){const{sessionStore:t}=e;this.sessionStore=t}async backupFile(e){const{filePath:t}=e,n=await this.fileHistoryManager.backupFile({filePath:t,sessionId:this.fileHistoryManager.getSessionId()});if(n.success&&this.snapshots.length>0){const e=this.snapshots[this.snapshots.length-1];e.trackedFileBackups=this.fileHistoryManager.getTrackedFileBackups(),this.sessionStore&&this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0}).catch(()=>{})}return{success:n.success,backup:n.backup}}async createSnapshot(e){const{messageId:t}=e,n={messageId:t,trackedFileBackups:{},timestamp:getCurrentTimestamp()};return this.snapshots.push(n),this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:n,isUpdate:!1}),n}async updateCurrentSnapshot(){if(0===this.snapshots.length)return;const e=this.snapshots[this.snapshots.length-1],t=this.fileHistoryManager.getTrackedFileBackups(),n=this.snapshots.length>1?this.snapshots[this.snapshots.length-2]:null,r=n?.trackedFileBackups||{},o={};for(const[e,n]of Object.entries(t)){const t=r[e];(!t||t.version!==n.version||t.backupFileName!==n.backupFileName)&&(o[e]=n)}e.trackedFileBackups=o,this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0})}listCheckpoints(){const e=[];for(let t=0;t<this.snapshots.length;t++){const n=this.snapshots[t];t>0&&this.snapshots[t-1];let r="";if(this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:n.messageId}),t=this.sessionStore.getMessageAtIndex({index:e});t&&(r=truncateString2({text:t.content,maxLength:100}))}const o=Object.keys(n.trackedFileBackups);let s=null;if(o.length>0){const e=o[0];n.trackedFileBackups[e]&&(s={additions:0,deletions:0,fileName:getFileName({filePath:e})})}e.push({messageId:n.messageId,timestamp:n.timestamp,userPrompt:r,fileCount:Object.keys(n.trackedFileBackups).length,filesModified:o,codeChanges:s})}return e.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime())}getSnapshot(e){const{messageId:t}=e;return this.snapshots.find(e=>e.messageId===t)||null}async restore(e){const{messageId:t,mode:n}=e;if(!this.getSnapshot({messageId:t}))return{success:!1,error:"Snapshot not found",filesRestored:0,filesDeleted:0,messagesRemoved:0};const r=this.snapshots.findIndex(e=>e.messageId===t);let o=0,s=0,a=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return trackError({error:sanitizeErrorForTelemetry({error:new Error(`Restore verification failed:\n${t.join("\n")}`),label:"restore_verification_failed"}),context:{component:_n.CHECKPOINT_MANAGER,heading:"Checkpoint restore verification failed","checkpoint.failures":t.length}}),{success:!1,error:`Restore verification failed:\n${t.join("\n")}`,filesRestored:0,filesDeleted:0,messagesRemoved:0};for(const t of e)await this.fileHistoryManager.restoreFile({filePath:t.filePath,backup:t.backup}),null===t.backup.backupFileName?s++:o++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(a=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const i=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&i.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&i.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:i}),{success:!0,filesRestored:o,filesDeleted:s,messagesRemoved:a}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}};wt();var ls=null;function initializeCheckpointService(e){const{sessionId:t}=e;return ls=new cs({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return ls?ls.backupFile({filePath:t}):{success:!0,backup:null}}function createFileEditError(e,t){const n=new Error(e);return n.name="FileEditError",n.code=t,n}async function editFile(t){const{filePath:n,oldValue:r,newValue:o,replaceAll:s=!1,replacementCount:a=1}=t;if(!n)throw createFileEditError("filePath is required","INVALID_PATH");if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!r)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==o)throw createFileEditError("newValue is required","INVALID_INPUT");if(!s&&a<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await w.access(n,b.F_OK|b.R_OK|b.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${n}`,"FILE_ACCESS_ERROR")}let i;try{const e=await readFileContent({absolutePath:n});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");i=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const c=(i.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===c)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let l,d;if(s)l=c;else if(l=a,l>c)throw createFileEditError(`Expected ${l} replacements, but only found ${c} occurrences`,"INSUFFICIENT_MATCHES");let u=0;if(s||l===c)d=i.split(r).join(o),u=c;else{d=i;for(let e=0;e<l;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+o+d.substring(e+r.length),u++)}}if(0===u)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await w.writeFile(n,d,"utf-8"),{path:n,replacementsCount:u,oldContent:i,newContent:d}}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}__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit"),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),wt(),__name(formatOutput2,"formatOutput");var ds={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=ns.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while editing file`}},"execute")};wt(),wt();var us=u.object({path:u.string().describe("The absolute path to the directory to read"),exclude:u.array(u.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:u.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});u.object({files:u.array(u.string()),directories:u.array(u.string())});var ms=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}};async function readDirectory(t){const{path:n,exclude:r=[],respectGitIgnore:o=!1}=t;if(!e.isAbsolute(n))throw new ms("Path must be absolute, not relative","INVALID_PATH");try{if(!(await P.stat(n)).isDirectory())throw new ms("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof ms)throw e;throw new ms(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await P.readdir(n);let s=[];o&&(s=await loadGitIgnorePatterns(n));const a=[...r,...s],i=[],c=[];for(const r of t){if(shouldIgnoreEntry(r,a))continue;const t=e.join(n,r);try{const e=await P.stat(t);e.isDirectory()?c.push(r):e.isFile()&&i.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:i.sort(),directories:c.sort()}}catch(e){if(e instanceof ms)throw e;throw new ms(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(t){const n=[];try{if(!await isInGitRepository(t))return n;let r=e.resolve(t);const o=await findGitRoot(t);for(;r&&isWithinGitRoot(r,o);){const t=e.join(r,".gitignore");try{const e=(await P.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch(e){}const o=e.dirname(r);if(o===r)break;r=o}}catch(e){}return n}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await P.stat(t)).isDirectory())return n}catch{}const t=e.dirname(n);if(t===n)throw new Error("Not in a git repository");n=t}}function isWithinGitRoot(t,n){const r=e.resolve(t),o=e.resolve(n);return"win32"===process.platform?r.toLowerCase().startsWith(o.toLowerCase()):r.startsWith(o)}function shouldIgnoreEntry(e,t){for(const n of t)if($e(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")}wt(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),wt(),__name(formatOutput3,"formatOutput");var gs={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=us.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while reading directory`}},"execute")};wt(),wt();var ps=u.object({filePath:u.string().describe("The absolute path where the file should be written"),content:u.string().describe("The content to write to the file")});async function writeFile2({filePath:e,content:t}){if(!s(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=r(e);return y(n)||await I(n,{recursive:!0}),await backupFileBeforeEdit({filePath:e}),await R(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}`}u.object({success:u.boolean(),message:u.string(),path:u.string().optional()}),wt(),__name(writeFile2,"writeFile"),wt(),__name(formatOutput4,"formatOutput");var hs={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=ps.parse(e),n=await writeFile2(t);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")};wt(),wt();var fs=u.object({include:u.array(u.string()).describe("Array of glob patterns to include files"),exclude:u.array(u.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:u.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:u.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:u.string().optional().describe("Base directory for relative paths. Default: current working directory")}),ys=u.object({filePath:u.string(),content:u.string(),fileType:u.string(),size:u.number()});u.object({content:u.string(),filesRead:u.array(u.string()),errors:u.array(u.object({file:u.string(),error:u.string()})),fileDetails:u.array(ys)});var Es=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}};wt();var ws=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const o=new Set;for(const s of e)try{(await De(s,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>o.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${s}": ${e}`)}return Array.from(o).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:n,exclude:r=[],gitIgnore:o=!0,defaultExclude:s=!0,targetDirectory:a=process.cwd()}=e;if(!n||0===n.length)throw new Es("At least one include pattern must be provided","NO_PATTERNS");const i=t.resolve(a),c={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];s&&e.push(...ws);const a=await findMatchingFiles({include:n,exclude:e,gitIgnore:o,targetDirectory:i});for(const e of a)try{const n=t.resolve(i,e),r=await readFileContent({absolutePath:n}),o=processFileResult({content:r,filePath:e});c.fileDetails.push(o),c.content+=`\n// File: ${e} (${r.fileType})\n`,c.content+=o.content,c.content+="\n",c.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);c.errors.push({file:e,error:n}),c.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return c}catch(e){if(e instanceof Es)throw e;throw new Es(`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"),wt(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var bs={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=fs.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while reading multiple files`}},"execute")};wt(),wt();var Ss=u.object({pattern:u.string().min(1,"Pattern is required"),include:u.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},u.array(u.string()).optional()),directory:u.string().optional()});wt(),wt();var ks=1e5,Cs=5e4;function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=A(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",a="";o.stdout?.on("data",e=>{try{const t=e.toString();if(s.length+t.length>ks)return a="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",void o.kill("SIGTERM");s+=t}catch(e){a+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,o.kill("SIGTERM")}}),o.stderr?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>Cs)return void(a+="\n[Error output truncated: too large]");a+=t}catch(e){a+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),o.on("close",e=>{0===e?n(s):1!==e||a?r(new Error(a||`Command failed with exit code ${e}`)):n("")}),o.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,o]=t;return{file:n,line:parseInt(r,10),column:1,content:o.trim(),match:o.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",o=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)o.splice(-1,0,"--glob",e);o.splice(-1,0,"--glob","!node_modules/**"),o.splice(-1,0,"--glob","!.git/**"),o.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:o,command:"rg"})}catch(s){if(!(s instanceof Error&&s.message.includes("ENOENT")))throw s;if(r="grep",o=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)o.splice(-1,0,"--include",e);o.splice(-1,0,"--exclude-dir=node_modules"),o.splice(-1,0,"--exclude-dir=.git"),o.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:o,command:"grep"})}if(!e.trim())return[];const s=e.trim().split("\n"),a=[];for(const e of s){const t=parseGrepLine(e);t&&a.push(t)}return a}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"),wt(),__name(formatGrepResults,"formatGrepResults");var vs={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=Ss.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while searching files`}},"execute")};wt(),wt();var Ts=u.object({pattern:u.string().min(1,"Pattern is required"),path:u.string().optional()}),As=class extends Error{static{__name(this,"GlobError")}code;constructor(e,t){super(e),this.name="GlobError",this.code=t}};async function globSearch(e){const{pattern:n,path:r="."}=e;if(!n)throw new As("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r),o=process.cwd(),s=o.endsWith(t.sep)?o:o+t.sep;if(e!==o&&!e.startsWith(s))throw new As("Search path must be within the current working directory","INVALID_PATH");const a=await De(n,{cwd:e,ignore:ht,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),i=await Promise.all(a.map(async n=>{const r=t.join(e,n);try{return{file:n,mtime:(await x.stat(r)).mtimeMs}}catch{return{file:n,mtime:0}}}));return i.sort((e,t)=>t.mtime-e.mtime),{files:i.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof As)throw e;if(e instanceof Error)throw new As(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new As("Unknown error occurred during file search","UNKNOWN_ERROR")}}function formatGlobResults(e){if(0===e.files.length)return"No files found matching pattern";const t=[],n=e.files.length;t.push(`Found ${n} file${1!==n?"s":""}`);for(const n of e.files)t.push(` ${n}`);return t.join("\n")}wt(),Ct(),__name(globSearch,"globSearch"),wt(),__name(formatGlobResults,"formatGlobResults");var Ps={name:"glob",description:"Searches for files in a directory tree using glob-style path patterns, enabling fast and flexible discovery of files across codebases of any size.\nThis tool matches file paths against glob patterns such as **/*.js or src/**/*.ts, making it ideal for locating files by name, extension, or directory structure without inspecting file contents. It performs recursive traversal where applicable and efficiently handles large repositories.\nResults are returned as a list of matching file paths, sorted by modification time, allowing you to quickly identify the most recently changed or relevant files.\nFile pattern matching can be refined using inclusive or exclusive glob expressions to narrow down results, improving performance and focus when working with large or complex projects.\nIt should be used when you need to find files based on naming or path patterns, explore the structure of an unfamiliar codebase, locate configuration or entry-point files, or prepare a targeted set of files for further inspection with tools like grep.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files. Supports wildcards: * matches any characters except /, ** matches any characters including / (for recursive search), ? matches single character, [abc] matches character set, {js,ts} matches alternatives. Examples: "**/*.ts" finds all TypeScript files recursively, "src/**/*.{js,jsx}" finds JavaScript files in src directory, "*.json" finds JSON files in current directory, "**/test/**/*.spec.ts" finds test spec files.'},path:{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=Ts.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while finding files`}},"execute")};wt(),wt();var xs=u.object({command:u.string().min(1,"Command cannot be empty"),args:u.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},u.array(u.string()).optional()),directory:u.string().optional(),timeout:u.preprocess(e=>"string"==typeof e?parseInt(e,10):e,u.number().optional())}),Is=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,a){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=a}};async function executeShellCommand(t){const{command:n,args:r=[],directory:o,timeout:s=3e4}=t,a=Date.now();if(!n.trim())throw new Is("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(e.isAbsolute(o))throw new Is("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=e.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await x.stat(i)).isDirectory())throw new Is(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof Is)throw e;throw new Is(`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((t,o)=>{let i="",c="",l=!1;const d=r.length>0?Ne([n,...r]):n,u=setTimeout(()=>{if(!l){m.kill("SIGTERM");const e=Date.now()-a;o(new Is(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",i,c,e))}},s),m=A(d,[],e);m.stdout?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>ks)return c="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void m.kill("SIGTERM");i+=t}catch(e){c+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,m.kill("SIGTERM")}}),m.stderr?.on("data",e=>{try{const t=e.toString();if(c.length+t.length>Cs)return void(c+="\n[Error output truncated: too large]");c+=t}catch(e){c+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),m.on("close",(e,n)=>{l=!0,clearTimeout(u);const r=Date.now()-a;0===e?t({stdout:i.trim(),stderr:c.trim(),exitCode:e,signal:n,duration:r}):o(new Is(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,i.trim(),c.trim(),r))}),m.on("error",e=>{l=!0,clearTimeout(u);const t=Date.now()-a;o(new Is(`Failed to start command: ${e.message}`,"START_FAILED",null,null,i.trim(),c.trim(),t))})})}catch(e){if(e instanceof Is)throw e;throw new Is(`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")}wt(),__name(executeShellCommand,"executeShellCommand"),wt(),__name(formatShellCommandResult,"formatShellCommandResult");var Rs={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=xs.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${pe.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${pe.cross} Error: ${e.message}`}return`${pe.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}wt(),wt(),__name(think,"think");var $s={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"string"==typeof e.todos?e.todos:JSON.stringify(e.todos)}wt(),wt(),__name(todoWrite,"todoWrite");var Ds={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};async function askUserQuestion(e,t){if(!e.questions||0===e.questions.length)return JSON.stringify({error:"No questions provided"});for(let t=0;t<e.questions.length;t++){const n=e.questions[t];if(!n.question?.trim()||!n.header?.trim()||!n.options)return JSON.stringify({error:`Question ${t+1} is missing required fields (question, header, options)`});if(n.options.length<2||n.options.length>4)return JSON.stringify({error:`Question ${t+1} must have 2-4 options`});for(const e of n.options)if(!e.label?.trim()||!e.description?.trim())return JSON.stringify({error:`Question ${t+1} has an option with missing label or description`});if(n.header.length>12)return JSON.stringify({error:`Question ${t+1} header exceeds maximum length of 12 characters`})}if(!t?.onQuestionRequest)return JSON.stringify({error:"Question request callback not available"});if(t.abortSignal?.aborted)return JSON.stringify({error:"Interrupted by user"});try{const n=await t.onQuestionRequest(e);return t.abortSignal?.aborted?JSON.stringify({error:"Interrupted by user"}):JSON.stringify(n)}catch(e){return e instanceof Error?JSON.stringify({error:e.message}):JSON.stringify({error:"Failed to get user response"})}}function isErrorResponse(e){return"error"in e&&"string"==typeof e.error}function formatOutput6(e){const{result:t,params:n}=e;if(isErrorResponse(t))return`Error: ${t.error}`;if(!t.answers||0===t.answers.length)return"User declined to answer questions";const r=t.answers.filter(e=>e.selectedOptions&&Array.isArray(e.selectedOptions)&&e.selectedOptions.length>0);if(0===r.length)return"User declined to answer questions";const o=[];return r.forEach(e=>{let t=`Question ${e.questionIndex+1}`;n?.questions?.[e.questionIndex]&&(t=n.questions[e.questionIndex].question||t);const r=e.selectedOptions.join(", ");o.push(`${t} → ${r}`)}),o.join("\n")}wt(),wt(),__name(askUserQuestion,"askUserQuestion"),wt(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var Ns={name:"ask_user_question",description:'Use this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- Users will always be able to select "Type something" to provide custom text input\n- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label\n- Use multiSelect: true to allow multiple answers to be selected for a question',acceptsCallbacks:!0,input_schema:{type:"object",properties:{questions:{type:"array",description:"Questions to ask the user",items:{type:"object",properties:{question:{type:"string",description:"The complete question to ask the user. Should be clear, specific, and end with a question mark."},header:{type:"string",description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'},options:{type:"array",description:'The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Type something" option, that will be provided automatically.',items:{type:"object",properties:{label:{type:"string",description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."},description:{type:"string",description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}},required:["label","description"]}},multiSelect:{type:"boolean",description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."}},required:["question","header","options"]}}},required:["questions"]},execute:__name(async(e,t)=>{const n=await askUserQuestion(e,{onQuestionRequest:t?.onQuestionRequest,abortSignal:t?.abortSignal});try{return formatOutput6({result:JSON.parse(n),params:e})}catch{return n}},"execute")};wt(),wt();var Fs=u.object({port:u.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:u.number().int().positive().optional()}).refine(e=>void 0!==e.port&&void 0===e.pid||void 0===e.port&&void 0!==e.pid,{message:"Exactly one of port or pid must be provided"}),Ls=class extends Error{static{__name(this,"KillshellError")}code;pid;port;constructor(e,t,n,r){super(e),this.name="KillshellError",this.code=t,this.pid=n,this.port=r}};function isUnixLike(){const e=process.platform;return"darwin"===e||"linux"===e}function isWindows(){return"win32"===process.platform}async function executeCommand(e,t){return new Promise((n,r)=>{const o=A(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let s="",a="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{a+=e.toString()}),o.on("close",e=>{0===e?n(s.trim()):r(new Error(a.trim()||s.trim()))}),o.on("error",e=>{r(e)})})}async function findPidByPort(e){try{if(isUnixLike()){const t=(await executeCommand("lsof",["-ti",`:${e}`,"-sTCP:LISTEN"])).trim().split("\n")[0];if(!t||!/^\d+$/.test(t))return null;const n=parseInt(t,10);return isNaN(n)?null:n}if(isWindows()){const t=(await executeCommand("netstat",["-ano"])).split("\n");for(const n of t){const t=n.trim();if(!t)continue;const r=t.split(/\s+/);if(r.length<5)continue;if("LISTENING"!==r[3])continue;const o=r[1].match(/:(\d+)$/);if(!o)continue;const s=parseInt(o[1],10);if(isNaN(s)||s!==e)continue;const a=parseInt(r[r.length-1],10);if(!isNaN(a))return a}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new Ls(`No process found listening on port ${e.port}`,"NO_PROCESS_FOUND",void 0,e.port);t=r}else void 0!==e.pid&&(t=e.pid);if(!t)throw new Ls("Unable to determine target process","INVALID_TARGET");const r=await getProcessName(t);try{await killProcess(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new Ls(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}function formatKillshellResult(e){const t=[];return t.push(`${pe.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}wt(),__name(isUnixLike,"isUnixLike"),__name(isWindows,"isWindows"),__name(executeCommand,"executeCommand"),__name(findPidByPort,"findPidByPort"),__name(getProcessName,"getProcessName"),__name(isProcessAlive,"isProcessAlive"),__name(waitForProcessTermination,"waitForProcessTermination"),__name(killProcess,"killProcess"),__name(executeKillshell,"executeKillshell"),wt(),__name(formatKillshellResult,"formatKillshellResult");var Os={name:"kill_shell",description:"Terminates processes by port number or PID, useful for freeing occupied ports or stopping stuck development servers. Attempts graceful termination first (SIGTERM/taskkill), then forces if needed. Use with caution - terminating system processes may cause instability.",acceptsCallbacks:!0,input_schema:{type:"object",properties:{port:{type:"number",description:"Port number (1-65535) to free by terminating the listening process. Automatically finds and kills the process using this port."},pid:{type:"number",description:"Process ID to terminate directly. Use when you know the exact PID to kill."}},required:[]},execute:__name(async(e,t)=>{try{const n=Fs.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?`${pe.cross} Permission denied: Process termination was not approved`:formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while killing process`}},"execute")};wt(),wt(),wt(),wt(),wt(),Ct(),wt(),wt();var _s=["explore","plan","review","general"],Ms=[{name:"explore",description:"Use this for codebase exploration, search, or understanding tasks that require multiple file operations",tools:"glob, grep, read_file, read_directory, read_multiple_files, think",systemPrompt:'You are a codebase explorer. Your prompt will specify depth level and what information is needed.\n\nTOOLS AVAILABLE:\n- glob: Find files by patterns\n- grep: Search code for keywords/patterns\n- read_file: Read specific files\n- read_directory: List directory contents\n- read_multiple_files: Read many files efficiently\n- think: Reason through findings\n\nDEPTH LEVELS:\n- quick: 1-2 files, answer the specific question only\n- medium: 3-5 files, understand the main component and context\n- thorough: 10+ files, comprehensive understanding\n\nINSTRUCTIONS:\n1. Look for "Depth: [level]" in the prompt (usually on line 2)\n2. Identify exactly what information is needed (specified in the prompt)\n3. Use only the file operations needed to get that information\n4. Stop when you have the requested information\n\nIf no depth level specified, default to "quick".\n\nRESPONSE FORMAT:\n- Provide exactly what was requested\n- Include relevant file paths and code sections\n- Match your depth to the specified level\n- Stop when done - don\'t over-explore',location:"personal",filePath:"__builtin__"}];function isReservedAgentName(e){return!!e&&_s.includes(e.toLowerCase())}function getRootAgentDir(){return t.join(g.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await x.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await x.readFile(o,"utf-8"),{data:a,content:i}=Re(s),c=a.name||r.replace(".md","");if(isReservedAgentName(c))return null;let l=a.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:c,description:a.description||"",tools:l,systemPrompt:i.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,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(isReservedAgentName,"isReservedAgentName"),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents"),wt(),Ct(),Lt(),En(),Dt(),wt();var Us=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)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=1.1*estimateTextTokens(JSON.stringify(n.input)));else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));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.max(0,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 checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?(estimateTokens(e),"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."):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 sleep(e){const{delay:t,signal:n}=e;return new Promise((e,r)=>{if(n?.aborted)return r(new Error("Interrupted by user"));const o=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(o),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(function getOversizedOutputError(e,t){return"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."},"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),wt(),__name(sleep,"sleep"),wt(),mn();var js=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${pe.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${pe.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${pe.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${pe.warning} ${e}`)}debug(e){dlog(`[${this.prefix}] ${e}`)}};function getEnterpriseMemoryPath(){switch(m.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return e.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const t=m.homedir();return e.join(t,".commandcode","AGENTS.md")}function getProjectMemoryPaths(t){return[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:y(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(y(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:y(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return y(e)&&k(e).isFile()?await P.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}async function processImports(t,n,r=0,o=5){if(r>=o)return t;const s=[],a=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(s.push(e),`__CODE_BLOCK_${s.length-1}__`)),i=Array.from(a.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let c=a;for(const t of i){const s=t[1];let a=s;s.startsWith("~/")?a=e.join(m.homedir(),s.slice(2)):e.isAbsolute(s)||(a=e.resolve(e.dirname(n),s));const i=await loadMemoryFile(a);if(i){const e=await processImports(i,a,r+1,o);c=c.replace(t[0],`\n# Imported from ${s}\n${e}\n`)}}return c=c.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>s[parseInt(t)]),c}async function loadAllMemories(t,n){const r=new Map,o=getEnterpriseMemoryPath();if(y(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const s=getUserMemoryPath();if(y(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const a=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of a)if(y(e)){const t=await loadMemoryFile(e);if(t){const n=await processImports(t,e);r.set(e,n)}break}if(n&&n.length>0)for(const o of n){const n=e.isAbsolute(o)?e.dirname(o):e.dirname(e.resolve(t,o));if(n.startsWith(t)&&n!==t){const o=[];let s=n;for(;s.startsWith(t)&&s!==t;)o.push(s),s=e.dirname(s);for(const t of o.reverse()){const n=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of n)if(y(e)&&!r.has(e)){const t=await loadMemoryFile(e);if(t){const n=await processImports(t,e);r.set(e,n)}break}}}}return r}async function openInEditor(t){const n=process.env.EDITOR||process.env.VISUAL||"code",r=e.dirname(t);return y(r)||await P.mkdir(r,{recursive:!0}),y(t)||await P.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const o=A(n,[t],{stdio:"inherit",shell:!0});o.on("exit",t=>{0===t?e():r(new Error(`Editor exited with code ${t}`))}),o.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),r(e)})})}async function initProjectMemory(t){const n=e.join(t,"AGENTS.md");return y(n)||await P.writeFile(n,"# 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"),n}async function getMemoryContent(t){try{const n=process.cwd(),r=await loadAllMemories(n,t);if(0===r.size)return null;const o=[],s=getEnterpriseMemoryPath(),a=getUserMemoryPath(),i=[e.join(n,"AGENTS.md"),e.join(n,".commandcode","AGENTS.md")];r.has(s)&&o.push(`# Memory from: ${s}\n\n${r.get(s)}`),r.has(a)&&o.push(`# Memory from: ${a}\n\n${r.get(a)}`);for(const e of i)if(r.has(e)){o.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===s||e===a||i.includes(e)||o.push(`# Memory from: ${e}\n\n${t}`);return o.join("\n\n---\n\n")}catch(e){return null}}wt(),Ct(),__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"),wt(),Ct(),rr();var Bs=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(g.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Le(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const n=_SessionManager.getCurrentProjectDirName();this.projectPath=t.join(_SessionManager.getProjectsBasePath(),n),this.sessionFilePath=t.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=v("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await x.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"project_init_failed"}),context:{component:_n.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await x.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{if(0===e.length)return;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 x.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 n=e||this.sessionId,r=t.join(this.projectPath,`${n}.jsonl`);try{const e=(await x.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let n=0;for(const r of e)try{const e=JSON.parse(r);"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){n++,console.error("Error parsing session line:",e)}return{messages:t,corruptedLines:n,totalLines:e.length}}catch(e){return console.error("Error loading messages:",e),{messages:[],corruptedLines:0,totalLines:0}}}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=Xo(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=Xo(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 n=e||this.sessionId,r=t.join(this.projectPath,`${n}.jsonl`);try{const e=(await x.readFile(r,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);t.push(e)}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading session:",e),[]}}convertToFeedEntries(e){return e.map(e=>{const t={id:e.id,timestamp:new Date(e.timestamp).getTime(),role:e.role,metadata:e.metadata};return"object"==typeof e.content&&null!==e.content&&"input"in e.content?{...t,input:e.content.input,output:e.content.output,...e.content.name?{name:e.content.name}:{},...e.content.command?{command:e.content.command}:{}}:{...t,input:"string"==typeof e.content?e.content:JSON.stringify(e.content)}})}convertToAnthropicMessages(e){return e.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>{let t;if(t="string"==typeof e.content?e.content:e.content&&"object"==typeof e.content?e.content.input||JSON.stringify(e.content):"","user"===e.role&&e.metadata?.fileReferences)try{t=reconstructContent(t,e.metadata.fileReferences)}catch(e){console.error("Failed to reconstruct file content from session:",e)}return{role:e.role,content:t}})}static async isProjectInitialized(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return(await x.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await x.mkdir(r,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),n=t.join(_SessionManager.getProjectsBasePath(),e);try{try{await x.access(n)}catch{return[]}const e=(await x.readdir(n)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),r=[];for(const o of e){const e=o.replace(".jsonl",""),s=t.join(n,o);try{const t=await x.stat(s),o=(await x.readFile(s,"utf-8")).trim().split("\n").filter(e=>e.trim());if(o.length>0){let s="",a="";const i=JSON.parse(o[0]);i.gitBranch&&(a=i.gitBranch);for(const e of o){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)s=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){s=e.text;break}}else t.content?.input&&(s=t.content.input);if(s)break}}r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:s||"No messages",messageCount:o.length,projectPath:n,gitBranch:a||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return r.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const n=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await x.writeFile(n,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=t.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await x.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await x.unlink(e)}catch(e){}}getCheckpointsFilePath(){return t.join(this.projectPath,`${this.sessionId}.checkpoints.jsonl`)}async saveSnapshot(e){const{snapshot:t,isUpdate:n}=e,r=this.getCheckpointsFilePath();try{await this.initializeProject();const e={type:"file-history-snapshot",messageId:t.messageId,snapshot:t,isSnapshotUpdate:n};if(n){let n=[];try{n=(await x.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const o=n.findIndex(e=>e.messageId===t.messageId);-1!==o?n[o]=e:n.push(e);const s=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await x.writeFile(r,s)}else await x.appendFile(r,JSON.stringify(e)+"\n")}catch(e){console.error("Failed to save checkpoint snapshot:",e)}}async loadSnapshots(){const e=this.getCheckpointsFilePath();try{const t=(await x.readFile(e,"utf-8")).trim().split("\n").filter(e=>e.trim()),n=[];for(const e of t)try{const t=JSON.parse(e);"file-history-snapshot"===t.type&&n.push(t.snapshot)}catch{}return n}catch{return[]}}async deleteSnapshotsAfter(e){const{messageId:t,inclusive:n=!1}=e,r=this.getCheckpointsFilePath();try{const e=(await x.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),o=e.findIndex(e=>e.messageId===t);if(-1===o)return;const s=(n?e.slice(0,o):e.slice(0,o+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await x.writeFile(r,s)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let o="";if("string"==typeof r.message.content)o=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(o+=e.text);return{messageId:r.meta.messageId||crypto.randomUUID(),content:o}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return r.length>0&&await this.saveMessages(r),r}};hn();var Ws=new js("AgentExecutor");function agentToTool(t,n){const{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}=n;return{name:t.name,description:t.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object"}}},required:["messages"]},execute:__name(async(n,i)=>{let c=null;const l=Date.now();let d=null;try{let u=getAvailableTools(t,{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}),m=Date.now();const g=10,p=[];if(i?.onFeedUpdate){const e=Xo(t.name,n);c=Go({name:t.name,input:e}),i.onFeedUpdate(c)}d=setInterval(()=>{if(i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{...c.metadata,elapsedSeconds:t}},i.onFeedUpdate(c)}},1e3);const h=await getConfiguredProvider(),f=await isOAuthEnforced();let y;h===ut.ANTHROPIC&&(y=await Rt.getValidAccessToken(),validateOAuthToken({token:y,provider:h}));const E=getApiBaseUrl(),w=new no({baseUrl:E});let b=0;const S=[];let k=n?.messages;if("string"==typeof k)try{k=JSON.parse(k)}catch(e){k=[]}if(Array.isArray(k)&&k.length>0)for(const e of k)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&S.push({role:"user",content:t})}const C={stream:!0,messages:S,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:u,model:`anthropic:${getConfiguredModel()}`},v=await isTasteLearningEnabled(),T={[it.PROJECT_SLUG]:Bs.getCurrentProjectDirName(),[it.TASTE_LEARNING]:v.toString(),[it.INTERNAL_TEAM_FLAG_HEADER]:f.toString()};y&&(T[it.OAUTH_TOKEN]=`Bearer ${y}`);const A=getEnvironmentContext(),P=await getMemoryContent([]),x=crypto.randomUUID();let I="",R=!0;const $=__name(()=>{Ws.debug("[Agent] Abort signal triggered, stopping immediately"),R=!1,d&&(clearInterval(d),d=null)},"abortHandler");i?.abortSignal&&i.abortSignal.addEventListener("abort",$);try{for(;R;){if(i?.abortSignal?.aborted)throw Ws.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:w,body:{mode:"custom-agent",config:A,memory:P,threadId:x,params:{...C,messages:S}},headers:T,abortSignal:i?.abortSignal,onTextDelta:__name(e=>{b+=estimateTokens(e);const t=Date.now();if(i?.onFeedUpdate&&c&&t-m>=g){const e=Math.floor((t-l)/1e3);c={...c,metadata:{...c.metadata,tokensUsed:b,elapsedSeconds:e}},i.onFeedUpdate(c),m=t}},"onTextDelta")});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(b=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if(I=t.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(t,i):t.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===n.length){const e=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);e.length>0&&S.push({role:"assistant",content:e}),R=!1;break}const r=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);r.length>0&&S.push({role:"assistant",content:r});const o=[],s=new Set;let a=!1;for(const t of n){if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{if(["edit_file","write_file","create_file","delete_file","shell_command"].includes(t.name)&&i?.onPermissionRequest){if(d&&(clearInterval(d),d=null),!await i.onPermissionRequest(t.name,n)){Ws.debug(`Permission denied for tool: ${t.name}`),a=!0;break}d=setInterval(()=>{if(i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{...c.metadata,elapsedSeconds:t}},i.onFeedUpdate(c)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let o=!1;const s=["path","file_path","absolutePath","filePath","directory","folder"];for(const t of s)if(t in r&&"string"==typeof r[t]){const n=r[t];if(!e.isAbsolute(n)){const s=e.resolve(process.cwd(),n);r[t]=s,o=!0,Ws.debug(`Converted '${t}': '${n}' -> '${s}'`)}}"paths"in r&&Array.isArray(r.paths)&&(r.paths=r.paths.map(t=>"string"!=typeof t||e.isAbsolute(t)?t:(o=!0,e.resolve(process.cwd(),t)))),o?(n=r,Ws.debug(`Resolved input for ${t.name}: ${Xo(t.name,n)}`)):Ws.debug(`No path resolution needed for ${t.name}: ${Xo(t.name,n)}`)}if(i?.onFeedUpdate&&c){const e=Xo(t.name,n);p.push({name:t.name,input:e}),p.length>3&&p.shift();const r=Date.now(),o=Math.floor((r-l)/1e3);c={...c,metadata:{isAgent:!0,status:"running",startTime:l,tokensUsed:b,elapsedSeconds:o,recentTools:[...p]}},Ws.debug(`Updating agent with recentTools (${p.length} tools): ${JSON.stringify(p)}`),i.onFeedUpdate(c)}const r=await executeTool(t.name,n,{abortSignal:i?.abortSignal});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");const u=checkToolOutputTokensLimit(r,t.name);if(o.push({type:"tool_result",tool_use_id:t.id,content:u}),s.add(t.id),i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{isAgent:!0,status:"running",startTime:l,tokensUsed:b,elapsedSeconds:t,recentTools:[...p]}},i.onFeedUpdate(c)}Ws.debug(`Tool executed successfully: ${t.name}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";o.push({type:"tool_result",tool_use_id:t.id,content:`Error: ${n}`,is_error:!0}),s.add(t.id),Ws.error(`Tool execution failed: ${t.name} - ${n}`)}}if(a){const e=S[S.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?s.has(e.id):"text"===e.type);t.length>0?e.content=t:S.pop()}R=!1;break}const u=[...o];S.push({role:"user",content:u})}}finally{i?.abortSignal&&i.abortSignal.removeEventListener("abort",$)}if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&c){const e=Date.now(),t=(e-l)/1e3;c={...c,output:I||"DONE",metadata:{isAgent:!0,status:"done",startTime:l,endTime:e,tokensUsed:b,elapsedSeconds:t}},i.onFeedUpdate(c)}return I||"DONE"}catch(e){if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&c){const t=Date.now(),n=(t-l)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||i?.abortSignal?.aborted;c={...c,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:l,endTime:t,tokensUsed:c?.metadata?.tokensUsed||0,elapsedSeconds:n}},i.onFeedUpdate(c)}throw e}},"execute")}}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=t;let a=[];if("*"===e.tools)a=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=s[e];if(!t&&o.has(e)&&(t=e),t){const e=o.get(t);if(e)a.push(e);else{const e=r.find(e=>e.name===t);e&&a.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=s[t];if(!e&&o.has(t)&&(e=t),e){const t=o.get(e);if(t)a.push(t);else{const t=r.find(t=>t.name===e);t&&a.push(t)}}}return a}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:s}=e;let a=null;for(let e=0;e<5;e++){if(o?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:ct.ALPHA.GENERATE,signal:o,headers:r}),a=Fe.fromReadableStream(e);s&&a.on("text",s);let i=null;a.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await a.finalMessage();if(i)throw i;return c}catch(t){if(a=t,o?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Ws.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:o})}}throw a||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 Kr&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof Yr||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 Kr&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof Yr||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=Xo(r.name,r.input),n=So(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 Hs=new Map,zs=null;function initializeAgentManager(e){zs=e}async function loadAgentTools(){if(!zs)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Hs.clear();for(const e of Ms){const t=agentToTool(e,zs);Hs.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,zs);Hs.set(t.name,t)}}async function getAgentTools(){return 0===Hs.size&&await loadAgentTools(),Array.from(Hs.values())}async function getAgentTool(e){return 0===Hs.size&&await loadAgentTools(),Hs.get(e)}function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,o=e.join(r,".commandcode","taste"),s=e.normalize(e.resolve(r,n)),a=e.normalize(o);return s.startsWith(a)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),o=e.normalize(e.join(m.homedir(),".commandcode","taste"));let s=null;if(n.startsWith(r)?s=r:n.startsWith(o)&&(s=o),!s)return{isTaste:!1};if(!n.endsWith("taste.md"))return{isTaste:!1};const a=e.relative(s,n).split(e.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"),wt(),Ct(),__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"),rr();var Gs=[ts,ds,gs,hs,bs,vs,Ps,Rs,$s,Ds,Ns,Os],qs=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],Vs=new Map(Gs.map(e=>[e.name,e])),Ks=new Set([...Gs.map(e=>e.name),...qs.map(e=>e.name)]);function isAgentTool(e){return!Ks.has(e)}async function executeTool(e,t,n){let r=Vs.get(e);if(r||(r=await getAgentTool(e)),!r){const t=await getAgentTools(),n=[...Array.from(Vs.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: ",""))}const o=trackToolStart({toolName:e});try{let s;return s=(!Vs.has(e)||!0===r.acceptsCallbacks)&&n?await r.execute(t,n):await r.execute(t),o.end({status:"success"}),s}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message){const t=sanitizeErrorForTelemetry({error:e,label:"tool_interrupted"});throw o.end({status:"error",error:t}),e}if(e instanceof Error){const t=sanitizeErrorForTelemetry({error:e,label:"tool_error"});return o.end({status:"error",error:t}),`Error: ${e.message}`}return o.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(){return[...Gs.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})),...qs]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var Js={};Gs.forEach(e=>{Js[e.name]=toPascalCase(e.name)}),qs.forEach(e=>{Js[e.name]=toPascalCase(e.name)});var Ys={};function parseEmbeddedErrorJSON(e){const t=e.indexOf("{");if(-1===t)return null;try{const n=JSON.parse(e.slice(t));if(n?.error?.message){const r=e.slice(0,t).trim();return{status:/^\d+$/.test(r)?Number(r):null,type:n.error.type||null,message:n.error.message}}}catch{}return null}function parseErrorLine(e){try{const t=JSON.parse(e);if("error"===t?.type&&t?.error?.type&&t?.error?.message)return{type:t.error.type,message:t.error.message}}catch{}return null}function interceptStreamErrors(e){const{responseStream:t}=e;let n=null,r="";const o=new TextDecoder,s=new TransformStream({transform(e,t){const s=o.decode(e,{stream:!0});r+=s;const a=r.split("\n");r=a.pop()??"";for(const e of a){const r=e.trim();if(!r){t.enqueue((new TextEncoder).encode(e+"\n"));continue}const o=parseErrorLine(r);if(o)return n=o,void t.error(new Error(`Error: Stream error: ${o.type} - ${o.message}`));t.enqueue((new TextEncoder).encode(e+"\n"))}},flush(e){const t=r.trim();if(t){const o=parseErrorLine(t);if(o)return n=o,void e.error(new Error(`Error: Stream error: ${o.type} - ${o.message}`));e.enqueue((new TextEncoder).encode(r))}}});return{stream:t.pipeThrough(s),getStreamError:__name(()=>n,"getStreamError")}}Object.entries(Js).forEach(([e,t])=>{Ys[t]=e}),initializeAgentManager({clientTools:Gs,serverTools:qs,toolsMap:Vs,displayNameToToolName:Ys}),wt(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors"),rr(),Ct(),Dt(),hn(),En(),wt(),Ct(),Lt(),mn(),wt();var Qs=new class extends Oe{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;get observerHasRun(){return this._observerHasRun}markObserverRun(){this._observerHasRun=!0}get importHasStarted(){return this._importHasStarted}markImportStarted(){this._importHasStarted=!0}get learningComplete(){return this._learningComplete}markLearningComplete(){this._learningComplete=!0,this.emit("learning-complete")}addEvent(e){const{type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d}=e,u={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d};this.events.unshift(u),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",u)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}};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}),s=new Map(r.map(e=>[e.text,e.confidence])),a=[],i=[],c=[];return o.forEach(e=>{const t=s.get(e.text);void 0===t?a.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:a,upgraded:i,downgraded:c}}wt(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings"),hn(),En(),rr();var Zs=new js("LearningAgent"),Xs=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=3;request;projectRoot;tasteDir;sessionId;abortSignal;constructor(t){this.request=t.request,this.sessionId=t.sessionId,this.projectRoot=t.projectRoot,this.tasteDir=e.join(t.projectRoot,".commandcode","taste")}updateRequest(e){this.request=e}setAbortSignal(e){this.abortSignal=e}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)return this.pendingMessages=t,{success:!0};if(0===t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length)return{success:!0};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)}return{success:!0}}catch(e){const n=e instanceof Error?e.message:String(e);return dlog(`[LearningAgent] ERROR: ${n}`),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learning_pass_failed"}),context:{component:_n.LEARNING_AGENT,heading:"Learning pass failed"}}),Qs.addEvent({type:"error",message:"learning pass failed",details:n}),this.lastProcessedMessageIndex=t.length-1,{success:!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)];Qs.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),s=t.length-this.lastProcessedMessageIndex-1,a=Math.max(20,s),i=Math.max(0,t.length-a),c=t.slice(i);let l=0,d=!1;dlog(`[LearningAgent] analyzing ${s} new messages for patterns`);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){const e=await this.callLearningAPI({conversation:u}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.name).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&Zs.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Qs.addEvent({type:"no_learnings",message:"no changes to taste"}),Qs.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{this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",s="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(s=String(e.filePath||e.file_path||""),s)try{o=await h.promises.readFile(s,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const a=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&s)try{i=await h.promises.readFile(s,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=s.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:o,newText:i});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{Qs.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Qs.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Qs.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:a})}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(t){const{toolName:n,input:r}=t,o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(!o||!r[o])return;const s=String(r[o]);if(e.isAbsolute(s))throw new Error(`Security: ${n} received absolute path. Only taste-relative paths are allowed (e.g., ".commandcode/taste/cli/taste.md" or ".commandcode/taste/taste.md"). Attempted: ${s}`);const a=e.normalize(s);if(a.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${s}`);const i=e.join(this.tasteDir,a);if(!e.normalize(i).startsWith(this.tasteDir))throw new Error(`Security: ${n} can only access files within .commandcode/taste/. Attempted: ${s}`)}adjustPathsForTaste(t){const{toolName:n,input:r}=t,o={...r},s={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(s&&o[s]){const t=String(o[s]);let r;const a="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)&&t.startsWith(this.tasteDir))if(a){if(!this.isValidTasteFilePath(t))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${t}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);r=t}else r=t;else{if(e.isAbsolute(t))throw new Error(`Invalid path: Absolute path outside taste directory: ${t}`);const n=e.normalize(t);if(n.startsWith(".."))throw new Error(`Security: Path traversal attempt detected: ${t}`);if(r=n.startsWith(".commandcode/taste")||n.startsWith(".commandcode"+e.sep+"taste")?n.replace(/^\.commandcode[/\\]taste/,this.tasteDir):e.join(this.tasteDir,n),r=e.normalize(r),!r.startsWith(this.tasteDir))throw new Error(`Security: Resolved path escapes taste directory: ${t} -> ${r}`);if(a&&!this.isValidTasteFilePath(r))throw new Error(`Invalid adjusted path: ${r}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}o[s]=r}return o}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 t=e.join(this.tasteDir,"taste.md");h.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!h.existsSync(t))return!1;const n=h.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let o=n;for(const t of r){const n=t.name.toLowerCase().replace(/\s+/g,"-"),r=e.join(this.tasteDir,n),s=e.join(r,"taste.md");h.mkdirSync(r,{recursive:!0}),Qs.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const a=`# ${t.name}\n${t.learnings.join("\n")}\n`;h.writeFileSync(s,a,"utf-8");const i=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;o=o.replace(t.fullSection,i)}return h.writeFileSync(t,o,"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(t){const{dir:n,prefix:r}=t,o=h.readdirSync(n,{withFileTypes:!0});let s="";for(let t=0;t<o.length;t++){const a=o[t],i=t===o.length-1,c=i?"└── ":"├── ";if(a.isDirectory()){s+=`${r}${c}${a.name}/\n`;const t=r+(i?" ":"│ ");s+=await this.buildTree({dir:e.join(n,a.name),prefix:t})}else if("taste.md"===a.name){const t=(h.readFileSync(e.join(n,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;s+=`${r}${c}${a.name} (${t} learnings)\n`}else s+=`${r}${c}${a.name}\n`}return s}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===ut.ANTHROPIC&&(o=await Rt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[it.PROJECT_SLUG]:Bs.getCurrentProjectDirName(),[it.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[it.OAUTH_TOKEN]=`Bearer ${o}`);const a=await this.getTasteTools(),i=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${i})`);const c={conversation:t,tools:a,model:i,threadId:this.sessionId};let l=0,d=null;for(;l<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:ct.ALPHA.TASTE.LEARN,body:c,headers:s,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),l++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${d.message}`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_client_error"}),context:{component:_n.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(l>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:_n.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":l}}),d;const n=1e3*Math.pow(2,l);dlog(`[LearningAgent] retrying API call (${l}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw d||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return h.existsSync(r)}};wt(),Ct(),Lt(),Dt(),hn(),En(),mn();var ea="claude-haiku-4-5-20251001",ta=class{static{__name(this,"CompactAgent")}request;sessionId;maxApiRetries=3;constructor(e){this.request=e.request,this.sessionId=e.sessionId}updateRequest(e){this.request=e}async compactMessages(e){const{messages:t}=e;dlog(`[CompactAgent] compacting ${t.length} messages`);try{const e=await this.callCompactAPI({messages:t});return dlog(`[CompactAgent] compaction complete: ${e.summary.length} chars`),e}catch(e){throw dlog(`[CompactAgent] ERROR: ${e instanceof Error?e.message:String(e)}`),e}}async callCompactAPI(e){const{messages:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===ut.ANTHROPIC&&(o=await Rt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[it.PROJECT_SLUG]:Bs.getCurrentProjectDirName(),[it.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[it.OAUTH_TOKEN]=`Bearer ${o}`);const a=t.map(e=>{const t=e.role;let n="";return"string"==typeof e.content?n=e.content:Array.isArray(e.content)&&(n=e.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("\n")),`[${t}]: ${n}`}).join("\n\n"),i={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],system:"Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\nThis summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.\n\nBefore providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:\n\n1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:\n - The user's explicit requests and intents\n - Your approach to addressing the user's requests\n - Key decisions, technical concepts and code patterns\n - Specific details like:\n - file names\n - full code snippets\n - function signatures\n - file edits\n - Errors that you ran into and how you fixed them\n - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.\n\nYour summary should include the following sections:\n\n1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail\n2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.\n3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.\n4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.\n6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.\n7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.\n8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.\n9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.\n If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.\n\nHere's an example of how your output should be structured:\n\n<example>\n<analysis>\n[Your thought process, ensuring all points are covered thoroughly and accurately]\n</analysis>\n\n<summary>\n1. Primary Request and Intent:\n [Detailed description]\n\n2. Key Technical Concepts:\n - [Concept 1]\n - [Concept 2]\n - [...]\n\n3. Files and Code Sections:\n - [File Name 1]\n - [Summary of why this file is important]\n - [Summary of the changes made to this file, if any]\n - [Important Code Snippet]\n - [File Name 2]\n - [Important Code Snippet]\n - [...]\n\n4. Errors and fixes:\n - [Detailed description of error 1]:\n - [How you fixed the error]\n - [User feedback on the error if any]\n - [...]\n\n5. Problem Solving:\n [Description of solved problems and ongoing troubleshooting]\n\n6. All user messages:\n - [Detailed non tool use user message]\n - [...]\n\n7. Pending Tasks:\n - [Task 1]\n - [Task 2]\n - [...]\n\n8. Current Work:\n [Precise description of current work]\n\n9. Optional Next Step:\n [Optional Next step to take]\n\n</summary>\n</example>\n\nPlease provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.\n\nThere may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:\n<example>\n## Compact Instructions\nWhen summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.\n</example>\n\n<example>\n# Summary instructions\nWhen you are using compact - please focus on test output and code changes. Include file reads verbatim.\n</example>",messages:[{role:"user",content:`Please summarize the following conversation.\n\n${a}`}],model:`anthropic:${ea}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let c=0,l=null;for(;c<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${ct.ALPHA.GENERATE} with model: ${ea}`);const e=await this.request.post({endpoint:ct.ALPHA.GENERATE,body:i,headers:s,stream:!0});if(!e)throw new Error("No response stream received");const t=Fe.fromReadableStream(e);let n="",r=null;t.on("text",e=>{n+=e}),t.on("error",e=>{r=e});const o=await t.finalMessage();if(r)throw r;return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:o.usage.input_tokens,output:o.usage.output_tokens}}}catch(e){l=e instanceof Error?e:new Error(String(e)),c++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${l.message}`),l;if(c>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),l;const n=1e3*Math.pow(2,c);dlog(`[CompactAgent] retrying API call (${c}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}throw l||new Error("Compact API call failed")}};async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!y(n))return null;const r=await P.readFile(n,"utf-8"),o=r.trim();return o&&"# Taste (Continuously Learned by CommandCode.ai)"!==o&&"# Taste (Continuously Learned by CommandCode)"!==o?r:null}catch(e){return null}}wt(),Ct(),__name(getTasteContent,"getTasteContent"),mn();var na=new js("ContextEngine"),ra=200,oa=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;requestInterrupted=!1;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();lastFileContexts=[];learningAgent;compactAgent;checkpointManager;constructor(e,t){const n=getApiBaseUrl();this.request=new no({baseUrl:n}),this.callbacks=e,this.sessionManager=new Bs(t),this.learningAgent=new Xs({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new ta({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new no({baseUrl:e}),this.learningAgent.updateRequest(this.request),this.compactAgent.updateRequest(this.request)}createSessionStoreAdapter(){return{saveSnapshot:__name(async e=>{await this.sessionManager.saveSnapshot(e)},"saveSnapshot"),loadSnapshots:__name(async()=>this.sessionManager.loadSnapshots(),"loadSnapshots"),deleteSnapshotsAfter:__name(async e=>{await this.sessionManager.deleteSnapshotsAfter(e)},"deleteSnapshotsAfter"),getMessageAtIndex:__name(e=>this.sessionManager.getMessageAtIndex({index:e.index,messages:this.messages}),"getMessageAtIndex"),getMessageIndexById:__name(e=>this.sessionManager.getMessageIndexById({messageId:e.messageId,messages:this.messages}),"getMessageIndexById"),truncateMessagesAtIndex:__name(async e=>{const t=await this.sessionManager.truncateMessagesAtIndex({index:e.index,messages:this.messages});this.messages=t},"truncateMessagesAtIndex"),getMessageCount:__name(()=>this.sessionManager.getMessageCount({messages:this.messages}),"getMessageCount")}}setupCheckpointSessionStore(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),this.checkpointManager.runCleanup().catch(()=>{})}async interrupt(e=!1){if(this.requestInterrupted=!0,this.abortController){this.abortController.abort(),this.abortController=null,na.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)){const n=t.message.content.filter(e=>"tool_use"===e.type),r=[];if(n.length>0){const e=n.map(e=>({type:"tool_result",tool_use_id:e.id,content:"Interrupted by user",is_error:!0}));r.push(...e),na.debug(`Added tool_result blocks for ${e.length} interrupted tool calls`)}e&&r.push({type:"text",text:"Interrupted by user"}),r.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:r}))}if(e){const e=Lo("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>na.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n){let r=e,o=[];try{const t=await processFileReferences(e);if(r=t.processedContent,o=t.fileReferences,o.length>0){const e=o.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(r=`${n}\n\n${r}`);const s=Lo(e);t&&t.length>0&&(s.metadata={...s.metadata,images:t}),o&&o.length>0&&(s.metadata={...s.metadata,fileReferences:o}),this.callbacks.onFeedUpdate(s);const a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),r.trim()&&a.push({type:"text",text:r});const i={role:"user",content:a},c=crypto.randomUUID(),l=this.createMessageWithMeta(i,{messageId:c});return this.addMessageAndSync(l),this.checkpointManager.createSnapshot({messageId:c}).catch(e=>na.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,s).catch(e=>na.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){na.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}async processMessages(){let e="";this.requestInterrupted=!1,this.abortController=new AbortController,this.learningAgent.setAbortSignal(this.abortController.signal);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.checkIfInterrupted(),this.updateContextUsage(o),await this.checkAndCompactIfNeeded();const s=o.content.filter(e=>"tool_use"===e.type),a=o.content.filter(e=>"server_tool_use"===e.type);if(e=a.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===s.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===a.length){const t=_o(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>na.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>na.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=Lo(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>na.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=_o(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:s}),{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=Lo(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>na.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&na.debug("Request interrupted or insufficient credits"),e}return this.abortController=null,e}getHistory(){return[...this.messages]}async loadSession(e){const{messages:t,corruptedLines:n,totalLines:r}=await this.sessionManager.loadMessages(e);this.messages=t;try{await this.loadCheckpoints()}catch(t){na.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return na.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}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 manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};na.debug(`Manual compact: ${this.messages.length} messages`);const e=this.contextTokensUsed;return await this.summarizeAndCompact(),{tokensSaved:Math.max(0,e-this.contextTokensUsed),didCompact:!0}}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}}}let o=0;const s=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],a=n.message.role;if(e&&t>=r&&-1!==r)s.push(n);else{if("user"===a){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){o+=estimateTokens(n.message);continue}s.push(n)}else s.push(n)}else if("assistant"===a){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)o+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?s.push({...n,message:{...n.message,content:r}}):o+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&s.push(n)}"user"!==a&&"assistant"!==a&&(o+=estimateTokens(n.message))}}this.messages=s,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,n-o);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:Us}),{messagesRemoved:t-s.length,tokensSaved:o}}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=Gr.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:ct.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.requestInterrupted||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===ut.ANTHROPIC&&(r=await Rt.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o={tools:e,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},s={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:o,threadId:this.sessionManager.getSessionId()};na.debug(`calling API (${o.model}, ${this.messages.length} msgs, ${e.length} tools)`);const a=await isTasteLearningEnabled(),i={[it.PROJECT_SLUG]:Bs.getCurrentProjectDirName(),[it.TASTE_LEARNING]:a.toString(),[it.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(i[it.OAUTH_TOKEN]=`Bearer ${r}`),{body:s,headers:i}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++){let r;try{const t=interceptStreamErrors({responseStream:await this.request.post({body:e.body,stream:!0,endpoint:ct.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const o=Fe.fromReadableStream(n);o.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let s=null;o.on("error",e=>{s="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const a=await o.finalMessage();if(s)throw s;return this.callbacks.onRetryUpdate?.(null),a}catch(e){const o=r?.(),s=o?Object.assign(new Error(o.message),{type:o.type,error:{type:o.type,message:o.message}}):e;if(t=s,this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(s))throw trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"non_retryable_api_error"}),context:{component:_n.CONTEXT_ENGINE,heading:"Non-retryable API error",code:s?.status||s?.statusCode}}),this.formatAPIError(s);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:_n.CONTEXT_ENGINE,code:s?.status||s?.statusCode,"retry.attempts":10}}),this.formatAPIError(s);const a=Math.min(n,10),i=100*Math.pow(2,a),c=Math.max(i,1e3),l=Math.min(c,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:l,signal:this.abortController?.signal})}}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){const{message:t}=this.extractErrorMessage(e),n=t?.toLowerCase()||"",r="Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")||this.requestInterrupted||this.abortController?.signal.aborted,o="Insufficient credits"===t||n.includes("insufficient credits"),s=e instanceof Jr||401===e?.status||e instanceof Yr||403===e?.status,a=e?.type||e?.error?.type,i="rate_limit_error"===a||429===e?.status||n.includes("rate limit"),c="overloaded_error"===a||529===e?.status||n.includes("overloaded");return r||o||s||i||c}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.error?.message){const n=parseEmbeddedErrorJSON(e.error.message);return n?{...n,status:n.status||t}:{status:t,type:e.error.type||null,message:e.error.message}}const n=e?.message;if("string"==typeof n){const e=parseEmbeddedErrorJSON(n);if(e)return{...e,status:e.status||t}}return{status:t,type:e?.type||null,message:e?.message||null}}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.requestInterrupted||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=this.extractErrorMessage(e),n=t.status,r=t.type,o=t.message;dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",o);const s=o?.toLowerCase().includes("insufficient credits");if(s)return new Error("Insufficient credits");const a=o?.toLowerCase().includes("oauth authentication required");if(a)return e;if(e instanceof Yr||403===e?.status)return e;if(e instanceof Jr||401===e?.status)return new Error('Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.');const i=getSupportId();let c="";if(o)if(o.includes("Invalid 'Authorization' header"))c='Error: Authentication failed. Run "cmd login" to sign in again.';else{let e=o;for(;e.startsWith("Error: ");)e=e.substring(7);e.includes("Unexpected event order")&&(e="The API returned an error. This may be due to high traffic or a temporary issue.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>ra&&(t=t.substring(0,ra)+"..."),c=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const s=o.toLowerCase(),a="overloaded_error"===r||s.includes("overloaded"),l="rate_limit_error"===r||s.includes("rate limit");c+=a?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":l?'\n\nYou can wait a moment and try again, or type "continue" to retry.':'\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==i&&(c+=`\nRequest ID: ${i}`)}else if(e.toString){const t=e.toString();c=t.length>ra?t.substring(0,ra)+"...":t}else c="Error: Unknown error occurred";return new Error(c)}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 s=await this.executeSingleTool(o);t.push({type:"tool_result",tool_use_id:o.id,content:s}),n.add(o.id),isAgentTool(o.name)||this.showToolSuccess(o,s)}catch(e){const r=e instanceof Error?e.message:"Unknown error";"Interrupted by user"===r&&isAgentTool(o.name)?n.add(o.id):(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,onQuestionRequest:this.callbacks.onQuestionRequest,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=Xo(e.name,e.input),n={..."edit_file"===e.name?e.input:{},permissionDenied:!0},r=Mo(e.name,t,n),o=qo(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=Xo(e.name,r),s=Mo(e.name,o,n),a=qo(s,t);this.callbacks.onFeedUpdate(a)}showToolError(e,t){const n=Xo(e.name,e.input),r="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,o=Mo(e.name,n,r),s=qo(o,Vo(t));this.callbacks.onFeedUpdate(s)}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=_o(t.trim());this.callbacks.onFeedUpdate(e),t=""}const e=Xo(n.name,n.input),r=Mo(n.name,e),o=So(n.name)?"Found 10 results":"Content fetched",s=qo(r,o);this.callbacks.onFeedUpdate(s)}if(t.trim()){const e=_o(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:Us})}async checkAndCompactIfNeeded(){const e=Math.floor(Us*ft.TIER_1_THRESHOLD),t=Math.floor(Us*ft.TIER_2_THRESHOLD),n=Math.floor(Us*ft.TIER_3_THRESHOLD);try{if(this.contextTokensUsed>n){na.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 3 threshold (${n}), triggering summarization`),this.callbacks.onStatusUpdate?.("Context limit reached. Auto-compacting the conversation...");const e=this.contextTokensUsed;await this.summarizeAndCompact();const t=Math.max(0,e-this.contextTokensUsed);return void(t>0&&this.callbacks.onFeedUpdate(Oo(`Auto-compacted conversation, saved ~${t.toLocaleString()} tokens.`)))}if(this.contextTokensUsed>t){na.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${ft.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(ft.TIER_2_KEEP_COUNT);return na.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void(e.tokensSaved>0&&this.callbacks.onFeedUpdate(Oo(`Auto-compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`)))}if(this.contextTokensUsed>e){const t=this.countToolCalls(),n=ft.TIER_1_KEEP_COUNT;if(t>n){na.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);na.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),t.tokensSaved>0&&this.callbacks.onFeedUpdate(Oo(`Auto-compacted conversation, saved ~${t.tokensSaved.toLocaleString()} tokens.`))}}}catch(e){na.debug(`Failed to automatically compact conversation: ${e}`)}}countToolCalls(){let e=0;for(const t of this.messages){const n=t.message.content;if(Array.isArray(n))for(const t of n)"tool_use"===t.type&&e++}return e}async removeToolCallsExceptLast(e){const t=this.contextTokensUsed;let n=0;const r=[];for(let e=0;e<this.messages.length;e++){const t=this.messages[e].message.content;if(Array.isArray(t))for(let n=0;n<t.length;n++)"tool_use"===t[n].type&&r.push({id:t[n].id,msgIndex:e,blockIndex:n})}const o=new Set(r.slice(-e).map(e=>e.id)),s=new Set(r.filter(e=>!o.has(e.id)).map(e=>e.id)),a=[];for(const e of this.messages){const t=e.message.role,r=e.message.content;if("user"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_result"!==e.type||!s.has(e.tool_use_id)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;a.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_use"!==e.type||!s.has(e.id)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;a.push({...e,message:{...e.message,content:t}});continue}a.push(e)}this.messages=a,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,t-n);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:Us}),{toolsRemoved:s.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return na.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(ft.TIER_2_KEEP_COUNT);na.debug(`Summarizing ${e.length} older messages, keeping ${t.length} recent messages`);const n=e.map(e=>e.message),r=await this.compactAgent.compactMessages({messages:n});na.debug(`Summarization complete: ${r.summary.length} chars, used ${r.tokensUsed.input}/${r.tokensUsed.output} tokens`);const o=this.createMessageWithMeta({role:"user",content:[{type:"text",text:`This is an auto-compacted summary of the earlier conversation that ran out of context.\n\n${r.summary}`}]},{isSummary:!0}),s=this.contextTokensUsed,a=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[o,...t],await this.sessionManager.saveMessages(this.messages);const i=estimateTokens(o.message),c=Math.max(0,s-a+i);this.contextTokensUsed=c,this.callbacks.onContextUsageUpdate?.({current:c,limit:Us}),na.debug(`Tier 3 summarization complete: reduced from ${s} to ~${c} tokens`)}catch(e){na.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(ft.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=ft.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const o=this.messages[r],s=estimateTokens(o.message);if(t+s>e){n=r+1;break}t+=s;const a=o.message.content;Array.isArray(a)&&a.some(e=>"tool_result"===e.type)}n=Math.min(n,this.messages.length-3),n=Math.max(0,n);let r=0;this.messages[0]?.meta?.isSummary&&(r=1);for(let e=r;e<n;e++){const t=this.messages[e].message.content;if(Array.isArray(t)&&t.some(e=>"image"===e.type)){n=e;break}}for(;n>r&&"user"===this.messages[n].message.role;)n--;return{messagesToSummarize:this.messages.slice(r,n),messagesToKeep:this.messages.slice(n),keepStartIndex:n}}getCheckpointManager(){return this.checkpointManager}listCheckpoints(){return this.checkpointManager.listCheckpoints()}hasCheckpoints(){return this.checkpointManager.hasCheckpoints()}async restoreToCheckpoint(e){const{messageId:t,mode:n}=e;this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()});const r=this.sessionManager.getMessageIndexById({messageId:t,messages:this.messages});let o=0;if(-1!==r&&("conversation"===n||"both"===n))for(let e=r;e<this.messages.length;e++)o+=estimateTokens(this.messages[e].message);const s=await this.checkpointManager.restore({messageId:t,mode:n});return!s.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-o),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:Us})),s}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}};function getShellPathAndName(){const e=process.env.SHELL||"/bin/bash",t=e.split("/").pop()?.toLowerCase()||"bash";return{path:e,name:t}}function getShellType(e){return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":"unknown"}function detectUserShell(){const{path:e,name:t}=getShellPathAndName();return"win32"===process.platform?{type:"unknown",path:e}:{type:getShellType(t),path:e}}wt(),wt(),wt(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var sa=["no job control","cannot set terminal process group"],aa=null;function getShellInfo(){return aa||(aa=detectUserShell()),aa}__name(getShellInfo,"getShellInfo");var ia=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{let s=!1;const a=__name(e=>{s||(s=!0,t(e))},"doResolve"),i=getShellInfo(),c="bash"===i.type||"zsh"===i.type,l=c?i.path:"/bin/bash",d=A(l,c?["-i","-c",e]:["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let u="",m="",g=null;n>0&&(g=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),a({stdout:u,stderr:m+(m?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(u.length+n.length>ks){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void a({stdout:u,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}u+=n}catch(e){m+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,d.kill("SIGTERM")}}),d.stderr?.on("data",e=>{try{const t=e.toString();if(m.length+t.length>Cs)return void(m+="\n[Error output truncated: too large]");m+=t}catch(e){m+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{g&&clearTimeout(g);const n=c?m.split("\n").filter(e=>!sa.some(t=>e.includes(t))).join("\n"):m;a({stdout:u.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{g&&clearTimeout(g),a({stdout:u,stderr:m+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),ca=__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"),la=__name(()=>{const[e,t]=_({isExecuting:!1,currentCommand:null});return{executeBash:j(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await ia(e,{timeout:3e4,cwd:process.cwd()}),o=ca(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]=qo(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]=qo(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");wt(),wt(),Ct();var da=class extends Oe{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,n){super(),this.projectRoot=e,this.configPath=n||t.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 x.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 n=t.relative(this.projectRoot,e.filePath);return`${e.action}:${n}`}isTrustedPath(e){const n=t.relative(this.projectRoot,e);return this.config.trustedPaths.some(t=>n.startsWith(t)||e.startsWith(t))}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=t.join(this.projectRoot,".commandcode"),n=t.join(e,"settings.local.json");try{await x.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await x.readFile(n,"utf-8"),r=JSON.parse(e);r.permissions&&r.permissions.allow&&(t.permissions.allow=[...new Set([...r.permissions.allow,...t.permissions.allow])]),r.permissions&&r.permissions.deny&&(t.permissions.deny=r.permissions.deny)}catch(e){}await x.writeFile(n,JSON.stringify(t,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const n=t.join(this.projectRoot,".commandcode"),r=t.join(n,"settings.local.json"),o=`Bash(${e.split(" ")[0]}:*)`;try{let e;await x.mkdir(n,{recursive:!0});try{const t=await x.readFile(r,"utf-8");e=JSON.parse(t)}catch(t){e={permissions:{allow:[],deny:[],defaultMode:"ask"}}}e.permissions||(e.permissions={allow:[],deny:[],defaultMode:"ask"}),e.permissions.allow||(e.permissions.allow=[]),e.permissions.allow.includes(o)||e.permissions.allow.push(o),await x.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},ua=__name((e={})=>{const[t,n]=_(null),[r,o]=_(null),[s,a]=_(!1);return U(()=>{const t=e.projectRoot||process.cwd(),r=new da(t);return r.on("permission-request",(t,n)=>{o(t),a(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),a(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:j(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:j(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:j(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),a(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),a(!1)}},[t]),clearSessionPermissions:j(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:j(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:j((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:j(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r=["create","edit","delete","execute","shellCommands"];for(const e of r)n.setAutoApprove(e,t)}wt(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),wt();var ma=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole");function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",o=!1,s="";for(let e=0;e<t.length;e++){const a=t[e];'"'!==a&&"'"!==a||o?a===s&&o?(o=!1,s=""):" "!==a||o?r+=a:(r.trim()&&n.push(r.trim()),r=""):(o=!0,s=a)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const o=n.substring(0,r),s=n.substring(r+1).trim();return{commandName:o,rawArguments:s,positionalArgs:parsePositionalArguments({input:s})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let o=t;return o=o.replace(/\$ARGUMENTS/g,n),o=o.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:o}}function loadCustomCommands(){const e=[],n=t.join(process.cwd(),".commandcode","commands"),r=t.join(g.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,o=""){if(f.existsSync(n))try{const s=f.readdirSync(n,{withFileTypes:!0});for(const a of s){const s=t.join(n,a.name);if(a.isDirectory())loadCommandsFromDirectory(s,r,o?`${o}/${a.name}`:a.name);else if(a.isFile()&&a.name.endsWith(".md")){const n=t.basename(a.name,".md"),i=f.readFileSync(s,"utf-8").trim();e.push({name:n,source:r,content:i,subdirectory:o})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(r,"user"),loadCommandsFromDirectory(n,"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.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim()} ${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}function isDirectoryEmpty(){try{return 0===S(process.cwd()).length}catch{return!1}}async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new no({baseUrl:e});return await t.get({endpoint:ct.ALPHA.WHOAMI})}wt(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),Ft(),wt(),Ct(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),wt(),__name(isDirectoryEmpty,"isDirectoryEmpty"),wt(),Ct(),__name(getAuthenticatedEntity,"getAuthenticatedEntity"),yn(),wt();var ga=["Code","Code - Insiders","VSCodium","Cursor"],pa="Code",ha={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},fa=__name(e=>l(e).href,"formatPathForTerminal"),ya=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),Ea=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),wa=__name(({home:t,configSegments:n,variants:r})=>{for(const o of r){const r=Ea({home:t,configSegments:n,variant:o});if(h.existsSync(e.dirname(r)))return o}return null},"findExistingVariant"),ba=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Sa(t.when)},"isTerminalShiftEnterBinding"),Sa=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),ka=__name(e=>{const t=_e(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),Ca=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),va=__name(({error:e,content:t})=>{const n=e.message;return Ca(t)&&(n.includes("Expected double-quoted property name")||n.includes("Unexpected token")||n.includes("is not valid JSON"))?"Invalid JSON: trailing comma detected. Remove the comma before the closing bracket.":n.includes("Expected")&&n.includes(",")&&n.includes("or")?"Invalid JSON: missing comma between elements.":n.includes("Unterminated string")||n.includes("Bad string")?"Invalid JSON: unterminated string. Check for missing closing quotes.":"Invalid JSON syntax. Please check the file format."},"formatJsonParseError"),Ta=__name(e=>{let t="",n=!1,r=!1;for(let o=0;o<e.length;o++){const s=e[o];if(n)t+=s,r?r=!1:"\\"===s?r=!0:'"'===s&&(n=!1);else if('"'!==s){if(","===s){let t=o+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=s}else n=!0,t+=s}return t},"removeTrailingCommas"),Aa=__name(e=>{try{const t=_e(e),n=Ta(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:va({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),Pa=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:fa(t)}),"createSuccessResult"),xa=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:fa(t)}),"createErrorResult"),Ia=__name(()=>{const t=m.homedir(),n=m.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=ya(n);if(!r)return Ea({home:t,configSegments:[".config"],variant:pa});const o=wa({home:t,configSegments:r,variants:ga});return Ea({home:t,configSegments:r,variant:o??pa})},"getVSCodeKeybindingsPath"),Ra=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)ba(n)&&(n.command===ha.command&&n.args?.text===ha.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),$a=__name(t=>{try{if(!h.existsSync(t)){const n=e.dirname(t);return h.existsSync(n)||h.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=h.readFileSync(t,"utf-8");if(ka(n))return{rawContent:n,keybindings:[]};const r=Aa(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:xa({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):xa({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return xa({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),Da=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(ha,null,2);if(ka(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return xa({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?xa({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,o+1)+",\n"+n+e.substring(o+1)},"generateNewContent");function setupVSCodeTerminal(){const e=Ia();try{const t=$a(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=Ra(r);if(o.hasConflicting)return xa({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return Pa({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=Da({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(h.writeFileSync(e,s,"utf-8"),Pa({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return xa({message:`Failed to configure VSCode key binding: ${t instanceof Error?t.message:"Unknown error"}`,keybindingsPath:e})}}function isVSCodeTerminal(){return"vscode"===process.env.TERM_PROGRAM}__name(setupVSCodeTerminal,"setupVSCodeTerminal"),__name(isVSCodeTerminal,"isVSCodeTerminal"),wt(),Ct(),mn(),wt();var Na={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return Na[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Le(t);return e.join(g.homedir(),".commandcode","projects",n)}function getGlobalProjectSettingsPath(t=process.cwd()){return e.join(getGlobalProjectSettingsDir(t),"settings.json")}async function loadGlobalProjectSettings(e=process.cwd()){try{const t=getGlobalProjectSettingsPath(e),n=await P.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(t,n=process.cwd()){try{const r=getGlobalProjectSettingsPath(n),o=e.dirname(r);await P.mkdir(o,{recursive:!0}),await P.writeFile(r,JSON.stringify(t,null,2))}catch(e){const t=e instanceof Error?e.message:String(e);dlog("Error saving global project settings:",e),Qs.addEvent({type:"error",message:`Failed to save global project settings: ${t}`})}}async function loadLocalProjectSettings(t=process.cwd()){try{const n=e.join(t,".commandcode","settings.local.json"),r=await P.readFile(n,"utf-8");return JSON.parse(r)}catch{return{}}}async function loadMergedProjectSettings(e=process.cwd()){try{const t=mergeSettings(await loadGlobalProjectSettings(e),await loadLocalProjectSettings(e)),n=t.tasteOnboarding,r=n?.learnedSessions?.["claude-code"]?.length||0;return dlog(`[Config] project settings loaded (taste: ${n?.completed?"complete":n?.skipped?"skipped":"pending"}, learned: ${r} sessions)`),t}catch(e){return dlog("[Settings] error loading",e),{}}}function mergeSettings(e,t){const n={...e};return t.tasteOnboarding&&(n.tasteOnboarding={...e.tasteOnboarding,...t.tasteOnboarding},(e.tasteOnboarding?.learnedSessions||t.tasteOnboarding?.learnedSessions)&&(n.tasteOnboarding.learnedSessions={...e.tasteOnboarding?.learnedSessions,...t.tasteOnboarding?.learnedSessions})),n}__name(getAgentDisplayName,"getAgentDisplayName"),__name(getProjectDirName,"getProjectDirName"),wt(),mn(),Ct(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),wt(),mn();var Fa=e.join(m.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=C(e,{encoding:"utf8"}),n=Me.createInterface({input:t,crlfDelay:1/0});for await(const e of n)if(e.trim()){try{const r=JSON.parse(e);if("session_meta"===r.type&&r.payload?.cwd)return n.close(),t.destroy(),{cwd:r.payload.cwd,id:r.payload.id,timestamp:r.payload.timestamp}}catch{}break}return n.close(),t.destroy(),null}catch{return null}}async function findAllSessionFiles(t,n){const r=[];try{await P.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const o=await P.readdir(t);for(const s of o){if(!/^\d{4}$/.test(s))continue;const o=e.join(t,s);if(!(await P.stat(o)).isDirectory())continue;const a=await P.readdir(o);for(const t of a){if(!/^\d{2}$/.test(t))continue;const a=e.join(o,t);if(!(await P.stat(a)).isDirectory())continue;const i=await P.readdir(a);for(const o of i){if(!/^\d{2}$/.test(o))continue;const i=e.join(a,o);if(!(await P.stat(i)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${s}/${t}/${o}`});const c=(await P.readdir(i)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(i,t));r.push(...c)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const o=[];for(let s=0;s<e.length;s+=n){const a=e.slice(s,s+n),i=await Promise.all(a.map(t));for(const e of i)null!==e&&o.push(e);r?.(Math.min(s+n,e.length),e.length)}return o}async function findCodexSessions(t,n,r=0){const o=t||process.cwd(),s=[];dlog(`[Codex] scanning for project: ${o}`);const a=await findAllSessionFiles(Fa,n);if(0===a.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${a.length} session files to scan`),n?.({phase:"reading",totalFiles:a.length,processedFiles:0,matchedSessions:0});let i=0;const c=await processFilesInBatches(a,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===o)try{const r=await P.stat(t),o=e.basename(t,".jsonl");return{id:n.id||o,filePath:t,createdAt:new Date(n.timestamp||r.birthtime),lastModified:r.mtime,messageCount:0,agent:"codex",projectDir:n.cwd}}catch{return null}return null},10,(e,t)=>{i=s.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:i})});s.push(...c);const l=r>0?s.slice(0,r):s;return dlog(`[Codex] matched ${l.length} sessions for project`),n?.({phase:"complete",totalFiles:a.length,processedFiles:a.length,matchedSessions:l.length}),l.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await P.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("event_msg"===n.type&&"user_message"===n.payload?.type&&n.payload?.message){const e=n.payload.message;"string"==typeof e&&e.trim()&&t.push(e.trim())}}catch{continue}t.length>0&&dlog(`[Codex] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Codex] failed to extract prompts: ${e}`,t)}return t}async function loadProjectSettings(){return loadMergedProjectSettings()}async function saveProjectSettings(e){await saveGlobalProjectSettings(e)}function isOnboardingDone(e){return!0===e?.skipped||!0===e?.completed}function buildAgentSessionsList(e){return Object.entries(e).filter(([e,t])=>t&&t.length>0).map(([e,t])=>({agent:e,sessionIds:t,displayName:getAgentDisplayName(e)}))}async function checkOnboardingConditions(){try{const e=(await loadProjectSettings()).tasteOnboarding,t=!0===e?.demoShown;if(isOnboardingDone(e))return dlog("[Onboarding] "+(e?.skipped?"user skipped":"already completed")),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!0,agentSessions:[],demoShown:t};const n=await findNewSessions(e?.learnedSessions||{}),r=(n["claude-code"]?.length||0)+(n.codex?.length||0);return r>0?(dlog(`[Onboarding] found ${r} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:r,hasTasteContent:!0,agentSessions:buildAgentSessionsList(n),demoShown:t}):t?(dlog("[Onboarding] no new sessions to learn from"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t}):(dlog("[Onboarding] first time user, will show demo"),{shouldTrigger:!0,reason:"no_sessions",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:!1}}}async function getSessionFilesFromDir(e){try{return(await P.readdir(e)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints")).map(e=>e.replace(".jsonl",""))}catch{return[]}}async function findNewSessions(t){const n={},r=t["claude-code"]||[],o=t.codex||[];try{const t=e.join(m.homedir(),".claude","projects");await P.access(t);const o=getProjectDirName(process.cwd()),s=(await P.readdir(t)).filter(e=>e===o);for(const o of s){const s=e.join(t,o);if((await P.stat(s)).isDirectory()){const e=await getSessionFilesFromDir(s);e.length>0&&(n["claude-code"]=e.filter(e=>!r.includes(e)))}}dlog(`[Sessions] claude-code: ${n["claude-code"]?.length||0} new, ${r.length} learned`)}catch{dlog("[Sessions] claude projects dir not found")}try{const e=await findCodexSessionIds();e.length>0&&(n.codex=e.filter(e=>!o.includes(e)));dlog(`[Sessions] codex: ${n.codex?.length||0} new, ${o.length} learned`)}catch{dlog("[Sessions] codex sessions not found")}return n}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0,await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function markDemoShown(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.demoShown=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:o}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions();e.shouldTrigger?(dlog(`[Onboarding] starting taste learning (${e.reason})`),o(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),__name(loadProjectSettings,"loadProjectSettings"),__name(saveProjectSettings,"saveProjectSettings"),__name(isOnboardingDone,"isOnboardingDone"),__name(buildAgentSessionsList,"buildAgentSessionsList"),__name(checkOnboardingConditions,"checkOnboardingConditions"),__name(getSessionFilesFromDir,"getSessionFilesFromDir"),__name(findNewSessions,"findNewSessions"),__name(markSessionsAsLearned,"markSessionsAsLearned"),__name(markOnboardingSkipped,"markOnboardingSkipped"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markDemoShown,"markDemoShown"),__name(triggerTasteOnboarding,"triggerTasteOnboarding"),wt(),Ct(),wt();var La="# Taste (Continuously Learned by CommandCode.ai)",Oa=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return Oa.test(t)?t.replace(Oa,`$1${La}`):t}__name(migrateHeader,"migrateHeader");var _a=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await P.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await P.access(r);const e=await P.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await P.writeFile(r,t,"utf-8")}catch{await P.writeFile(r,La+"\n\n")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await P.access(n),!0}catch{return!1}}};hn(),En(),Kt(),wt(),wt(),Ct(),wt(),wt(),Ct();var Ma=__name(()=>t.join(g.homedir(),".commandcode","agents"),"getRootAgentDir"),Ua=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),ja=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=_("idle"),[a,i]=_(""),c=[...Gs.map(e=>e.name),...qs.map(e=>e.name)],l=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void i("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?Ma():Ua();await x.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),a=Array.from(e.selectedTools).map(e=>Js[e]||e).join(", "),i=0===e.selectedTools.size?"none":e.selectedTools.size===c.length?'"*"':JSON.stringify(a),l=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${i}\n---\n\n${e.sysPrompt}\n`;await x.writeFile(s,l,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),i(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");V((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||l()});const d=Array.from(e.selectedTools).map(e=>Js[e]||e).join(", "),u="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return O.createElement(W,{flexDirection:"column",gap:1},O.createElement(W,{flexDirection:"column"},O.createElement(W,{gap:1},O.createElement(H,{color:"white",bold:!0},"Name:"),O.createElement(H,{color:"gray"},e.agentType)),O.createElement(W,{gap:1},O.createElement(H,{color:"white",bold:!0},"Location:"),O.createElement(H,{color:"gray"},u)),O.createElement(W,{gap:1},O.createElement(H,{color:"white",bold:!0},"Tools:"),O.createElement(H,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===c.length?"*":d))),O.createElement(W,{gap:1},O.createElement(H,{color:"white",bold:!0},"Description"),O.createElement(H,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),O.createElement(H,{color:"gray"},e.ccToolDefinition),O.createElement(W,{gap:1},O.createElement(H,{color:"white",bold:!0},"System Prompt:")),O.createElement(H,{color:"gray"},e.sysPrompt),!r&&O.createElement(W,{marginTop:1},"idle"===o&&O.createElement(W,{gap:1},O.createElement(H,{color:"green",dimColor:!0},"Press"),O.createElement(H,{color:"green",bold:!0},"Enter"),O.createElement(H,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===o&&O.createElement(H,{color:"yellow"},"Saving agent..."),"saved"===o&&O.createElement(H,{color:"green"},"✓ ",a),"error"===o&&O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"red"},"✗ Error: ",a),O.createElement(H,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),Ba=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=_("menu"),a=[...Gs.map(e=>e.name),...qs.map(e=>e.name)];let i=new Set;if("*"===e.tools||'"*"'===e.tools)i=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>Ys[e]||e);i=new Set(t)}const c={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(V((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return O.createElement(W,{flexDirection:"column"},O.createElement(ja,{config:c,onSaveComplete:()=>s("menu"),viewOnly:!0}),O.createElement(W,{marginTop:1},O.createElement(H,{color:"gray"},"Press Enter to go back")));if("edit"===o)return O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"yellow"},"Edit functionality coming soon..."),O.createElement(H,{color:"gray"},"Press Esc to go back"));if("delete"===o){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],o=__name(async r=>{if("confirm-delete"===r.value)try{await x.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return O.createElement(W,{flexDirection:"column",gap:1},O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"red"},"Delete agent"),O.createElement(H,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),O.createElement(W,null,O.createElement(Ue,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>O.createElement(H,{color:e?"white":"gray"},` ${t}`)})))}return O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"white",bold:!0},e.name),O.createElement(W,{marginTop:1},O.createElement(Ue,{items:l,onSelect:d,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>O.createElement(H,{color:e?"white":"gray"},` ${t}`)})),O.createElement(W,{marginTop:1},O.createElement(H,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Wa=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=_([]),[s,a]=_([]),[i,c]=_([]),[l,d]=_(!0),[u,m]=_(!1),[p,h]=_(null),[f,y]=_(!1),E=__name(()=>t.join(g.homedir(),".commandcode","agents"),"getRootAgentDir"),w=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),b=__name(async(e,n)=>{try{m(!1);const r=(await x.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await x.readFile(o,"utf-8"),{data:a,content:i}=Re(s);let c=a.tools||"";return"*"!==c&&'"*"'!==c||(c="*"),{name:a.name||r.replace(".md",""),description:a.description||"",tools:c,sysPrompt:i.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");U(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([b(E(),"personal"),b(w(),"project")]),n=Ms.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));o(e),a(t),c(n),d(!1)},"loadAgents")()},[u]);const S=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{S.push({label:e.name,value:e.filePath})}),s.forEach(e=>{S.push({label:e.name,value:e.filePath})});const k=r.length+s.length,C=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(h(e),y(!0))}},"handleAgentSelect");if(l)return O.createElement(H,{color:"gray"},"Loading agents...");if(f&&p){const e=p.filePath.startsWith("__builtin__:");return O.createElement(Ba,{agent:p,onBack:()=>{y(!1),h(null)},setRevalidateAgent:m,isReadOnly:e})}const v=__name(({isSelected:e,label:t})=>{const n=S.find(e=>e.label===t),o=n?.value||"",a=r[0]?.filePath===o,i=s[0]?.filePath===o;return O.createElement(W,{flexDirection:"column"},a&&r.length>0&&O.createElement(W,{marginTop:1},O.createElement(H,{color:"gray",bold:!0},"User agents")),i&&s.length>0&&O.createElement(W,{marginTop:1},O.createElement(H,{color:"gray",bold:!0},"Project agents")),O.createElement(W,null,O.createElement(H,{color:"white"},e?">":" "),O.createElement(H,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return O.createElement(W,{flexDirection:"column"},O.createElement(W,{marginBottom:1},O.createElement(H,{color:"white",bold:!0},"Agents"),k>0?O.createElement(H,{color:"gray"}," ","(",k," agent",k>1?"s":"",")"):O.createElement(H,{color:"gray"}," (No custom agents)")),n&&O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(H,{color:"green",dimColor:!0},"Created agent: ",n)),O.createElement(Ue,{items:S,onSelect:C,indicatorComponent:()=>null,itemComponent:v}),i.length>0&&O.createElement(W,{flexDirection:"column",marginTop:1},O.createElement(H,{color:"gray",bold:!0},"Default agents"),i.map(e=>O.createElement(H,{key:e.filePath,color:"gray"}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),O.createElement(W,{flexDirection:"column",marginTop:1},O.createElement(H,{color:"gray"},"Create specialized subagents that Command Code can delegate to."),O.createElement(H,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");wt(),Ct(),wt(),wt(),Ct();var Ha=__name(({onSelect:e})=>O.createElement(Ue,{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})=>O.createElement(H,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>O.createElement(H,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector");wt(),nn(),Ct(),on(),dn();var za=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=_(!1),[m,g]=_(!1),p=j(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?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),h=j(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?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[m,a]);return"agentType"===e?O.createElement(O.Fragment,null,O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(Js).some(e=>Le(e)===Le(t))||Object.keys(Js).some(e=>Le(e)===Le(t)))&&O.createElement(H,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Le(t))&&O.createElement(H,{color:"red"},"⚠ This name is reserved. Reserved names:"," ",_s.join(", "))),O.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Le(t);Object.values(Js).some(t=>Le(t)===e)||Object.keys(Js).some(t=>Le(t)===e)||isReservedAgentName(e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?O.createElement(O.Fragment,null,O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"white"},"Enter the system prompt for your agent:"),O.createElement(H,{color:"gray"},"Be comprehensive for best results.")),O.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?O.createElement(O.Fragment,null,O.createElement(H,{color:"white"},"When should ","Command Code"," use this agent?"),O.createElement(TextInput,{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");wt();var Ga=__name(({onSelect:e})=>O.createElement(Ue,{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})=>O.createElement(H,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>O.createElement(H,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector");wt(),nn(),wt();var qa=["·","○","◇","☆","✧","☆","◇","○","⌘"],Va=[8,5,4,4,4,4,4,5,20],Ka=[5,4,4,4,4,4,5],Ja=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Va.length;e++)if(n+=Va[e],t<n)return qa[e];const r=t-58;n=0;for(let e=0;e<Ka.length;e++)if(n+=Ka[e],r<n)return qa[7-e];return qa[0]},"getWaveSymbol"),Ya=["#8A6BA3","#B799E6","#E4CCFF","#FFFFFF","#E4CCFF","#B799E6","#8A6BA3"];function ShimmerText({text:e}){const[t,n]=_(0);U(()=>{const t=setInterval(()=>{n(t=>(t+1)%(e.length+10))},50);return()=>clearInterval(t)},[e.length]);const r=__name(e=>{const n=e-(t-5);return n>=0&&n<Ya.length?Ya[n]:"#B799E6"},"getCharColor");return O.createElement(H,null,e.split("").map((e,t)=>O.createElement(H,{key:t,color:r(t)},e)))}function CMDIcon(){const[e,t]=_(0);return U(()=>{const e=setInterval(()=>{t(e=>(e+1)%88)},15);return()=>clearInterval(e)},[]),O.createElement(H,{color:"#E4CCFF",bold:!0},Ja(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var Qa=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=_(0),s=getTerminalWidth();function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}U(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),s=e>0?t:-t,a=setInterval(()=>{o(e=>{const t=e+s;return s>0&&t>=n||s<0&&t<=n?n:t})},30);return()=>clearInterval(a)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");const a=s>70,i=s>40&&s<=70;return O.createElement(W,{width:s,height:1,paddingLeft:0,marginLeft:0},O.createElement(CMDIcon,null),O.createElement(W,{marginRight:1},O.createElement(ShimmerText,{text:e})),a?O.createElement(O.Fragment,null,O.createElement(W,{columnGap:1},O.createElement(H,{dimColor:!0},`(${formatTime3(t)}`),O.createElement(H,{dimColor:!0},"•"),O.createElement(H,{color:"gray"},pe.arrowDown),O.createElement(H,{dimColor:!0},`${formatToken(Math.round(r))}`),O.createElement(H,{dimColor:!0},"•"),O.createElement(W,{columnGap:1},O.createElement(H,{bold:!0,color:"gray"},"esc"),O.createElement(H,{dimColor:!0},"to interrupt)")))):i?O.createElement(W,{columnGap:1},O.createElement(H,{dimColor:!0},`(${formatToken(Math.round(r))})`)):O.createElement(O.Fragment,null))},"Status");dn(),on();var Za=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,a]=_(!1),[i,c]=_(0),l=j(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(a(!0),n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}},[s,t]);return O.createElement(W,{flexDirection:"column"},r?O.createElement(W,null,O.createElement(CMDIcon,null),O.createElement(H,{color:"white"},"Generating agent from description...")):O.createElement(TextInput,{key:i,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:l,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&O.createElement(W,{marginTop:1},O.createElement(H,{color:"red"},`${he.warning} ${o}`)))},"RecommendedFlow");wt();var Xa=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=_(!1),[a,i]=_(0),c=B(()=>[...Gs.map(e=>e.name),...qs.map(e=>e.name)],[]),l=B(()=>[{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=B(()=>{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]":"[ ]"} ${Js[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 V((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[a];if(e){const a=d[e.value];if(!a)return;"continue"===a.type?r():"toggle"===a.type?(s(!o),i(0)):"category"===a.type?n(a.value):"tool"===a.type&&t(a.value)}}}),O.createElement(W,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===a;if("divider"===e.type)return O.createElement(W,{key:`divider-${t}`},O.createElement(H,{color:"gray"}," ",e.label));if("spacer"===e.type)return O.createElement(W,{key:`spacer-${t}`,height:1});if("label"===e.type)return O.createElement(W,{key:`label-${t}`},O.createElement(H,{color:"gray"}," ",e.label));const o="continue"===e.type;return O.createElement(W,{key:`item-${t}`},O.createElement(H,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),O.createElement(W,{marginTop:1},e.size===c.length&&O.createElement(H,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&O.createElement(H,{color:"gray"},e.size," tools selected"),0===e.size&&O.createElement(H,{color:"gray"},"No tools selected")))},"ToolsSelector");En(),Lt(),Ft(),hn();var ei=__name(({onComplete:e})=>{const[t,n]=_("location"),[r,o]=_(!1),[s,a]=_(null),[i,c]=_("agentType"),l=B(()=>[...Gs.map(e=>e.name),...qs.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=_(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{a(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===ut.ANTHROPIC&&(r=await Rt.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const s={[it.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(s[it.OAUTH_TOKEN]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new no({baseUrl:i}),l=await c.post({headers:s,endpoint:ct.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});m({...u,agentType:Le(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof Kr&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?a(Pt):a("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{m({...u,agentType:Le(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),w=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),b=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),S=__name(()=>{n("summary")},"handleToolsComplete"),k=__name(e=>{const t=new Set(u.selectedTools);t.has(e)?t.delete(e):t.add(e),m({...u,selectedTools:t})},"handleToggleTool"),C=__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 O.createElement(W,{flexDirection:"column",gap:1},O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"white",bold:!0},"Create new agent"),O.createElement(H,{color:"gray"},p())),O.createElement(W,null,"location"===t&&O.createElement(Ha,{onSelect:h}),"method"===t&&O.createElement(Ga,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&O.createElement(Za,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:y}),"configuration"===t&&"manual"===u.method&&O.createElement(W,{flexDirection:"column",gap:1},O.createElement(za,{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:E,onSysPromptSubmit:w,onCCToolDefinitionSubmit:b})),"tools"===t&&O.createElement(Xa,{selectedTools:u.selectedTools,onToggleTool:k,onToggleCategory:C,onComplete:S}),"summary"===t&&O.createElement(ja,{config:u,onSaveComplete:g})))},"AgentNew"),ti=__name(({onCancel:e})=>{const[t,n]=_(null),[r,o]=_(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return V((t,n)=>{n.escape&&e()}),O.createElement(W,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"single",flexDirection:"column"},null===t&&O.createElement(Wa,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&O.createElement(ei,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");wt(),wt();var ni=__name(({messages:e})=>0===e.length?null:O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(W,{marginBottom:0},O.createElement(H,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>O.createElement(W,{key:t},O.createElement(H,{dimColor:!0},he.pointerSmall," "),O.createElement(H,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages");function accumulateDelta(e,t,n){const r=n+t;return e===t||e===r?t:r&&e.startsWith(r)?t+e.slice(r.length):t&&e.startsWith(t)?t+e.slice(t.length):t+e}function useBracketedPaste(e){const{input:t,detectedImages:n,detectedContent:r,setInput:o,setDetectedImages:s,setDetectedContent:a,incrementInputKey:i}=e,c=M(!1),l=M(""),d=M(null),u=M(""),m=j(async(e,t)=>{let c=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectClipboardImage();if(l){const e=`[Image#${n.length+1}]`;return s(e=>[...e,l]),o(t+e),void i()}let d=c;if(!d.trim()){const e=await detectClipboardText();d=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(d){if(d.length>300){const e=`[Text#${r.length+1}]`;a(e=>[...e,d]),o(t+e)}else o(t+d);i()}},[n.length,r.length,s,a,o,i]),g=j(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(c.current){const e=l.current,t=u.current;l.current="",u.current="",c.current=!1,d.current=null,e&&await m(e,t)}},500)},[m]);return{handlePaste:j(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return c.current&&(c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)),await m(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!c.current)return c.current=!0,u.current=n.textBeforePaste??t,l.current=n.pastedContent??n.cleanedContent,g(),!0;if(c.current&&!n.isPasteEnd)return void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current)),g(),!0;if(c.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current));const e=l.current,t=u.current;return l.current="",u.current="",c.current=!1,await m(e,t),!0}return!(!n.isPasteEnd||n.isPasteStart||c.current)},[t,m,g]),resetPasteState:j(()=>{c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:j(()=>c.current,[])}}wt(),nn(),Ct(),on(),Kt(),En(),wt(),dn(),on(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),wt(),wt();var ri=["code --wait","cursor --wait","nano"],oi=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return oi.some(e=>n===e||n.endsWith(`/${e}`))?t.some(e=>"--wait"===e||"-w"===e)?e:`${n} --wait ${t.slice(1).join(" ")}`.trim():e}function isCommandAvailable(e){try{const t=e.split(" ")[0],n="win32"===process.platform?"where":"command -v";return v(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of ri)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var si=class extends Error{static{__name(this,"NoEditorError")}constructor(){super("No editor configured"),this.name="NoEditorError"}};async function openInEditor2(e){let t=process.env.EDITOR||process.env.VISUAL||null;if(!t&&("true"===process.env.COMMAND_CODE_DISABLE_EDITOR_FALLBACK||(t=findFallbackEditor()),!t))throw new si;t=ensureWaitFlag(t);const n=o(p(),`commandcode-${Date.now()}.md`);return await R(n,e),new Promise((e,r)=>{const o=t.split(" ").filter(e=>e.length>0),s=o[0],a=o.slice(1),i=A(s,[...a,n],{stdio:"inherit"});i.on("close",async()=>{try{const t=await $(n,"utf-8");await D(n),e(t.trimEnd())}catch(e){r(e)}}),i.on("error",async e=>{try{await D(n)}catch{}r(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[o,s]=_(!1),[a,i]=_(null),c=j(async()=>{if(!o){s(!0),i(null);try{const n=e.replace(/\n+$/,""),o=await openInEditor2(n);t(o),r?.()}catch(e){i(e instanceof si?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{s(!1)}}},[e,t,r,o]),l=j(()=>{i(null)},[]);return{isEditorOpen:o,editorError:a,handleOpenInEditor:c,clearEditorError:l}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),wt(),Ct(),yn();var ai=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear (reset, new)",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.COMPACT="/compact",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.FEEDBACK="/feedback",e.TERMINAL_SETUP="/terminal-setup",e.IDE_SETUP="/ide",e))(ai||{}),ii=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{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:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/agents",description:"Manage agent configurations"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/model",description:"Switch between Command Code models"},{command:"/compact",description:"Compact the conversation history"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/ide",description:"Install extension to fetch IDE context"}];function truncateText(e){const{text:t,maxWidth:n}=e;return t.length<=n?t:n<=3?t.substring(0,n):t.substring(0,n-3)+"..."}__name(truncateText,"truncateText");var ci=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=_(0),[s,a]=_(0),{stdout:i}=q(),c=i?.columns??80,l=Math.max(20,c-22-2-1-2),d=B(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...ii.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];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]),u=B(()=>{const e=s,t=Math.min(e+8,d.length);return d.slice(e,t)},[d,s]);return U(()=>{o(0),a(0)},[n]),V((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>{const t=Math.max(0,e-1);return t<s&&a(t),t});else if(i.downArrow)o(e=>{const t=Math.min(d.length-1,e+1);return t>=s+8&&a(Math.max(0,t-8+1)),t});else if(i.return){const t=d[r];return void(t&&e(t.command))}}),0===d.length?O.createElement(W,{flexDirection:"column",paddingLeft:2},O.createElement(H,{color:"dim"},"No commands found")):(d.length,O.createElement(W,{flexDirection:"column",paddingLeft:1},O.createElement(W,{columnGap:2},O.createElement(W,{flexDirection:"column",width:22},u.map((e,t)=>{const n=s+t;return O.createElement(H,{key:n,color:r===n?"white":"dim",wrap:"truncate"},e.command)})),O.createElement(W,{flexDirection:"column"},u.map((e,t)=>{const n=s+t;return O.createElement(H,{key:n,color:r===n?"white":"dim",wrap:"truncate"},truncateText({text:e.description,maxWidth:l}))})))))},"CommandMenu");function loadGitignore(e){const t=je(),n=o(e,".gitignore");if(y(n))try{const e=E(n,"utf8");t.add(e)}catch{}return t.add(".git"),t}wt(),__name(loadGitignore,"loadGitignore");var li=__name(({onSelectFile:e,onClose:t,searchQuery:s=""})=>{const[i,c]=_(process.cwd()),[l,d]=_([]),[u,m]=_(0),[g,p]=_(0),h=s.trim()?15:10,f=j((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const s=o(t,e);try{const e=S(s),a=[];return e.forEach(e=>{const i=o(s,e);try{const e=k(i),o=n(t,i);if(r.ignores(o))return;a.push({name:o,path:i,isDirectory:e.isDirectory()})}catch{}}),a.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),a.slice(0,50)}catch{}}if(e.includes("/")){const s=e.split("/"),a=s.pop()||"",i=o(t,s.join("/"));try{const e=S(i),s=[],c=a.toLowerCase();return e.forEach(e=>{const l=e.toLowerCase();if(!a||l.includes(c)){const a=o(i,e);try{const e=k(a),o=n(t,a);if(r.ignores(o))return;s.push({name:o,path:a,isDirectory:e.isDirectory()})}catch{}}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),s.slice(0,50)}catch{}}const s=[],a=e.toLowerCase(),i=__name((e,c=0)=>{if(!(c>8))try{S(e).forEach(l=>{const d=o(e,l);try{const e=k(d),o=n(t,d);if(r.ignores(o))return;const u=o.toLowerCase();(l.toLowerCase().includes(a)||u.includes(a))&&s.push({name:o,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==l&&i(d,c+1)}catch(e){}})}catch(e){}},"searchRecursively");return i(t),s.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),o=n===a,s=r===a;if(o&&!s)return-1;if(!o&&s)return 1;const i=n.split("/").pop()||"",c=r.split("/").pop()||"",l=i.includes(a),d=c.includes(a);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)}),s.slice(0,50)},[]),y=j(e=>{try{const t=S(e),s=[],a=process.cwd(),i=loadGitignore(a);"/"!==e&&s.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=o(e,t);try{const e=k(r),o=n(a,r);if(i.ignores(o))return;s.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(s),m(0),p(0)}catch{}},[]);U(()=>{if(s.trim()){const e=f(s);d(e),m(0),p(0)}else y(i)},[i,y,s,f]),V((n,r)=>{if(r.escape)t();else if(r.upArrow)m(e=>{const t=Math.max(0,e-1);return t<g&&p(t),t});else if(r.downArrow)m(e=>{const t=Math.min(l.length-1,e+1);return t>=g+h&&p(t-h+1),t});else{if(r.rightArrow){const e=l[u];if(!e)return;return void(e.isDirectory&&!s.trim()&&c(a(e.path)))}if(r.return){const t=l[u];if(!t)return;return void e(t.path)}}});const E=l.slice(g,g+h);return O.createElement(W,{flexDirection:"column",paddingLeft:1},O.createElement(W,{marginBottom:1,flexDirection:"column"},O.createElement(H,{color:"dim"},s.trim()?`Searching for: "${s}"`:`Files: ${i}`),O.createElement(H,{color:"dim"},s.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===E.length?O.createElement(H,{color:"dim"},s.trim()?`No files found matching "${s}"`:"No files found in this directory"):E.map((e,t)=>{const n=g+t,r=e.name,o=n===u;return O.createElement(H,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList");wt(),Ct(),yn(),wt();var di=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20)return null;const r=__name(e=>e>=90?"red":e>=70?"yellow":"dim","getColor"),o=`context: ${n}% left before auto-compact`;return O.createElement(W,{paddingRight:1},O.createElement(H,{color:r(t)},o))},"ContextUsage");wt();var ui=__name(()=>{const[e,t]=_("continuous learning"),n=M([]),r=M(0),o=M(null),s=M(!1);U(()=>{const e=__name(e=>"analyzing"===e.type?(s.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):s.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(s.current=!1,void(n.current.length>0?(r.current=0,a()):t("continuous learning"))):void 0,"handleNewEvent"),a=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const s="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,a()},s)},"cycleThroughNextEvent");return Qs.on("new-event",e),()=>{Qs.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const a=9+e.length+9>100;let i=e;if(a){const t=100;e.length>t&&(i=e.substring(0,t-3)+"...")}else{const t=82;e.length>t&&(i=e.substring(0,t-3)+"...")}return O.createElement(W,null,!a&&O.createElement(H,{color:"green"},"● taste: "),O.createElement(H,null,i),!a&&O.createElement(H,{dimColor:!0}," (ctrl+t)"))},"LearningFeedMini"),mi=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?O.createElement(O.Fragment,null,t&&O.createElement(H,{dimColor:!0}," · "),O.createElement(H,{color:"connected"===e.type?"green":"yellow"},e.message)):null,"ConnectionIndicatorBadge"),gi=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,autoAcceptMode:r,tasteLearning:o,contextUsage:s,connectionIndicator:a,pendingExitKey:i,updateStatus:c,updateFailedInfo:l,currentProvider:d,showProviderInfo:u,isBashMode:m,shareInfo:g,showShareNotification:p,unshareNotificationMessage:h,tasteNotificationMessage:f})=>{const y=e>=60;return O.createElement(O.Fragment,null,O.createElement(W,{flexDirection:"column",paddingLeft:1},r&&!i?O.createElement(O.Fragment,null,O.createElement(W,{flexDirection:"row",justifyContent:"space-between",width:e-1},O.createElement(W,{flexDirection:"row",columnGap:0},O.createElement(H,{color:"#E4CCFF"},"»» accept edits on "),O.createElement(H,{dimColor:!0},"(shift+tab to cycle)")),y&&o&&O.createElement(ui,null)),O.createElement(W,{flexDirection:"row",justifyContent:"space-between",width:e-1},O.createElement(W,{flexDirection:"row",columnGap:0},O.createElement(H,{color:n?"#5FAFAF":void 0,dimColor:!n},t),O.createElement(mi,{indicator:a})),y&&s&&O.createElement(di,{usage:s}))):O.createElement(W,{flexDirection:"row",justifyContent:"space-between",width:e-1},O.createElement(W,{flexDirection:"row",columnGap:0},i?O.createElement(H,{dimColor:!0},"Press Ctrl+C again to exit"):O.createElement(H,{color:n?"#5FAFAF":void 0,dimColor:!n},t),!i&&O.createElement(mi,{indicator:a})),y&&O.createElement(W,{flexDirection:"column",alignItems:"flex-end"},o&&O.createElement(ui,null),s&&O.createElement(di,{usage:s}))),(c||l||u&&d)&&O.createElement(W,{flexDirection:"row",columnGap:1},c&&O.createElement(H,null,he.tick," ","Command Code"," updated:"," ",O.createElement(H,{dimColor:!0},"v",c.updatedFrom),O.createElement(H,{dimColor:!0}," ",he.arrowRight," "),O.createElement(H,null,"v",c.updatedTo)),!c&&l&&O.createElement(H,{color:"yellow",dimColor:!0},he.info," Update available:"," ",l.currentVersion," ",he.arrowRight," ",l.latestVersion),u&&d&&O.createElement(H,{color:"green",dimColor:!0},he.bullet," Provider:"," ",getProviderDisplayName(d)))),m&&O.createElement(W,{paddingLeft:1},O.createElement(H,{color:"green"},"! for bash mode")),p&&g&&O.createElement(W,{paddingLeft:1},O.createElement(H,{color:"#E4CCFF"},"SHARED: ",g.url," (copied to clipboard)")),h&&O.createElement(W,{paddingLeft:1},O.createElement(H,{color:h.includes("NOT SHARED")?"red":"#E4CCFF"},h)),f&&O.createElement(W,{paddingLeft:1},O.createElement(H,{color:"#E4CCFF"},f)))},"BottomIndicator");wt();var pi=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=_([]),[o,s]=_(0),[a,i]=_(!0);U(()=>{c()},[]);const c=__name(async()=>{i(!0);const e=await Bs.listSessions();r(e.slice(0,30)),i(!1)},"loadSessions");if(V((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)}),a)return O.createElement(W,{flexDirection:"column",paddingLeft:2},O.createElement(H,{color:"gray"},"Loading sessions..."));if(0===n.length)return O.createElement(W,{flexDirection:"column",paddingLeft:2},O.createElement(H,{color:"gray"},"No previous sessions found"),O.createElement(H,{color:"dim",dimColor:!0},"Press ESC to go back"));const l=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),d=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return O.createElement(W,{flexDirection:"column",paddingLeft:1,width:"100%"},O.createElement(H,{color:"cyan",bold:!0},"Resume Session"),O.createElement(H,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),O.createElement(W,{marginTop:1}),O.createElement(W,{columnGap:2,marginBottom:1},O.createElement(W,{width:5},O.createElement(H,{color:"gray"}," ")),O.createElement(W,{width:13},O.createElement(H,{color:"gray"},"Modified")),O.createElement(W,{width:20},O.createElement(H,{color:"gray"},"Git Branch")),O.createElement(W,{width:11},O.createElement(H,{color:"gray"},"# Messages")),O.createElement(W,null,O.createElement(H,{color:"gray"},"Summary"))),O.createElement(W,{columnGap:2},O.createElement(W,{flexDirection:"column",width:5},n.map((e,t)=>O.createElement(H,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${he.pointer} ${t+1}.`:` ${t+1}.`))),O.createElement(W,{flexDirection:"column",width:13},n.map((e,t)=>O.createElement(H,{key:`mod-${e.id}`,color:o===t?"white":"gray"},l(e.lastModified)))),O.createElement(W,{flexDirection:"column",width:20},n.map((e,t)=>O.createElement(H,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),O.createElement(W,{flexDirection:"column",width:11},n.map((e,t)=>O.createElement(H,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),O.createElement(W,{flexDirection:"column"},n.map((e,t)=>O.createElement(H,{key:`summary-${e.id}`,color:o===t?"white":"gray"},d(e.firstMessage))))))},"SessionsResumeTable");wt(),or();var hi=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=_(null),[s,a]=_(!1),i=M(!1),c=M(null),[l,d]=_(!1),[u,m]=_("connected"),g=M(null),p=M(null),h=j((e,t)=>{p.current&&(clearTimeout(p.current),p.current=null),m(e),d(!0),void 0!==t&&(p.current=setTimeout(()=>{d(!1)},t))},[]),f=j(()=>{p.current&&(clearTimeout(p.current),p.current=null)},[]),y=j(async(e=!1)=>{if(!i.current){i.current=!0;try{let t=c.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new Xn,c.current=t;const r=e?200:500;n=await t.connect(r)}const r=g.current;if(null===r?n?h("connected",3e3):h("disconnected",5e3):r!==n&&(n?h("connected",2e3):h("disconnected",5e3)),g.current=n,a(n),n){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),c.current=null),o(r)}else o(null)}catch{!0===g.current&&h("disconnected",5e3),g.current=!1,a(!1),o(null),c.current?.disconnect(),c.current=null}finally{i.current=!1}}},[h]);return U(()=>{if(!t||n)return;y(!0);const e=setInterval(()=>y(!1),500);return()=>{clearInterval(e),f(),c.current?.disconnect(),c.current=null}},[t,n,y,f]),{context:r,connected:s,refresh:y,connectionIndicator:{visible:l,message:"connected"===u?"IDE ✓":"IDE disconnected",type:u}}},"useVSCodeContext");wt();var fi=__name(e=>{const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:o}=e.activeFile;t.push(`File: ${n} (${r}, line ${o.line})`)}if(e.selection){const{text:n,startLine:r,endLine:o}=e.selection,s=e.activeFile?.language||"";t.push(`Selected lines ${r}-${o}:`),t.push(`\`\`\`${s}`),t.push(n),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt"),yi=["\n","\r","","[27;2;13~","[27;2;13~","[13;2u"],Ei=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isNewlineShortcutKey(e){const{inputChar:t,key:n,isPasting:r}=e;return!r&&(!(!n.return||!n.shift)||!(!n.ctrl||!n.return)||!(!n.ctrl||"j"!==t)||!("\r"!==t||n.return||n.ctrl||n.shift||n.meta)||yi.includes(t))}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isNewlineShortcutKey,"isNewlineShortcutKey"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var wi=__name(()=>O.createElement(W,{flexDirection:"column",paddingLeft:1},O.createElement(H,{color:"dim",bold:!0},"Available Shortcuts:"),O.createElement(W,{columnGap:4},O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"dim"},"! for bash mode"),O.createElement(H,{color:"dim"},"/ for commands"),O.createElement(H,{color:"dim"},"@ for file paths"),O.createElement(H,{color:"dim"},"shift + tab to toggle auto-accept")),O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"dim"},"double tap esc to clear input"),O.createElement(H,{color:"dim"},"ctrl + j / shift + ⏎ for newline"),O.createElement(H,{color:"dim"},"ctrl + g to open in editor"),O.createElement(H,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),bi=__name(({input:e,onSubmit:t,setInput:r,showCursor:o=!0,placeholder:s="Enter your input…",showFileList:a,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:E,updateFailedInfo:w,currentProvider:b,showProviderInfo:S,autoAcceptMode:k=!1,onToggleAutoAccept:C,hintMessage:v,historyManager:T,pendingExitKey:A=null,onOverlayVisibilityChange:P,onDoubleEscapeEmpty:x,onAltP:I,isProcessing:R=!1,ideContextEnabled:$=!0})=>{const[D,N]=_(0),[F,L]=_(!1),[z,G]=_(!1),[K,J]=_(!1),[Y,Q]=_(!1),[Z,X]=_(""),[ee,te]=_(!1),[ne,re]=_(0),[oe,se]=_([]),[ae,ie]=_([]),[ce,le]=_(""),de=M(!1),ue=M(!1),[me,ge]=_(-1),[pe,fe]=_(""),ye=M(0),{isEditorOpen:Ee,editorError:we,handleOpenInEditor:be,clearEditorError:Se}=useExternalEditor({input:e,setInput:r,setInputKey:N,onEditorClose:__name(()=>{de.current=!1},"onEditorClose")}),{handlePaste:ke,resetPasteState:Ce,isPasting:ve}=useBracketedPaste({input:e,detectedImages:ae,detectedContent:oe,setInput:r,setDetectedImages:ie,setDetectedContent:se,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey")}),{context:Te,connected:Ae,refresh:Pe,connectionIndicator:xe}=hi({enabled:$,paused:R}),{stdout:Ie}=q(),Re=Ie?.columns??80;U(()=>{const e=a||Y||ee;P?.(e)},[a,Y,ee,P]);const $e=j(()=>{r(""),G(!1),Q(!1),X(""),te(!1),se([]),ie([]),le(""),Ce(),ge(-1),fe(""),N(e=>e+1)},[r,Ce]);V(async(t,n)=>{if(n.upArrow){if(a||Y||ee)return;const t=e.indexOf("\n"),n=-1===t||ye.current<=t;if(0!==e.length&&-1===me&&!n)return;const o=T?.count()??0;if(0===o)return;-1===me&&fe(e);const s=Math.min(me+1,o-1);return void(s!==me&&(ge(s),r(T?.getAt(s)||""),N(e=>e+1)))}if(n.downArrow){if(a||Y||ee)return;if(-1===me)return;const t=e.lastIndexOf("\n");if(!(-1===t||ye.current>t))return;const n=me-1;return ge(n),r(-1===n?pe:T?.getAt(n)||""),void N(e=>e+1)}if(""===t||n.ctrl&&"c"===t)return;if(isCtrlKey({inputChar:t,key:n,letter:"g",ctrlCode:7}))return de.current=!0,void be();if(getIsExpandToolShortcut(n,t))return de.current=!0,r(e),N(e=>e+1),void setTimeout(()=>{de.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:n,isPasting:ve()}))return ue.current=!0,de.current=!0,r(e+"\n"),N(e=>e+1),void setTimeout(()=>{ue.current=!1,de.current=!1},0);if(n.meta&&n.backspace)return void $e();if(n.meta&&"w"===t)return de.current=!0,void $e();const o=n.ctrl&&"v"===t||Ei.includes(t),s=n.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e,n=await detectClipboardImage();if(n){const e=`[Image#${ae.length+1}]`;ie(e=>[...e,n]),r(t+e),N(e=>e+1)}return void(de.current=!0)}}else if(!n.ctrl&&!n.meta||"u"!==t){if(n.ctrl&&"z"===t?.toLowerCase())return J(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(n.escape){if(Y)return;if(ee)return te(!1),r(ce),void N(e=>e+1);const t=Date.now();return t-ne<500?(e.length>0?$e():x?.(),re(0)):re(t),L(!1),void G(!1)}F&&(n.backspace||n.delete)&&0===e.length&&L(!1)}});const De=j(async t=>{if(Ee)return;const n=removeAltPCharacter(t);if(null!==n)return r(n),void I?.();if(await ke(t))return;if(de.current)return void(de.current=!1);-1!==me&&ge(-1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!F)return L(!0),r(""),void N(e=>e+1);if("!"===s&&!z)return L(!1),G(!0),r(""),void N(e=>e+1)}if("/"!==s||Y||"/"!==t||(Q(!0),X("")),Y&&!t.startsWith("/")&&(Q(!1),X("")),Y&&t.startsWith("/")){const e=t.substring(1);X(e)}"@"!==s||a||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(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),n=!e.includes(" "),r=c>0?t[c-1]:"";n&&isPrecededByWhitespace(r)&&(i(!0),l(e))}if(a)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)}}F&&(t!==e||t.length<e.length)&&L(!1),we&&Se(),0===t.length&&(G(!1),Q(!1),X(""),te(!1),ie([]),se([]),l(""),le(""),Ce()),r(t)},[F,e,r,a,i,Y,z,ae,me,ke,Ce,I,we,Se,Ee]),Ne=j(async()=>{if(Pe(),F)return void L(!1);let n=e.trim();if(!z&&n.startsWith("/"))return T?.add(n),d&&d(n),G(!1),Q(!1),X(""),ie([]),se([]),ge(-1),void fe("");n.length>0&&T?.add(n),ge(-1),fe("");let r=[];const o=ae.length>0,s=oe.length>0;if(!z&&o){const e=[];ae.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!z&&s){let e=n;oe.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:z?"bash":"user",images:r,ideContext:Te?fi(Te):void 0}),G(!1),Q(!1),X(""),ie([]),se([])},[t,d,F,e,z,ae,oe,T,Pe]),Fe=j(t=>{const o=n(process.cwd(),t);let s;if(a&&""!==c){const t=e.lastIndexOf("@");s=-1!==t?e.substring(0,t+1)+o+" ":o+" "}else s=`${e}${o} `;r(s),i(!1),l(""),N(e=>e+1)},[r,i,e,a,c,l]),Le=j(()=>{i(!1),l("")},[i,l]),Oe=j(t=>{if("/resume"===t)T?.add(t),ge(-1),fe(""),le(e),Q(!1),X(""),te(!0),r(""),N(e=>e+1);else{const e=Object.values(ai).includes(t);Q(!1),X(""),e?(T?.add(t),ge(-1),fe(""),r(""),N(e=>e+1),d&&d(t)):(r(t+" "),N(e=>e+1))}},[d,r,e,T]),_e=j(()=>{Q(!1),X(""),r(""),ge(-1),fe(""),N(e=>e+1)},[r]),Me=j(e=>{te(!1),r(""),le(""),ge(-1),fe(""),N(e=>e+1),d&&d(`/resume:${e}`)},[d,r]),Ue=j(()=>{te(!1),r(ce),ge(-1),fe(""),N(e=>e+1)},[ce,r]),je=j(e=>{ye.current=e},[]),Be=B(()=>k||Ae?!F&&!ee:!F&&0===e.length&&!z&&!ee,[F,e,z,ee,k,Ae]),We=__name(()=>F||a||Y||ee||K?0:Be||A||z?3:4,"getBottomMargin"),He=__name(()=>!(!Ae||!Te?.selection&&!Te?.activeFile?.relativePath),"hasIDEContext"),ze=__name(()=>{const e=Ae?Te?.selection:null;if(e)return`${e.lineCount} lines selected`;const t=Ae?Te?.activeFile:null;if(t?.relativePath){const e=t.relativePath.split("/").pop()||"",n=Re<80?15:Re<120?25:40;return`In ${e.length>n?e.slice(0,n-1)+"…":e}`}return"? for shortcuts"},"getIndicatorText");return O.createElement(W,{width:"100%",flexDirection:"column",marginBottom:We()},!ee&&O.createElement(W,{flexDirection:"column",width:"100%"},O.createElement(H,{color:z?"green":"gray"},he.line.repeat(Re)),O.createElement(TextInput,{key:D,value:e,placeholder:Ee?"Save and close the editor to continue...":s,onChange:De,onSubmit:()=>{ue.current?ue.current=!1:a||Y||ee||Ee||Ne()},showCursor:!Ee&&o,onCursorChange:je,prefix:`${z?"!":he.pointer} `,prefixColor:z?"green":"white"}),O.createElement(H,{color:z?"green":"gray"},he.line.repeat(Re))),F&&O.createElement(wi,null),K&&O.createElement(W,{paddingTop:1},O.createElement(H,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),a&&O.createElement(li,{onSelectFile:Fe,onClose:Le,searchQuery:c}),Y&&O.createElement(ci,{onSelectCommand:Oe,onClose:_e,searchQuery:Z}),ee&&O.createElement(pi,{onSelectSession:Me,onClose:Ue}),(Be||A)&&O.createElement(gi,{termWidth:Re,indicatorText:ze(),isIDEIndicator:He(),autoAcceptMode:k,tasteLearning:m,contextUsage:u,connectionIndicator:xe,pendingExitKey:A,updateStatus:E,updateFailedInfo:w,currentProvider:b,showProviderInfo:S,isBashMode:z,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y}),we&&O.createElement(W,{paddingLeft:1,flexDirection:"column"},O.createElement(H,{color:"yellow"},we)))},"InputBox"),Si=O.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:a,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:E,tasteNotificationMessage:w,updateStatus:b,updateFailedInfo:S,currentProvider:k,showProviderInfo:C,autoAcceptMode:v,onToggleAutoAccept:T,hintMessage:A,historyManager:P,pendingExitKey:x,onResetPendingExitKey:I,onDoubleEscapeEmpty:R,retryAttempt:$,onAltP:D})=>{const[N,F]=_(0),L=M(o);return U(()=>{x&&o!==L.current&&o.length>0&&I?.(),L.current=o},[o,x,I]),U(()=>{if(!t)return void F(0);const e=setInterval(()=>{F(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),O.createElement(W,{flexDirection:"column"},O.createElement(ni,{messages:e}),O.createElement(W,{flexDirection:"row",justifyContent:"space-between"},O.createElement(W,{flexDirection:"column"},(t||n.isExecuting)&&null===$&&O.createElement(Qa,{tokens:m,timeElapsed:N,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),A&&O.createElement(W,{marginLeft:1},O.createElement(H,{dimColor:!0}," ","⎿"," Tip: ",A)))),O.createElement(bi,{input:o,setInput:s,onSubmit:a,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:E,tasteNotificationMessage:w,updateStatus:b,updateFailedInfo:S,currentProvider:k,showProviderInfo:C,autoAcceptMode:v,onToggleAutoAccept:T,hintMessage:A,historyManager:P,pendingExitKey:!x||t||n.isExecuting?null:x,onDoubleEscapeEmpty:R,onAltP:D,isProcessing:t}))});wt();var ki=__name(({onClose:e})=>{const[t,n]=_(Qs.getEvents());V((t,n)=>{n.ctrl&&"t"===t&&(ma(),e())},{isActive:!0}),U(()=>{const e=__name(()=>{n(Qs.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return Qs.on("new-event",e),Qs.on("cleared",t),()=>{Qs.off("new-event",e),Qs.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`confidence: ${parseFloat(e).toString()}%`}const a={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:a,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"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"),a=__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 O.createElement(W,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(Be,{name:"vice"},O.createElement(H,null,_r()))),O.createElement(W,{marginBottom:1,width:"100%",justifyContent:"space-between"},O.createElement(W,null,O.createElement(H,{bold:!0},"Learning Feed"),O.createElement(H,{dimColor:!0}," - Real-time taste learning activity")),O.createElement(H,{dimColor:!0},"Press ctrl+t to close")),O.createElement(W,{flexDirection:"column"},0===t.length?O.createElement(W,null,O.createElement(H,{dimColor:!0},"No learning events yet...")):O.createElement(W,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:i}=o(e.message),c="moved"===t?a(e.details):null,l="upgraded"===t||"downgraded"===t?s(r):null;return O.createElement(W,{key:e.id,marginBottom:1},O.createElement(W,{flexDirection:"column"},O.createElement(W,null,O.createElement(H,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),c?O.createElement(H,{dimColor:!0}," (",c.fullPath,")"):e.details?O.createElement(H,{dimColor:!0}," (",e.details,")"):null),O.createElement(W,{marginLeft:1},O.createElement(H,{dimColor:!0},"⎿"," "),c?O.createElement(O.Fragment,null,O.createElement(H,null,c.category," package ("),O.createElement(H,{dimColor:!0},c.oldPath),O.createElement(H,null," → ",c.newPath),O.createElement(H,null,")")):l?O.createElement(O.Fragment,null,O.createElement(H,null,l.text," ("),O.createElement(H,{dimColor:!0},"confidence: "),O.createElement(H,{dimColor:!0},l.oldPercent,"%"),O.createElement(H,null," → "),O.createElement(H,{color:l.diff>0?"green":"red"},l.newPercent,"%"),O.createElement(H,null,")")):O.createElement(O.Fragment,null,O.createElement(H,null,r),i&&O.createElement(H,{dimColor:!0}," (",i,")")))))}return O.createElement(W,{key:e.id,marginBottom:1},O.createElement(H,{dimColor:!0},he.pointerSmall," ",e.message))}))))},"LearningFeedFull");wt(),Ct(),Ft();var Ci=__name(({onClose:e})=>{const[t,n]=_([]),[r,o]=_(0),[s,a]=_(!0),[i,c]=_(null);U(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),a(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),a(!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(V((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]))}),s)return O.createElement(W,{paddingLeft:1,paddingTop:1},O.createElement(H,{color:"dim"},"Loading memory files..."));if(i)return O.createElement(W,{paddingLeft:1,paddingTop:1},O.createElement(H,{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 O.createElement(W,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},O.createElement(W,null,O.createElement(H,{color:"white",bold:!0},"Select memory to edit:")),O.createElement(W,{columnGap:4,marginTop:1},O.createElement(W,{flexDirection:"column"},u.map((e,t)=>O.createElement(H,{key:t,color:r===t?"white":"dim"},r===t?`${It} `:" ",e.label))),O.createElement(W,{flexDirection:"column"},u.map((e,t)=>O.createElement(H,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector");wt(),wt(),wt();var vi=class extends He{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}list(e,t=!1,n=""){let r=super.list(e,t,n);return r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),r}},Ti=new We;Ti.setOptions({renderer:new vi({strong:J.bold,em:J.italic,del:J.strikethrough,codespan:J.yellow,code:J.yellow,heading:J.bold.underline,firstHeading:J.bold.underline,link:J.cyan,href:J.cyan.underline,blockquote:J.gray.italic,table:J.reset,hr:J.reset,paragraph:J.reset,html:J.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var Ai=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=B(()=>{if(!e)return"";const t=[],n=e.replace(Ai,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=Ti.parse(n);return"string"!=typeof r?e:r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").trim()}catch{return e}},[e]);return O.createElement(H,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return O.createElement(W,null,O.createElement(H,null,he.nodejs),O.createElement(W,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},O.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage"),wt(),Ft();var Pi={"Interrupted by user":"Interrupted by user","Insufficient credits":Pt};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&&Pi[e]||e;return O.createElement(W,{paddingX:1,backgroundColor:o?void 0:"#333333"},O.createElement(H,{color:o?"red":"#AAAAAA",bold:!o},he.pointer),O.createElement(W,{marginLeft:1},O.createElement(H,{color:o?"red":"white",wrap:"wrap"},s)))}__name(UserMessage,"UserMessage"),wt(),Dt(),En();var xi="#6B7280";function truncateToolOutputForDisplay({output:e,maxLines:t=1}){const n=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),r=n.split("\n");return r.length<=t?n:r.slice(0,t).join("\n")}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,dimDiff:a=!1,maxLines:i}){const c=ze.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(O.createElement(W,{key:`${t}-${r}-removed`,width:"100%"},O.createElement(H,{color:"gray",dimColor:a},u.toString().padStart(3)," "),O.createElement(W,{backgroundColor:"#712F37"},O.createElement(H,{dimColor:a},"-"),O.createElement(H,{dimColor:a}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(O.createElement(W,{key:`${t}-${r}-added`,width:"100%"},O.createElement(H,{color:"gray",dimColor:a},u.toString().padStart(3)," "),O.createElement(W,{backgroundColor:"#325B30"},O.createElement(H,{dimColor:a},"+"),O.createElement(H,{dimColor:a}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:O.createElement(W,{flexDirection:"column"},o&&!r&&O.createElement(H,{color:"gray"},"Updated"," ",O.createElement(H,{color:"white",bold:!0},n)," ","with ",O.createElement(H,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",O.createElement(H,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&O.createElement(H,{color:"red"},"Rejected update to",O.createElement(H,{color:"red"},` ${n}`)),O.createElement(W,{flexDirection:"column",marginLeft:s},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=es(e);return t?O.createElement(W,{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 O.createElement(W,{key:e.id||t,flexDirection:"row"},O.createElement(W,{width:2},O.createElement(H,{color:r},n)),O.createElement(H,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):O.createElement(H,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:a=!1}){const i="Thinking…"===e,c="Todos"===e,l="Edit"===e,d=!0===s?.isTasteFile,u=s?.tasteCategory,m=!0===s?.permissionDenied,g=!i&&!c&&!d,{name:p}=detectTerminal(),h="iTerm2"===p?"shift":"ctrl",f=!0===s?.isAgent,y=t&&f?(()=>{const e=t.split(/[.\n]/)[0];return e?e+(t.includes(".")||t.includes("\n")?".":""):t})():t,E=!i&&y&&!d,w=s?.status,b=s?.tokensUsed||0,S="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0;let k,C;if(r)k="yellow",C="→";else if(o)k="red",C=he.nodejs;else if(i)k=xi,C="✻";else if(c&&n){const e=es(n),t=e?.every(e=>"completed"===e.status);k=t?"#22C55E":"#D4A017",C=he.nodejs}else k="#22C55E",C=he.nodejs;return O.createElement(W,null,i&&O.createElement(H,{color:k},C),O.createElement(W,{flexDirection:"column",marginLeft:i?1:0},O.createElement(W,null,i?O.createElement(O.Fragment,null,O.createElement(H,{color:xi},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!a&&O.createElement(H,{dimColor:!0},"(",`${h}+o to expand`,")")):d?O.createElement(O.Fragment,null,O.createElement(H,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),O.createElement(H,null," ","Using your taste ",u?"package of ":"packages",u&&O.createElement(H,{bold:!0},u))):O.createElement(H,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),E&&O.createElement(H,null," ",O.createElement(Markdown,null,`(${y})`))),f&&("running"===w||n)&&O.createElement(W,{columnGap:1,marginLeft:g?1:0},g&&O.createElement(H,null,"⎿"," "),"running"===w?O.createElement(H,{color:"gray"},"Running (",formatTime2(S)," | ",formatTokens(b),")"):"interrupted"===w?O.createElement(H,{color:"red",wrap:"wrap"},"Interrupted by user"):"error"===w||o?O.createElement(H,{color:"red",wrap:"wrap"},n," (",formatTime2(S)," | ",formatTokens(b),")"):"Interrupted by user"===n?O.createElement(O.Fragment,null,O.createElement(H,{color:"red",wrap:"wrap"},"Interrupted by user")):O.createElement(O.Fragment,null,O.createElement(H,{wrap:"wrap"},"Done"),O.createElement(H,{color:"gray"}," ","(",formatTime2(S)," | ",formatTokens(b),")"))),n&&!d&&!f&&O.createElement(W,{columnGap:1,marginLeft:g?1:0},g&&O.createElement(H,null,"⎿"," "),c?formatTodosForDisplay(n):i?a?O.createElement(W,{width:"100%",flexDirection:"column"},O.createElement(H,null," "),O.createElement(H,{color:xi,wrap:"wrap",italic:!0},n)):null:l&&s?.oldValue&&s?.newValue?O.createElement(W,{flexDirection:"column"},(()=>{const e=a?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:m,permissionDenied:m,maxLines:e});return O.createElement(O.Fragment,null,n,r&&O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"… (",o-10," more lines) (",`${h}+o to expand`,")")))})(),m&&n&&O.createElement(W,{marginTop:1},O.createElement(H,{color:"red",wrap:"wrap"},n))):O.createElement(W,{width:"100%"},O.createElement(H,{color:o?"red":"",wrap:"wrap"},a?n:O.createElement(O.Fragment,null,truncateToolOutputForDisplay({output:n,maxLines:"Question"===e?10:1}),n.includes("\n")&&"Question"!==e&&O.createElement(H,{dimColor:!0}," ","(",`${h}+o to expand`,")"))))),r&&!f&&O.createElement(W,{columnGap:1,marginLeft:1},O.createElement(H,null,"⎿"," "),O.createElement(H,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,s;return n?(o="yellow",s="→"):r?(o="red",s="✗"):(o="green",s="✓"),O.createElement(W,null,O.createElement(H,{color:o},s),O.createElement(W,{flexDirection:"column",marginLeft:1},O.createElement(W,null,O.createElement(H,{color:"gray"},"$ "),O.createElement(H,{color:o,bold:!0},e)),O.createElement(W,{columnGap:1,marginLeft:1},O.createElement(H,null,"⎿"," "),O.createElement(H,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),wt(),__name(BashMessage,"BashMessage"),wt(),wt(),Ct();wt(),Ct();var Ii="Coding agent that continuously learns your taste of writing code.",Ri=34,$i=[{key:"Shift+Tab",description:"Toggle auto-accept mode"},{key:"Ctrl+T",description:"Toggle learning feed"},{key:"Ctrl+O",description:"Toggle expanded tool output (Shift+O in iTerm2)"},{key:"Alt+P",description:"Quick model switch (Option+P on macOS)"},{key:"Ctrl+G",description:"Open input in external editor ($EDITOR)"},{key:"Esc Esc",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],Di=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume",description:"Resume a conversation"},{key:"-c, --continue",description:"Continue the last conversation"},{key:"-t, --trust",description:"Auto-trust project (skip initial permission prompt)"},{key:"-p, --print [query]",description:"Run in non-interactive mode, output response and exit"},{key:"--dangerously-skip-permissions",description:"Bypass all permission prompts (use with caution)"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"--ide-setup",description:"Setup extension for editor context"},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],Ni=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/model",description:"Switch between Command Code models"},{key:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{key:"/compact",description:"Compact the conversation history"},{key:"/ide",description:"Setup extension to fetch editor context"},{key:"/login",description:"Authenticate with CommandCode via browser"},{key:"/logout",description:"Remove stored authentication"},{key:"/feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"/exit",description:"Exit the REPL"}],Fi=[{key:"cmd info",description:"Display system information"},{key:"cmd config",description:"Manage CLI configuration"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Li=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Oi=[{key:"cmd",description:"Start interactive session"},{key:'cmd "fix the login bug"',description:"Start with a task"},{key:"cmd -c",description:"Continue last conversation"},{key:"cmd -r",description:"Resume a past session"},{key:'cmd -p "your query"',description:"Run non-interactive query"},{key:"cmd info",description:"Show system information"},{key:'cmd feedback "title"',description:"Open feedback form with title"}],_i='Start with a prompt: cmd "fix the login bug"';wt(),Pn();var Mi="cmd";function getBinNames(){const e=getPackageJson();return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name]:[Mi]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||Mi;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||Mi}catch{return Mi}}function HelpMessage(){const e=getInvokedCommandName(),t=B(()=>Ni.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return O.createElement(W,{flexDirection:"column",paddingY:1},O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(W,null,O.createElement(H,{bold:!0},"Command Code"),O.createElement(H,{color:"gray"}," v","0.10.16")),O.createElement(H,{color:"gray"},Ii)),O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(H,{bold:!0},"Usage"),O.createElement(W,{paddingLeft:2},O.createElement(H,null,e," <command> [options]"))),O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(H,{bold:!0},"Options"),O.createElement(W,{flexDirection:"column",paddingLeft:2},Di.map(t=>O.createElement(W,{key:t.key},O.createElement(H,null,t.key.replace(/^cmd/,e).padEnd(Ri)),O.createElement(H,{color:"gray"},t.description))))),O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(H,{bold:!0},"Commands"),O.createElement(W,{flexDirection:"column",paddingLeft:2},Fi.map(t=>O.createElement(W,{key:t.key},O.createElement(H,null,t.key.replace(/^cmd/,e).padEnd(Ri)),O.createElement(H,{color:"gray"},t.description))))),O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(H,{bold:!0},"Slash Commands"),O.createElement(W,{flexDirection:"column",paddingLeft:2},t.map(e=>O.createElement(W,{key:e.key},O.createElement(H,null,e.key.padEnd(Ri)),O.createElement(H,{color:"gray"},e.description))))),O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(H,{bold:!0},"Keyboard Shortcuts"),O.createElement(W,{flexDirection:"column",paddingLeft:2},$i.map(e=>O.createElement(W,{key:e.key},O.createElement(H,null,e.key.padEnd(Ri)),O.createElement(H,{color:"gray"},e.description))))),O.createElement(W,{flexDirection:"column",marginBottom:1},O.createElement(H,{bold:!0},"Examples"),O.createElement(W,{flexDirection:"column",paddingLeft:2},Oi.map(t=>O.createElement(W,{key:t.key},O.createElement(H,null,t.key.replace(/^cmd/,e).padEnd(Ri)),O.createElement(H,{color:"gray"},t.description))))),O.createElement(W,{marginBottom:1},O.createElement(H,{color:"cyan"},"❯"),O.createElement(H,{color:"gray"}," ",_i.replace(/cmd/,e))),O.createElement(W,{flexDirection:"column"},O.createElement(H,{bold:!0},"Links"),O.createElement(W,{flexDirection:"column",paddingLeft:2},Li.map(e=>O.createElement(W,{key:e.key},O.createElement(H,null,e.key.padEnd(Ri)),O.createElement(H,{color:"cyan"},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?O.createElement(HelpMessage,null):O.createElement(W,{flexDirection:"column"},O.createElement(H,{wrap:"wrap"},O.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return O.createElement(W,null,O.createElement(H,{color:"red"},t?he.pointer:he.warning),O.createElement(W,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?O.createElement(H,{color:"red",wrap:"wrap"},e):O.createElement(Markdown,{color:"red"},e)))}function InfoMessage({content:e}){return O.createElement(W,null,O.createElement(H,{dimColor:!0},he.info),O.createElement(W,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},O.createElement(Markdown,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return O.createElement(W,{flexDirection:"column",marginBottom:0,marginTop:-1},O.createElement(W,{columnGap:1},O.createElement(H,null,"⎿"," "),O.createElement(W,{flexGrow:1,flexShrink:1,minWidth:0},O.createElement(H,{color:n?"yellow":void 0},e))),t&&O.createElement(W,{marginLeft:3},O.createElement(H,{dimColor:!0},"See ",t)))}function IDEStatusMessage({status:e,ide:t,details:n}){return O.createElement(W,{flexDirection:"column"},O.createElement(W,null,"connected"===e&&O.createElement(H,null,O.createElement(H,{color:"green"},he.tick),O.createElement(H,null," Connected to "),O.createElement(H,{color:"cyan"},t)),"installed"===e&&O.createElement(H,null,O.createElement(H,{color:"green"},he.tick),O.createElement(H,null," Installed for "),O.createElement(H,{color:"cyan"},t)),"needs_reload"===e&&O.createElement(H,null,O.createElement(H,{color:"yellow"},he.circle),O.createElement(H,null," "),O.createElement(H,{color:"cyan"},t),O.createElement(H,null," extension needs reload")),"failed"===e&&O.createElement(H,null,O.createElement(H,{color:"red"},he.cross),O.createElement(H,null," Install failed")),"not_in_ide"===e&&O.createElement(H,null,O.createElement(H,{color:"yellow"},he.circle),O.createElement(H,null," Not in IDE"))),n?.map((e,t)=>O.createElement(H,{key:t,dimColor:!0}," ",e)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),yn(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),wt(),__name(ErrorMessage,"ErrorMessage"),wt(),__name(InfoMessage,"InfoMessage"),wt(),__name(CommandResultMessage,"CommandResultMessage"),wt(),__name(IDEStatusMessage,"IDEStatusMessage"),Pn(),Ct(),wt(),wt(),Ct(),mn(),wn(),Pn(),wt(),Ct();var Ui=t.join(g.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(Ui);f.existsSync(e)||f.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!f.existsSync(Ui))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=f.readFileSync(Ui,"utf-8");return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null,...JSON.parse(e)}}catch{return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}}}function writeUpdatesConfig(e){ensureDir(),f.writeFileSync(Ui,JSON.stringify(e,null,2))}function updateUpdatesConfig(e){writeUpdatesConfig({...readUpdatesConfig(),...e})}function shouldCheckForUpdate(){const e=readUpdatesConfig();return!!e.autoUpdate&&Date.now()-e.lastCheckedAt>=e.checkIntervalMs}function recordUpdateCheck(){updateUpdatesConfig({lastCheckedAt:Date.now()})}function setPendingUpdate(e){updateUpdatesConfig({lastCheckedAt:Date.now(),pending:e})}function clearPendingUpdate(){updateUpdatesConfig({pending:null})}function getPendingUpdate(e){const t=readUpdatesConfig();return t.pending?t.pending.currentVersion!==e?(clearPendingUpdate(),null):t.pending:null}__name(function getDefaultConfig(){return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}},"getDefaultConfig"),__name(ensureDir,"ensureDir"),__name(readUpdatesConfig,"readUpdatesConfig"),__name(writeUpdatesConfig,"writeUpdatesConfig"),__name(updateUpdatesConfig,"updateUpdatesConfig"),__name(shouldCheckForUpdate,"shouldCheckForUpdate"),__name(recordUpdateCheck,"recordUpdateCheck"),__name(setPendingUpdate,"setPendingUpdate"),__name(clearPendingUpdate,"clearPendingUpdate"),__name(getPendingUpdate,"getPendingUpdate"),wn();var ji=ue(T),Bi=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=v("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return Bi.version}function isAlphaVersion(e){return e.includes("alpha")}function filterVersions(e){return{stable:e.filter(e=>!e.includes("alpha")),alpha:e.filter(e=>e.includes("alpha"))}}function getLatestVersion(e){return 0===e.length?null:e.sort(Ge.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Ge.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Ge.gt(t,e))return{latestVersion:t,updateAvailable:!0}}return{latestVersion:e,updateAvailable:!1}}async function checkForUpdateAvailable(){const e=fetchVersions();if(!e)return null;const t=getCurrentVersion(),{stable:n,alpha:r}=filterVersions(e),{latestVersion:o,updateAvailable:s}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:o,updateAvailable:s}}async function executeUpdate(e){try{return await ji(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;if(!Ge.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=xe(`Updating ${e} → ${t.targetVersion}`).start(),r=await executeUpdate(t.targetVersion);if(clearPendingUpdate(),!r)return n.fail("Update failed"),void console.log("Run `cmd update` to try again.");n.succeed(`Updated to v${t.targetVersion}`)}async function performAutoUpdate(e){const{silent:t,updateInfo:n,onStart:r}=e||{};if(isLocalDevelopmentBuild())return{success:!1};const o=n||await checkForUpdateAvailable();return o?.updateAvailable?(r?.(o.latestVersion),await executeUpdate(o.latestVersion)?{success:!0,updateInfo:o}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:o})):{success:!1}}function getCurrentGitBranch(){try{return v("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","ignore"],cwd:process.cwd()}).trim()||null}catch(e){return null}}function getGitHeaderInfo(){return{branch:getCurrentGitBranch(),isLocal:isLocalDevelopmentBuild()}}function getModelShortName(e){const t=Object.values(gt).find(t=>t.id===e);return t?t.name.toLowerCase().replace(" ","-"):e.includes("sonnet")?"sonnet-4.5":e.includes("opus-4-6")?"opus-4.6":e.includes("opus")?"opus-4.5":"sonnet-4.5"}__name(shouldSkipUpdateSystem,"shouldSkipUpdateSystem"),__name(fetchVersions,"fetchVersions"),__name(getCurrentVersion,"getCurrentVersion"),__name(isAlphaVersion,"isAlphaVersion"),__name(filterVersions,"filterVersions"),__name(getLatestVersion,"getLatestVersion"),__name(determineUpdateTarget,"determineUpdateTarget"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(executeUpdate,"executeUpdate"),__name(checkForUpdateAsync,"checkForUpdateAsync"),__name(doUpdateCheck,"doUpdateCheck"),__name(maybeRunPendingUpdate,"maybeRunPendingUpdate"),__name(performAutoUpdate,"performAutoUpdate"),__name(getCurrentGitBranch,"getCurrentGitBranch"),__name(getGitHeaderInfo,"getGitHeaderInfo"),yn(),__name(getModelShortName,"getModelShortName");var Wi=O.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const s=t?["header",...e]:e,a=_r();getTerminalWidth();const i=getPackageJson().version||"0.0.0",c=o?getModelShortName(o):"sonnet-4.5",l=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",u=l.replace(d,"~"),m=getGitHeaderInfo();return O.createElement(z,{items:s,key:n,style:{width:"100%"}},e=>{if("header"===e)return O.createElement(W,{key:"header",marginBottom:1,flexDirection:"column"},O.createElement(Be,{name:"vice"},O.createElement(H,null,a.trimEnd())),O.createElement(W,{flexDirection:"column",marginTop:1},O.createElement(W,null,O.createElement(H,{color:"gray"},"# "),O.createElement(H,{bold:!0},"Command Code"),O.createElement(H,{color:"gray"}," v",i)),O.createElement(H,{color:"gray"},"# models: ",c," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),O.createElement(W,null,O.createElement(H,{color:"gray"},"# ",u,m&&m.isLocal&&m.branch&&O.createElement(H,{color:"gray"}," (branch: ",m.branch,")")))));const t=e,n=(()=>{switch(t.role){case"user":return O.createElement(UserMessage,{content:t.input});case"assistant":return O.createElement(AssistantMessage,{content:t.input});case"tool":return O.createElement(ToolMessage,{name:Zo(t.name||""),input:t.input,output:t.output||"",isPending:Jo(t),hasError:Ko(t),metadata:t.metadata,expandedOutput:r});case"bash":return O.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:Jo(t),hasError:Ko(t)});case"system":return O.createElement(SystemMessage,{content:t.input});case"info":return O.createElement(InfoMessage,{content:t.input});case"error":return O.createElement(ErrorMessage,{content:t.input});case"command-result":return O.createElement(CommandResultMessage,{message:t.input,details:t.details,hasError:t.hasError??!1});case"ide-status":return O.createElement(IDEStatusMessage,{status:t.status,ide:t.ide,details:t.details});default:return O.createElement(O.Fragment,null)}})();return O.createElement(W,{key:t.id,marginBottom:1,width:"90%"},n)})});function getModelOptions(){return Object.values(gt).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}wt(),Ct(),__name(getModelOptions,"getModelOptions");var Hi=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");V((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0;return O.createElement(W,{flexDirection:"column",paddingX:0,width:"100%"},O.createElement(W,null,O.createElement(H,{color:"#E4CCFF",bold:!0},"Select model")),O.createElement(W,{marginBottom:1},O.createElement(H,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),O.createElement(Ue,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const o=r.find(e=>e.label===t),s=o?.value===n,a=o?.description?`${o.label} (${o.description})`:o?.label||t;return O.createElement(W,null,O.createElement(H,{color:e?"green":"gray"},` ${a.padEnd(24)}`),O.createElement(H,{color:e?"green":"gray"},o?.modelName),s&&O.createElement(H,{color:"green"}," ✓"))}}),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press "),O.createElement(H,{dimColor:!0,bold:!0},"Esc"),O.createElement(H,{dimColor:!0}," to cancel")))},"ModelSelector");wt(),Ct();var zi=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[o]=_(0),s=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",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}],a=__name(e=>{const t=s.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),i=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),c=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const n=t.basename(e.filePath),r=t.relative(process.cwd(),e.filePath);return r&&!r.startsWith("../")&&r.length<50?r:n||e.filePath}catch{return e.filePath}},"getDisplayPath"),l=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return O.createElement(W,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},O.createElement(W,{marginBottom:1},O.createElement(H,{bold:!0,color:"yellow"},`${l()} ${"edit"===e.action?c():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&O.createElement(W,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c(),marginLeft:0}).diffContent),O.createElement(W,{marginBottom:1},O.createElement(H,{bold:!0},"Do you want to ",i()," ",O.createElement(H,{color:"cyan"},c()),"?")),O.createElement(Ue,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:o,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:"cyan"},e?he.pointer:" "),itemComponent:({label:e,isSelected:t})=>O.createElement(H,{color:t?"cyan":"white"},e.includes("(shift+tab)")?O.createElement(O.Fragment,null,e.split("(shift+tab)")[0],O.createElement(H,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?O.createElement(O.Fragment,null,e.split("(")[0],O.createElement(H,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt");wt(),yn();var Gi=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");V((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,a=n&&-1===s;return O.createElement(W,{flexDirection:"column",paddingX:0,width:"100%"},O.createElement(W,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},O.createElement(W,null,O.createElement(H,{bold:!0},"Select AI Provider")),n&&O.createElement(W,{flexDirection:"row"},O.createElement(H,{dimColor:!0},"Current: "),O.createElement(H,{color:"green"},getProviderDisplayName(n)),a&&O.createElement(H,{color:"yellow"}," [OAuth enforced]"))),O.createElement(W,{marginBottom:0},O.createElement(H,{dimColor:!0},"Available Providers:")),O.createElement(Ue,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>O.createElement(H,{color:e?"cyan":"gray",bold:e},` ${t}`)}),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");wt();var qi=__name(({staticKey:e})=>O.createElement(z,{items:[{staticKey:e}],key:e},()=>O.createElement(H,{key:e},"\0")),"Responsive");function RetryMessage({attempt:e}){const[t,n]=_(0);if(U(()=>{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 O.createElement(W,{marginBottom:1},O.createElement(H,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}wt(),__name(RetryMessage,"RetryMessage"),wt(),Ft();var Vi=[{mode:"both",label:"Both",description:"Restore conversation and code (recommended)"},{mode:"conversation",label:"Conversation only",description:"Rewind conversation, keep current code"},{mode:"files",label:"Code only",description:"Restore code, keep conversation"}],Ki=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=B(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=_(Math.max(0,r.length-1)),[a,i]=_(Math.max(0,r.length-8)),[c,l]=_("checkpoint"),[d,u]=_(null),[m,g]=_(0),p=B(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),h=B(()=>p?Vi:Vi.filter(e=>"conversation"===e.mode),[p]);if(U(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),V((e,p)=>{p.escape?"mode"===c?(l("checkpoint"),u(null),g(0)):n():"checkpoint"===c?p.upArrow?s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t}):p.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(t-8+1),t}):p.return&&r.length>0&&(u(r[o]),l("mode"),g(0)):"mode"===c&&(p.upArrow?g(e=>Math.max(0,e-1)):p.downArrow?g(e=>Math.min(h.length-1,e+1)):p.return&&d&&h[m]&&t({messageId:d.messageId,mode:h[m].mode}))}),0===r.length)return O.createElement(W,{flexDirection:"column",paddingLeft:2,paddingTop:1},O.createElement(H,{color:"#E4CCFF",bold:!0},"Rewind"),O.createElement(H,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press "),O.createElement(H,{dimColor:!0,bold:!0},"Esc"),O.createElement(H,{dimColor:!0}," to close")));if("mode"===c&&d)return O.createElement(W,{flexDirection:"column",paddingLeft:2,paddingTop:1},O.createElement(H,{color:"#E4CCFF",bold:!0},"Rewind"),O.createElement(W,{marginBottom:1},O.createElement(H,{dimColor:!0},"Restore to: "),O.createElement(H,{color:"white"},truncateString2({text:d.userPrompt||"checkpoint",maxLength:50}))),O.createElement(W,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return O.createElement(W,{key:e.mode,flexDirection:"column"},O.createElement(W,{flexDirection:"row"},O.createElement(H,{color:n?"#E4CCFF":void 0},n?`${It} `:" "),O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:n?"#E4CCFF":"white"},e.label),O.createElement(H,{dimColor:!0},e.description))),!r&&O.createElement(H,null," "))})),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press "),O.createElement(H,{dimColor:!0,bold:!0},"Enter"),O.createElement(H,{dimColor:!0}," to confirm, "),O.createElement(H,{dimColor:!0,bold:!0},"Esc"),O.createElement(H,{dimColor:!0}," to go back")));const f=r.slice(a,a+8);return O.createElement(W,{flexDirection:"column",paddingLeft:2,paddingTop:1},O.createElement(H,{color:"#E4CCFF",bold:!0},"Rewind"),O.createElement(H,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),O.createElement(W,{marginTop:1}),O.createElement(W,{flexDirection:"column"},f.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,c=t===f.length-1,l=n===r.length-1;return O.createElement(W,{key:e.messageId,flexDirection:"column"},O.createElement(W,{flexDirection:"row"},O.createElement(H,{color:s?"#E4CCFF":void 0},s?`${It} `:" "),O.createElement(W,{flexDirection:"column"},O.createElement(W,null,O.createElement(H,{color:s?"#E4CCFF":"white"},truncateString2({text:e.userPrompt||"(no prompt)",maxLength:60})),O.createElement(H,{dimColor:!0}," • "),O.createElement(H,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),l&&" (latest)")),O.createElement(H,{dimColor:!0},i>0?`${i} file${i>1?"s":""} changed`:"No code changes"))),!c&&O.createElement(H,null," "))})),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press "),O.createElement(H,{dimColor:!0,bold:!0},"Enter"),O.createElement(H,{dimColor:!0}," to select, "),O.createElement(H,{dimColor:!0,bold:!0},"Esc"),O.createElement(H,{dimColor:!0}," to cancel")))},"RewindSelector");wt();var Ji=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=K(),[r,o]=_([]),[s,a]=_(0),[i,c]=_(!0),[l,d]=_(0),u=30;U(()=>{m()},[]);const m=__name(async()=>{c(!0);const e=await Bs.listSessions();o(e),c(!1)},"loadSessions");if(V((t,o)=>{o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t}):o.downArrow?a(e=>{const t=Math.min(r.length-1,e+1);return t>=l+u&&d(t-u+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),i)return O.createElement(W,{flexDirection:"column",paddingLeft:2,paddingTop:1},O.createElement(H,{color:"gray"},"Loading sessions..."));const g=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5),a=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:s<7?`${s} day${s>1?"s":""} ago`:1===a?"1 week ago":`${a} weeks ago`},"formatRelativeTime"),p=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return O.createElement(W,{flexDirection:"column"},O.createElement(H,{color:"gray"},"No sessions available"));const h=r.slice(l,l+u),f=l;return O.createElement(W,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>u&&O.createElement(W,{marginBottom:1},O.createElement(H,{color:"dim"},"Showing ",l+1,"-",Math.min(l+u,r.length)," ","of ",r.length," sessions",l>0&&" (↑ for more)",l+u<r.length&&" (↓ for more)")),O.createElement(W,{columnGap:2,marginBottom:1},O.createElement(W,{width:7},O.createElement(H,{color:"gray"}," ")),O.createElement(W,{width:13},O.createElement(H,{color:"gray"},"Modified")),O.createElement(W,{width:11},O.createElement(H,{color:"gray"},"# Messages")),O.createElement(W,{width:20},O.createElement(H,{color:"gray"},"Git Branch")),O.createElement(W,null,O.createElement(H,{color:"gray"},"Summary"))),O.createElement(W,{columnGap:2},O.createElement(W,{flexDirection:"column",width:7},h.map((e,t)=>{const n=f+t;return O.createElement(H,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${he.pointer} ${n+1}.`:` ${n+1}.`)})),O.createElement(W,{flexDirection:"column",width:13},h.map((e,t)=>{const n=f+t;return O.createElement(H,{key:`mod-${e.id}`,color:s===n?"white":"gray"},g(e.lastModified))})),O.createElement(W,{flexDirection:"column",width:11},h.map((e,t)=>{const n=f+t;return O.createElement(H,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),O.createElement(W,{flexDirection:"column",width:20},h.map((e,t)=>{const n=f+t;return O.createElement(H,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),O.createElement(W,{flexDirection:"column"},h.map((e,t)=>{const n=f+t;return O.createElement(H,{key:`summary-${e.id}`,color:s===n?"white":"gray"},p(e.firstMessage))}))))},"SessionTable");wt(),Ct();var Yi=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=_(0),o=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",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}],s=__name(e=>{const r=o.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),a=__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 O.createElement(W,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},O.createElement(W,{marginBottom:1},O.createElement(H,{bold:!0,color:"yellow"},"Execute Shell Command")),O.createElement(W,{marginBottom:1},O.createElement(H,{bold:!0},"Command Code needs to execute ",O.createElement(H,{color:"cyan"},a()),".")),e.workingDirectory&&O.createElement(W,{marginBottom:1},O.createElement(H,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&O.createElement(W,{marginBottom:1},O.createElement(H,{color:"gray",italic:!0},e.description)),O.createElement(Ue,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:"cyan"},e?he.pointer:" "),itemComponent:({label:e,isSelected:t})=>O.createElement(H,{color:t?"cyan":"white"},e.includes("(shift+tab)")?O.createElement(O.Fragment,null,e.split("(shift+tab)")[0],O.createElement(H,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt");wt();var Qi=__name(({onClose:e,staticKey:t})=>{const[n,r]=_([]),[o,s]=_(!0),[a,i]=_(null),{stdout:c}=q(),l=c?.columns??80,d=__name((e,t)=>e.length<=t?e:t<=3?e.substring(0,t):e.substring(0,t-3)+"...","truncateText");U(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),n=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];r(n)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=__name(async t=>{const r=n.find(e=>e.value===t.value);if(r)try{await qe([{file:r.filePath,line:1}]),ma(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(m()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelect");V((t,n)=>{n.escape&&(ma(),e())});const m=__name(()=>{const e=process.platform;return"win32"===e?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===e?"~/.zshrc":"~/.bashrc")},"getEditorSetupMessage");return o?O.createElement(W,{flexDirection:"column",paddingX:0,width:"100%"},O.createElement(H,{color:"#E4CCFF",bold:!0},"Agent Skills"),O.createElement(H,{dimColor:!0},"Loading skills...")):a?O.createElement(W,{flexDirection:"column",paddingX:0,width:"100%"},O.createElement(H,{color:"red",bold:!0},"Agent Skills"),O.createElement(H,{dimColor:!0},a),O.createElement(W,{marginTop:1}),O.createElement(H,{dimColor:!0},"Press ",O.createElement(H,{bold:!0},"Esc")," to close")):0===n.length?O.createElement(W,{flexDirection:"column",paddingX:0,width:"100%"},O.createElement(H,{color:"#E4CCFF",bold:!0},"Agent Skills"),O.createElement(W,{marginBottom:1},O.createElement(H,{dimColor:!0},"No skills found")),O.createElement(H,{dimColor:!0},"Create skills in:"),O.createElement(H,{dimColor:!0}," ~/.commandcode/skills/ (user)"),O.createElement(H,{dimColor:!0}," .commandcode/skills/ (project)"),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press ",O.createElement(H,{bold:!0},"Esc")," to close"))):O.createElement(W,{flexDirection:"column",paddingX:0,width:"100%"},O.createElement(W,null,O.createElement(H,{color:"#E4CCFF",bold:!0},"Agent Skills")),O.createElement(W,{marginBottom:1},O.createElement(H,{dimColor:!0},"Select a skill to open in your editor. Skills provide specialized guidance for coding tasks.")),O.createElement(Ue,{items:n,onSelect:u,initialIndex:0,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const r=n.find(e=>e.label===t),o=r?.location?` (${r.location})`:"",s=Math.max(30,l-35),a=r?.description?d(r.description,s):"";return O.createElement(W,null,O.createElement(H,{color:e?"green":"white"},` ${t}`),O.createElement(H,{color:"gray"},o.padEnd(25-t.length)),O.createElement(H,{color:"gray"},a))}}),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press ",O.createElement(H,{bold:!0},"Esc")," to cancel")))},"SkillsConfig");wt(),hn();var Zi=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=_(!1),[s,a]=_(!0);U(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{a(!1)}},"loadSettings")()},[]),V((t,n)=>{if(!n.return&&" "!==t)return n.escape?(ma(),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 s?O.createElement(W,{key:n,borderStyle:"single",borderColor:"blue",padding:1,flexDirection:"column"},O.createElement(H,{color:"blue",bold:!0},"Taste Settings"),O.createElement(H,{dimColor:!0},"Loading configuration...")):O.createElement(W,{key:n,borderStyle:"single",borderColor:"gray",padding:1,flexDirection:"column"},O.createElement(H,{bold:!0},"Taste Learning"),O.createElement(H,{dimColor:!0},"Configure taste learning preferences for this project"),O.createElement(W,{marginTop:1}),O.createElement(W,{justifyContent:"space-between"},O.createElement(H,null,"Taste learning",O.createElement(H,{dimColor:!0}," - Learn from your interactions")),O.createElement(H,{color:r?"green":"gray"},r?"enabled":"disabled")),O.createElement(W,{marginTop:1}),O.createElement(H,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),O.createElement(H,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig");wt(),mn(),wt(),wt();var Xi=__name(e=>{const[t,n]=_(e),[r,o]=_(null);return U(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),o(null)},"handleReset"),r=__name(e=>{"error"!==e.type?n(t=>{if("step_start"===e.type){const n=t.findIndex(t=>t.id===e.step);return n<0?t:t.map((t,r)=>r<n?{...t,active:!1,complete:!0}:r===n?{...t,active:!0,message:e.message||"",...e.label&&{label:e.label},..."complete"===e.step&&{complete:!0},...void 0!==e.learningCount&&void 0!==e.categories&&void 0!==e.storage&&t.summary&&{summary:{learningCount:e.learningCount,categories:e.categories,storage:e.storage}}}:t)}if("progress"===e.type){const n=t.findIndex(e=>e.active);return n<0?t:t.map((t,r)=>r===n?{...t,items:[...t.items,e.message]}:t)}if("insight"===e.type){const n=t.findIndex(e=>"learning"===e.id);return n<0?t:t.map((t,r)=>r===n?{...t,insights:[...t.insights,e.message]}:t)}return t}):o(e.message)},"handleNewEvent");return Qs.on("reset",t),Qs.on("new-event",r),()=>{Qs.off("reset",t),Qs.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new no({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;if(n===ut.ANTHROPIC)try{const e=await Rt.getValidAccessToken();validateOAuthToken({token:e,provider:n}),o=e}catch(e){dlog("Failed to get or validate Anthropic OAuth token:",e instanceof Error?e.message:String(e))}const s={[it.PROJECT_SLUG]:Bs.getCurrentProjectDirName(),[it.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(s[it.OAUTH_TOKEN]=`Bearer ${o}`),{request:t,headers:s}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}wt(),wt(),mn(),wt(),mn(),wt(),wt(),Ct(),Lt(),mn(),hn(),En(),__name(createRequestClient,"createRequestClient"),wt(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),wt(),wt(),Ct(),mn(),Dt(),wt();var ec="claude-haiku-4-5-20251001";function buildObserverPrompt(e,t){return`Scan prompts. ${t} casual observations like a dev friend glancing at your work.\n\nPLAIN TEXT ONLY. No markdown, no formatting.\n\nBe natural and VARIED. Don't repeat the same sentence starters.\n\nGood (notice the variety):\npnpm over npm, nice\ndebugging that auth flow\nreact + typescript stack\ncircular deps came up\ntui flicker stuff\nah the classic memory leak\nsession persistence wip\nfighting with imports again\nhaiku model issues huh\n\nBad (too repetitive - NEVER do this):\nI see you prefer pnpm\nI see debugging auth\nI see react stack\nI see circular deps\noh, TUI issues\noh, memory leak\n\nRules:\n- plain text, lowercase is fine\n- vary your sentence starts - mix it up\n- max 6 words\n- sound human, not robotic\n\nPrompts:\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:`anthropic:${ec}`,max_tokens:200,temperature:.7,stream:!0},threadId:`observer-${Date.now()}`}}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),Qs.addEvent({type:"insight",message:n}))}e=t[t.length-1]}},"emitCompletedLines");return{addText:__name(r=>{t++,dlog(`[ObserverAPI] text chunk ${t}: "${r.substring(0,50)}..."`),e+=r,n()},"addText"),emitRemaining:__name(()=>{e.trim()&&(dlog(`[ObserverAPI] emitting final insight: ${e.trim()}`),Qs.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=Fe.fromReadableStream(e),dlog("[ObserverAPI] created MessageStream")}catch(e){throw dlog(`[ObserverAPI] MessageStream creation failed: ${e instanceof Error?e.message:String(e)}`),e}const n=createInsightEmitter();t.on("text",e=>{n.addText(e)});try{await t.finalMessage(),dlog(`[ObserverAPI] stream complete, ${n.getChunkCount()} chunks received`)}catch(e){throw dlog(`[ObserverAPI] stream failed: ${e instanceof Error?e.message:String(e)}`),e}n.emitRemaining()}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${ct.ALPHA.GENERATE} with model: ${ec}`);const r=buildRequestBody(n);let o;try{o=await e.post({endpoint:ct.ALPHA.GENERATE,body:r,headers:t,stream:!0}),dlog("[ObserverAPI] got response stream")}catch(e){throw dlog(`[ObserverAPI] request failed: ${e instanceof Error?e.message:String(e)}`),e}await processStream(o),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const a=buildObserverPrompt(n,4);await callObserverAPI(e,t,a)}async function observeSessionPrompts(e){if(Qs.observerHasRun)return;Qs.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${r.length} batches`);const o=Math.min(r.length,6);for(let t=0;t<o;t++){if(Qs.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const o=r[t];try{await processBatch(e,n,o,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),Qs.addEvent({type:"progress",message:"Continuing without live observations..."})}}__name(buildObserverPrompt,"buildObserverPrompt"),__name(buildRequestBody,"buildRequestBody"),__name(createInsightEmitter,"createInsightEmitter"),__name(processStream,"processStream"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var tc=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(m.homedir(),".claude","projects");await P.access(r);const o=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await P.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await P.stat(s)).isDirectory())continue;const r=(await P.readdir(s)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const o of r){const r=e.join(s,o),a=await P.stat(r),i=o.replace(".jsonl","");if(n.push({id:i,filePath:r,createdAt:a.birthtime,lastModified:a.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{Qs.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&Qs.addEvent({type:"progress",message:`Scanning Codex: ${e.processedFiles}/${e.totalFiles} files (${e.matchedSessions} matched)`})},e);return dlog(`[Import] found ${n.length} Codex sessions`),n}catch(e){return dlog("[Import] no codex sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await P.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[];try{Qs.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const o=await loadProjectSettings(),s=o.tasteOnboarding?.learnedSessions||{},a=s["claude-code"]?.length||0,i=s.codex?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${i} learned`);const c=await findNewSessions(s),l=c["claude-code"]||[],d=c.codex||[],u=l.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${l.length} new, codex=${d.length} new`),0===u){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=e.length+t.length,r=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);Qs.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:n>0?`From ${r.join(" + ")} sessions`:"No sessions found for this project"});const o=[];return e.length>0&&o.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&o.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:n,learnedSessions:a+i,agentSessions:o,status:"already-learned"}}if(l.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>l.includes(e.id));n.push(...e)}if(d.length>0){const e=(await this.findCodexSessions()).filter(e=>d.includes(e.id));r.push(...e)}const m=n.length+r.length;dlog(`[Import] total sessions: ${m} (claude-code: ${n.length}, codex: ${r.length})`),Qs.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const g=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of g){Qs.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const p=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${p.length} batches`);const h=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});Qs.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${p.length} batch${1===p.length?"":"es"}`});try{const o=getApiBaseUrl(),s=new no({baseUrl:o});let a=!0;for(let e=0;e<p.length;e++){const t=p[e],n=e+1,r=p.length;r>1&&Qs.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),i=new Xs({request:s,sessionId:`taste-import-batch-${e}-${Date.now()}`,projectRoot:process.cwd()}),c=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await i.checkAndProcess({messages:c})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),Qs.markLearningComplete(),await h,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const i=await this.extractLearningSummary(),c=[];if(n.length>0&&c.push(`Claude Code (${n.length})`),r.length>0&&c.push(`Codex (${r.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),Qs.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}return Qs.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${c.join(" + ")}`,learningCount:i.totalLearnings,categories:i.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),Qs.addEvent({type:"error",message:r}),{success:!1,totalPrompts:t.length,preferencesLearned:0,errors:e}}}catch(t){const n=t instanceof Error?t.message:String(t);return e.push(n),{success:!1,totalPrompts:0,preferencesLearned:0,errors:e}}}static async extractLearningSummary(){try{const t=e.join(process.cwd(),".commandcode","taste","taste.md"),n=await P.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),o=r?r.length:0;return{totalLearnings:o,categories:n.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}},nc=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),rc=__name(e=>{const[t,n]=_({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return U(()=>{Qs.reset(),Qs.markImportStarted(),(async()=>{try{const t=await Promise.race([tc.importAndLearn(),nc(12e4)]);if(t.success)return void n(e=>({...e,isImporting:!1,waitingForInput:!0}));if("already-learned"===t.status)return void n(e=>({...e,isImporting:!1,alreadyLearned:!0,learnedSessionCount:t.learnedSessions||0,totalSessionCount:t.totalSessions||0,agentSessions:t.agentSessions||[],waitingForInput:!0}));const r=t.errors.join("\n");n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}catch(t){const r=t instanceof Error?t.message:String(t);n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}})()},[e]),t},"useImportProcess");wt();var oc=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{V((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");wt(),mn();var sc=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=_(null),[o,s]=_(null),a=M(!1);return U(()=>{if(a.current)return;let n=null;return(async()=>{try{a.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{Qs.reset(),e()}}async function skipOnboarding(e){try{await markOnboardingSkipped(),dlog("[Helper] onboarding marked skipped")}catch(e){dlog(`[Helper] skip error: ${e instanceof Error?e.message:String(e)}`)}finally{Qs.reset(),e()}}wt(),mn(),wt(),mn(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var ac=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=M(n),o=j(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=j(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=j(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=j(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current())},[e]),c=j(async()=>{dlog("[Handler] demo complete → done"),e("done"),await markDemoShown(),await completeOnboarding(()=>r.current())},[e]),l=j(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current())},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:a,handleErrorDismiss:i,handleDemoComplete:c,handleSkip:l}},"useOnboardingHandlers");wt(),mn();var ic=__name(({conditions:e,autoLearn:t})=>{const[n,r]=_("checking"),o=M(!1);return U(()=>{if(e&&!o.current){if(o.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),U(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");wt(),wt();var cc=__name(({error:e})=>O.createElement(W,{padding:1},O.createElement(W,{flexDirection:"column",borderColor:"red",padding:1},O.createElement(W,{marginBottom:1},O.createElement(H,null,"Error initializing onboarding: ",e)),O.createElement(W,null,O.createElement(H,null,"Continuing without onboarding...")))),"OnboardingError");wt(),wt();var lc=[{type:"user",text:"I always prefer pnpm",duration:2e3},{type:"learned",text:"Learned: pnpm (95% preference)",details:".commandcode/taste/taste.md",duration:2e3},{type:"user",text:"I prefer commander over meow",duration:2e3},{type:"updated",text:"Updated: commander boosted (60% → 95%), meow adjusted (90% → 35%)",details:".commandcode/taste/cli/taste.md",duration:2e3},{type:"user",text:"I prefer TypeScript for Node CLIs",duration:2e3},{type:"learned",text:"Learned: TypeScript for CLIs (90% preference)",details:".commandcode/taste/cli/taste.md",duration:2e3}],dc=__name(({onComplete:e})=>{const[t,n]=_(0),[r,o]=_(!1),s=t>=lc.length;U(()=>{if(t>=lc.length)return;if(r)return;const e=lc[t],o=setTimeout(()=>{n(e=>Math.min(e+1,lc.length))},e.duration);return()=>clearTimeout(o)},[t,r]),V((t,r)=>{r.escape?e():s?(r.return||" "===t)&&e():" "===t?o(e=>!e):r.return&&n(e=>Math.min(e+1,lc.length))});const a=lc.slice(0,t);return O.createElement(W,{flexDirection:"column"},O.createElement(W,null,O.createElement(H,{color:"cyan"},"Meet Your Coding Taste")),O.createElement(W,null,O.createElement(H,null,"Command Code learns your coding style as you work.")),O.createElement(W,null,O.createElement(H,null,"Here's how your preferences evolve in real-time:")),O.createElement(W,{flexDirection:"column",marginY:1},0===a.length&&!s&&O.createElement(H,{dimColor:!0},"Starting demo..."),a.map((e,t)=>"user"===e.type?O.createElement(W,{key:t},O.createElement(H,{color:"white"},`${he.pointer} ${e.text}`)):O.createElement(W,{key:t,marginBottom:1,marginTop:0,marginLeft:1},O.createElement(W,null,O.createElement(H,null,"⎿"),O.createElement(W,{flexDirection:"column",marginLeft:2,marginTop:0},O.createElement(H,{color:"green"},e.text),e.details&&O.createElement(H,{dimColor:!0},"Saved(",e.details,")")))))),s&&O.createElement(W,{flexDirection:"column",marginY:1,width:80},O.createElement(W,null,O.createElement(H,{color:"green",bold:!0},"Demo Complete!"," ")),O.createElement(H,null,"Command Code will now use these preferences to generate better suggestions tailored to your coding style. The more you code, the smarter it gets."),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Press Enter to get started →"))),!s&&O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"," ",r?"(paused)":"")))},"TasteDemoComponent");wt(),Ct();var uc=__name(()=>`(run /${mt.LEARN_TASTE} anytime)`,"getSkipHint"),mc=__name(()=>O.createElement(H,null,"Skip for now"," ",O.createElement(H,{dimColor:!0},uc())),"SkipOptionText"),gc=__name(({sessionCount:e,agentSessions:t,onImport:n,onDemo:r,onSkip:o,demoShown:s=!1})=>{const[a,i]=_(1),c=s?2:3,l=s?2:3;return V((e,t)=>{if(t.escape)o();else if(t.upArrow)i(e=>1===e?c:e-1);else if(t.downArrow)i(e=>e===c?1:e+1);else if("1"!==e)if("2"!==e)if("3"!==e||s){if(t.return){if(1===a)return void n();if(2===a)return void(s?o():r());o()}}else o();else s?o():r();else n()}),O.createElement(W,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},O.createElement(H,{color:"cyan",bold:!0},"Build Your Coding Taste"),O.createElement(W,{marginTop:1,flexDirection:"column"},O.createElement(H,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),O.createElement(W,{marginTop:1},O.createElement(H,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),O.createElement(W,{marginTop:1,flexDirection:"column"},O.createElement(W,null,O.createElement(H,{color:1===a?"cyan":"gray"},1===a?he.pointer:" "," 1. Yes, learn from my sessions (recommended)")),!s&&O.createElement(W,null,O.createElement(H,{color:2===a?"cyan":"gray"},2===a?he.pointer:" "," ","2. No, show me a demo instead")),O.createElement(W,null,O.createElement(H,{color:a===l?"cyan":"gray"},a===l?he.pointer:" "," ",l,". ",O.createElement(mc,null)))),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice"),pc=__name(({onDemo:e,onSkip:t})=>{const[n,r]=_(1);return V((o,s)=>{s.escape?t():s.upArrow||s.downArrow?r(e=>1===e?2:1):"1"!==o?"2"!==o?s.return&&(1===n?e():t()):t():e()}),O.createElement(W,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",padding:1},O.createElement(H,{color:"cyan",bold:!0},"No Previous Sessions Found"),O.createElement(W,{marginTop:1,flexDirection:"column"},O.createElement(H,null,"No previous sessions found to analyze."),O.createElement(W,{marginTop:1},O.createElement(H,null,"Would you like to see how taste learning works?"))),O.createElement(W,{marginTop:1,flexDirection:"column"},O.createElement(W,null,O.createElement(H,{color:1===n?"cyan":"gray"},1===n?he.pointer:" "," 1. Yes, show me a demo")),O.createElement(W,null,O.createElement(H,{color:2===n?"cyan":"gray"},2===n?he.pointer:" "," 2."," ",O.createElement(mc,null)))),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"NoSessionsChoice");wt(),wt();var hc=__name(({error:e})=>O.createElement(W,{flexDirection:"column",borderStyle:"single",borderColor:"red",paddingX:2,paddingY:1,marginBottom:2},O.createElement(H,{color:"red",bold:!0},"Oops, something went wrong:"),O.createElement(W,{marginTop:1},O.createElement(H,null,e))),"ErrorSection");wt(),wt(),wt(),wt(),wt();var fc=[he.bullet,he.squareSmallFilled,he.lozenge,he.star,he.triangleRight,he.triangleUp,he.circleFilled,he.pointer],yc=__name(()=>O.createElement(H,{backgroundColor:"green",color:"black"}," TASTE "),"TasteBadge"),Ec=["percolating","excavating","deciphering","triangulating","osmosing","metabolizing","grokking","spelunking","interpolating","marinating","crystallizing","synthesizing","calibrating","fermenting","coalescing","transmuting","simmering","distilling","ruminating","perusing","assimilating","untangling","decoding","absorbing","harmonizing","digesting","contemplating","extrapolating","materializing","finalizing"],wc=__name(()=>{const[e,t]=_(()=>Math.floor(Math.random()*Ec.length));U(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*Ec.length))},2e3);return()=>clearInterval(e)},[]);const n=Ec[e];return O.createElement(H,{color:"yellow"},n,"...")},"PulsingText"),bc=__name(e=>String(e).padStart(3," "),"padNum"),Sc=__name(e=>fc[e%fc.length],"getSymbol"),kc=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${bc(t)} ↓${bc(n)} (↑↓ scroll)`,"buildStatusLine"),Cc=__name(({insights:e})=>{const[t,n]=_(0),[r,o]=_(!0),s=e.length,a=s>10,i=Math.max(0,s-10);if(U(()=>{r&&a&&n(i)},[s,r,a,i]),V((e,t)=>{if(a)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(i,e+1);return t===i&&o(!0),t}))}),0===s)return null;const c=e.slice(t,t+10),l=t,d=s-t-10;return O.createElement(W,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&O.createElement(H,{dimColor:!0},kc(s,l,d,r)),c.map((e,n)=>{const r=t+n;return O.createElement(W,{key:r,marginBottom:0},O.createElement(H,{dimColor:!0},Sc(r)," ",e))}))},"ScrollableInsights"),vc=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:c})=>{if(a)return O.createElement(W,{flexDirection:"column",marginBottom:0},O.createElement(yc,null),O.createElement(W,{marginTop:0},O.createElement(H,{dimColor:!0},"⎿"),O.createElement(W,{marginLeft:2},i?O.createElement(H,{color:"green"},"learned your coding taste"):O.createElement(wc,null))));const l=__name(()=>{const[e,t]=_(!0);return U(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),O.createElement(H,{color:"yellow"},e?he.circleFilled:he.circle)},"PulsingDot"),d=__name(()=>r?O.createElement(H,{color:"green"},he.nodejs):n?O.createElement(l,null):O.createElement(H,{dimColor:!0},he.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||c&&c.learningCount>0;return!r||n||u?O.createElement(W,{flexDirection:"column",marginBottom:0},(n||r)&&O.createElement(W,{marginBottom:0},O.createElement(W,{marginRight:1},d()),O.createElement(H,{color:r?"white":n?"yellow":"dim"},e)),r&&t&&(!c||0===c.learningCount)&&O.createElement(W,{marginLeft:3,marginBottom:0},O.createElement(H,{dimColor:!0},t)),o.length>0&&O.createElement(W,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>O.createElement(H,{key:t,dimColor:!0},`${he.bullet} ${e}`))),s.length>0&&O.createElement(Cc,{insights:s}),r&&c&&c.learningCount>0&&O.createElement(W,{flexDirection:"column",marginLeft:1,marginBottom:0},O.createElement(W,{marginBottom:1,flexDirection:"row"},O.createElement(H,null,"⎿"),O.createElement(W,{marginLeft:2},O.createElement(H,{color:"green"},"Learned ",c.learningCount," preference",1===c.learningCount?"":"s",c.categories.length>0?` across ${c.categories.length} ${1===c.categories.length?"category":"categories"}`:""))),O.createElement(W,{flexDirection:"column",marginLeft:1},O.createElement(H,{dimColor:!0},he.pointerSmall," Stored in"," ",c.storage),O.createElement(H,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),Tc=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return O.createElement(W,{flexDirection:"column",marginBottom:1},e.map((e,n)=>O.createElement(W,{key:e.id,marginLeft:0===n?0:3},O.createElement(vc,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),Ac=__name(({steps:e})=>O.createElement(Tc,{steps:e}),"ProgressSection");wt();var Pc=__name(({isImporting:e=!1,waitingForInput:t=!1})=>O.createElement(O.Fragment,null,e&&O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"ESC to cancel")),t&&O.createElement(W,{marginTop:1},O.createElement(H,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");wt();var xc=[{id:"importing",label:"Initializing Taste Profile",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"batching",label:"Organizing your sessions",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"learning",label:"Learning your coding taste",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"complete",label:"Learned your coding taste!",message:"",active:!1,complete:!1,items:[],insights:[],summary:{learningCount:0,categories:[],storage:".commandcode/taste/taste.md"}}],Ic=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=Xi(xc),{isImporting:s,waitingForInput:a,error:i}=rc(t);return oc({onEscape:e,onEnter:__name(()=>{a&&(i&&n?n():e())},"onEnter"),enabled:s||a}),O.createElement(W,{flexDirection:"column",padding:1},o&&O.createElement(hc,{error:o}),!o&&O.createElement(Ac,{steps:r}),O.createElement(Pc,{isImporting:s,waitingForInput:a}))},"ImportProgress"),Rc=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onDemoComplete:a,onDemo:i,onSkip:c})=>"asking"===e?"has_sessions"!==t?.reason?O.createElement(pc,{onDemo:i,onSkip:c}):O.createElement(gc,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onDemo:i,onSkip:c,demoShown:t.demoShown}):"learning"===e?O.createElement(Ic,{onComplete:r,onError:o,onErrorDismiss:s}):"demo"===e?O.createElement(dc,{onComplete:a}):null,"OnboardingStepRenderer"),$c=__name(({onComplete:e,autoLearn:t=!1})=>{U(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=sc({autoLearn:t,onShouldSkip:e}),{step:s,setStep:a}=ic({conditions:n,autoLearn:t}),{handleImportStart:i,handleImportComplete:c,handleImportError:l,handleErrorDismiss:d,handleDemoComplete:u,handleSkip:m}=ac({onStepChange:__name(e=>{a(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?O.createElement(cc,{error:r}):"done"===s?null:O.createElement(Rc,{step:s,conditions:n,onImportStart:i,onImportComplete:c,onImportError:l,onErrorDismiss:d,onDemoComplete:u,onDemo:()=>a("demo"),onSkip:m})},"TasteOnboarding");wt(),Ct();var Dc=__name(({onTrust:e,onExit:t})=>{const{exit:n}=K(),[r,o]=_(1),s=process.cwd().replace(process.env.HOME||"","~");return V((s,a)=>{a.upArrow||a.downArrow?o(1===r?2:1):a.return?1===r?e():(t(),n()):"1"===s?e():("2"===s||a.escape||a.ctrl&&"c"===s)&&(t(),n())}),O.createElement(W,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",padding:1},O.createElement(H,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),O.createElement(W,{marginTop:1},O.createElement(H,{color:"gray"},s)),O.createElement(W,{marginTop:1,flexDirection:"column"},O.createElement(H,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),O.createElement(W,{marginTop:1},O.createElement(H,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),O.createElement(W,{marginTop:1,flexDirection:"column"},O.createElement(W,null,O.createElement(H,{color:1===r?"cyan":"gray"},1===r?he.pointer:" "," 1. Yes, proceed")),O.createElement(W,null,O.createElement(H,{color:2===r?"cyan":"gray"},2===r?he.pointer:" "," 2. No, exit"))))},"TrustPrompt");wt(),fn(),yn();var Nc=__name(({onComplete:e,onCancel:t})=>{const[n,r]=_(!1),[o,s]=_(""),{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u,cancel:m}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return V((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");m()}}),n?O.createElement(gn,{onSuccess:()=>{e(!0,o?`Logged in as ${o} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,o?`Logged in as ${o}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):O.createElement(hr,{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u})},"LoginOverlay");wt(),wt(),En();var Fc=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),Lc=__name(e=>{const t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`},"formatUptime"),Oc=__name(({icon:e,label:t,children:n})=>O.createElement(H,null,O.createElement(H,{color:"cyan"},e," "),O.createElement(H,{dimColor:!0},t.padEnd(12)),n),"Row"),_c=__name(({title:e})=>O.createElement(H,null,O.createElement(H,{color:"gray"},"───"),O.createElement(H,{color:"white"}," ",e," "),O.createElement(H,{color:"gray"},"─".repeat(35))),"Header"),Mc=__name(({title:e,marginTop:t=0,children:n})=>O.createElement(W,{flexDirection:"column",marginTop:t},O.createElement(_c,{title:e}),O.createElement(W,{flexDirection:"column",paddingY:1},n)),"Section"),Uc=__name(({cpuCount:e,totalMem:t})=>O.createElement(Mc,{title:"System Information"},O.createElement(Oc,{icon:pe.bullet,label:"Date"},O.createElement(H,null,formatDate())),O.createElement(Oc,{icon:pe.pointer,label:"Platform"},O.createElement(H,{color:"green"},Fc(m.platform())),O.createElement(H,{dimColor:!0}," ","(",m.platform(),", ",m.arch(),")")),O.createElement(Oc,{icon:pe.triangleUp,label:"Hostname"},O.createElement(H,null,m.hostname())),O.createElement(Oc,{icon:pe.bullet,label:"User"},O.createElement(H,{color:"yellow"},m.userInfo().username)),O.createElement(Oc,{icon:pe.bullet,label:"CPUs"},O.createElement(H,{color:"magenta"},e," cores")),O.createElement(Oc,{icon:pe.bullet,label:"Memory"},O.createElement(H,{color:"cyan"},t," GB")),O.createElement(Oc,{icon:pe.play,label:"Uptime"},O.createElement(H,null,Lc(m.uptime()))),O.createElement(Oc,{icon:pe.arrowRight,label:"Home"},O.createElement(H,{dimColor:!0},m.homedir())),O.createElement(Oc,{icon:pe.pointer,label:"Shell"},O.createElement(H,null,process.env.SHELL||"N/A")),O.createElement(Oc,{icon:pe.bullet,label:"Node"},O.createElement(H,{color:"green"},process.version))),"SystemInfoSection"),jc=__name(({cpus:e})=>O.createElement(Mc,{title:"CPU Details",marginTop:1},e.map((e,t)=>O.createElement(Oc,{key:t,icon:pe.bullet,label:`Core ${t}`},O.createElement(H,null,e.model.trim()),O.createElement(H,{color:"yellow"}," @ ",e.speed," MHz")))),"CPUDetailsSection"),Bc=__name(({networkInterfaces:e})=>O.createElement(Mc,{title:"Network",marginTop:1},Object.entries(e).map(([e,t])=>{const n=t?.filter(e=>"IPv4"===e.family&&!e.internal);return n&&0!==n.length?n.map((t,n)=>O.createElement(Oc,{key:`${e}-${n}`,icon:pe.bullet,label:e},O.createElement(H,{color:"green"},t.address))):null})),"NetworkSection"),Wc=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>O.createElement(W,{flexDirection:"column"},O.createElement(H,null,"System Information"),O.createElement(H,null,"─".repeat(40)),O.createElement(H,null,"Date ",formatDate()),O.createElement(H,null,"Platform ",Fc(m.platform())," (",m.platform(),","," ",m.arch(),")"),O.createElement(H,null,"Hostname ",m.hostname()),O.createElement(H,null,"User ",m.userInfo().username),O.createElement(H,null,"CPUs ",e.length," cores"),O.createElement(H,null,"Memory ",t," GB"),O.createElement(H,null,"Uptime ",Lc(m.uptime())),O.createElement(H,null,"Home ",m.homedir()),O.createElement(H,null,"Shell ",process.env.SHELL||"N/A"),O.createElement(H,null,"Node ",process.version),r&&O.createElement(O.Fragment,null,O.createElement(H,null,"\n","CPU Details"),O.createElement(H,null,"─".repeat(40)),e.map((e,t)=>O.createElement(H,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),O.createElement(H,null,"\n","Network"),O.createElement(H,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>O.createElement(H,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Hc=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>O.createElement(W,{flexDirection:"column"},O.createElement(Uc,{cpuCount:e.length,totalMem:t}),r&&O.createElement(jc,{cpus:e}),r&&O.createElement(Bc,{networkInterfaces:n})),"StyledInfo"),zc=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=K();U(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=m.cpus(),o=m.networkInterfaces(),s=Math.round(m.totalmem()/1024/1024/1024);return t?O.createElement(Wc,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e}):O.createElement(Hc,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e})},"InfoUI"),Gc={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},qc=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),Vc=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(qc("__CFBundleIdentifier","com.todesktop"))return"Cursor";const e=[process.env.VSCODE_GIT_ASKPASS_MAIN,process.env.VSCODE_GIT_ASKPASS_NODE,process.env.GIT_ASKPASS].filter(Boolean);for(const t of e){const e=t.toLowerCase();if(e.includes("cursor"))return"Cursor";if(e.includes("windsurf"))return"Windsurf"}return"vscode"===process.env.TERM_PROGRAM&&"1"===process.env.VSCODE_INJECTION?"VSCode":null},"detectIDE"),Kc=__name(()=>{const e=Vc();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&Gc[t]?Gc[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),Jc=__name(()=>{if("win32"===g.platform()){const e=process.env.COMSPEC;return e?i(e):process.env.SHELL?i(process.env.SHELL):"cmd.exe"}if(process.env.FISH_VERSION)return"fish";if(process.env.ZSH_VERSION)return"zsh";if(process.env.BASH_VERSION)return"bash";try{const e=process.ppid;if(e){const t=v(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=i(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?i(e):"N/A"},"getShellName"),Yc=__name(()=>{const e=Vc();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),Qc=__name(()=>{try{const e=v("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:Fc(g.platform()),terminal:Kc(),shell:Jc(),version:Qc(),ide:Yc()}}function buildGitHubIssueUrl(e){const t=getSystemInfo(),n=new URLSearchParams;if(n.append("template","1.bug_report.yml"),e){const t=e.slice(0,256).trim();t&&n.append("title",t)}return n.append("version",t.version),n.append("os",t.os),n.append("terminal",t.terminal),n.append("shell",t.shell),`https://github.com/CommandCodeAI/command-code/issues/new?${n.toString()}`}function createOSC8Link(e,t,n=!0){return`${n?"":""}]8;;${e}${t||e}]8;;${n?"":""}`}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),wt(),__name(createOSC8Link,"createOSC8Link"),wt(),wt(),mn();var Zc=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;constructor(){this.filePath=e.join(m.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await P.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean).slice(-100);let t=0;this.buffer=e.map(e=>{try{return JSON.parse(e).p}catch{return t++,""}}).filter(Boolean),t>0&&dlog(`[PromptHistory] Skipped ${t} corrupted entries`)}catch(e){e instanceof Error&&"code"in e&&"ENOENT"===e.code||dlog(`[PromptHistory] Failed to load history: ${e instanceof Error?e.message:String(e)}`),this.buffer=[]}this.initialized=!0}}add(e){if(!e||0===e.trim().length)return;const t=e.length>500?e.slice(0,500)+"...":e;this.buffer.push(t),this.buffer.length>500&&(this.buffer=this.buffer.slice(-500)),this.writeQueue.push({p:t,t:Date.now()}),this.scheduleFlush()}getAt(e){if(e<0||e>=this.buffer.length)return;const t=this.buffer.length-1-e;return this.buffer[t]}count(){return this.buffer.length}getAll(){return[...this.buffer]}isInitialized(){return this.initialized}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,await this.flush()},100))}async flush(){if(0===this.writeQueue.length)return;if(this.isFlushing)return void this.scheduleFlush();if(this.writeFailures>=3)return void(this.writeQueue=[]);this.isFlushing=!0;const t=this.writeQueue;this.writeQueue=[];try{const n=e.dirname(this.filePath);await P.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await P.appendFile(this.filePath,r),this.writeFailures=0,await this.rotateIfNeeded()}catch(e){this.writeFailures++;const n=e instanceof Error?e.message:String(e);this.writeFailures<3?(this.writeQueue.unshift(...t),dlog(`[PromptHistory] Write failed, retrying (${this.writeFailures}/3): ${n}`)):dlog(`[PromptHistory] Write disabled after 3 failures: ${n}`)}finally{this.isFlushing=!1}}async rotateIfNeeded(){try{const e=await P.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await P.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await P.writeFile(this.filePath,n.join("\n")+"\n"),dlog(`[PromptHistory] Rotated: kept ${n.length} of ${t.length} entries`)}catch(e){dlog(`[PromptHistory] Rotation failed (non-critical): ${e instanceof Error?e.message:String(e)}`)}}async cleanup(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);const e=Date.now();for(;this.isFlushing;){if(Date.now()-e>=5e3){dlog("[PromptHistory] Cleanup timed out waiting for flush after 5000ms");break}await new Promise(e=>setTimeout(e,10))}await this.flush()}};function createHistoryManager(){return new Zc}__name(createHistoryManager,"createHistoryManager"),wt();var Xc=__name((e,t)=>{if(!e.startsWith("option_"))return null;const n=e.slice(7),r=parseInt(n,10);return Number.isNaN(r)||r<0||r>t?null:r},"parseOptionIndex"),el=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r})=>{const o=[];e.forEach((s,a)=>{const i=a===t&&!r,c=n.has(a);let l,d;i?(l="●",d="cyan"):c?(l="✓",d="green"):(l="○",d="gray"),o.push(O.createElement(H,{key:a},O.createElement(H,{color:d},l),O.createElement(H,{color:i?"cyan":void 0}," ",s.header),a<e.length-1?O.createElement(H,{dimColor:!0}," | "):null))});const s=r;return o.push(O.createElement(H,{key:"review"},O.createElement(H,{dimColor:!0}," | "),O.createElement(H,{color:s?"cyan":"gray"},s?"●":"○"),O.createElement(H,{color:s?"cyan":void 0,bold:s}," ","Review"))),O.createElement(W,null,o)},"TabIndicator"),tl=__name(({questions:e,onResponse:t})=>{const[n,r]=_(0),[o,s]=_(new Map),a=M(new Map),[i,c]=_(""),[l,d]=_(new Set),[u,m]=_(null),[g,p]=_(!1),[h,f]=_(!1),[y,E]=_(!1),[w,b]=_(null),[S,k]=_(!1),C=e[n],v=C?.multiSelect??!1,T=o.get(n),A=C?[...C.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],P=A.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),x=new Map(P.map((e,t)=>[e.label,A[t]])),I=__name(e=>{"submit"===e.value?L():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),R=__name(()=>{if(!T||0===T.length)return 0;const e=T[0],t=C.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),$=__name(e=>{if(!g)if(v){const t=Xc(e.value,C.options.length-1);if(null===t)return;const n=C.options[t]?.label||"";d(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=Xc(e.value,C.options.length-1);if(null===t)return;p(!0);const n=C.options[t]?.label||"";F([n])}},"handleSelect"),D=__name(()=>{if(g)return;p(!0);const e=Array.from(l);F(e)},"handleMultiSelectDone"),N=__name(()=>{if(!g&&i.trim())if(v){const e=new Set(C.options.map(e=>e.label));d(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(i.trim()),n})}else p(!0),F([i.trim()])},"handleOtherSubmit"),F=__name(t=>{a.current.set(n,t);const o=new Map(a.current);s(o);const i=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){d(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),n?.multiSelect||1!==r?.length)c("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);c(t&&e?e:"")}},"restoreStateForQuestion");if(n<e.length-1){const e=n+1;i(e),r(e),p(!1),E(!1),b(null),k(!1)}else if(e.every((e,t)=>o.has(t)))d(new Set),c(""),f(!0),p(!1);else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(i(t),r(t)),p(!1),E(!1),b(null),k(!1)}},"finishQuestion"),L=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),U=__name(t=>{f(!1),r(t),k(!1),E(!1),b(null);const n=e[t],o=a.current.get(t);if(n?.multiSelect&&o){d(new Set(o));const e=o.find(e=>!n.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),n?.multiSelect||1!==o?.length)c("");else{const e=o[0],t=!n.options.some(t=>t.label===e);c(t&&e?e:"")}},"editQuestion"),j=__name(t=>{if(t<0||t>=e.length)return;v&&(l.size>0?a.current.set(n,Array.from(l)):a.current.delete(n),s(new Map(a.current))),p(!1),E(!1),b(null),k(!1);const o=e[t],i=a.current.get(t);if(o?.multiSelect&&i){d(new Set(i));const e=i.find(e=>!o.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),o?.multiSelect||1!==i?.length)c("");else{const e=i[0],t=!o.options.some(t=>t.label===e);c(t&&e?e:"")}r(t)},"navigateToQuestion"),B=__name(()=>{if(!u||!v)return;if("done"===u.value)return;const e=Xc(u.value,C.options.length-1);if(null===e)return;const t=C.options[e]?.label||"";d(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return V((t,r)=>{if(" "===t&&v&&!y&&B(),"d"!==t||!v||y||h||D(),!h&&!g){if(r.downArrow&&!y&&!S&&u&&P.length>0&&u.value===P[P.length-1]?.value&&E(!0),r.upArrow&&!y&&!S&&u&&P.length>0&&u.value===P[0]?.value&&(v?k(!0):(E(!0),b(P.length-1))),r.upArrow&&y){E(!1),b(P.length-1);const e=P[P.length-1];e&&m(e)}if(r.downArrow&&y)if(E(!1),v)k(!0);else{b(0);const e=P[0];e&&m(e)}if(r.upArrow&&S&&(k(!1),E(!0)),r.downArrow&&S){k(!1),b(0);const e=P[0];e&&m(e)}r.return&&S&&v&&D()}if(g||y||S||(h?r.leftArrow&&U(e.length-1):r.leftArrow&&n>0?j(n-1):r.rightArrow&&(n<e.length-1?j(n+1):(v&&(l.size>0?a.current.set(n,Array.from(l)):a.current.delete(n),s(new Map(a.current))),f(!0)))),r.escape&&!g)if(h)f(!1);else if(y){E(!1);const e=w??P.length-1;b(e);const t=P[e];t&&m(t)}else if(S){k(!1);const e=P[P.length-1];e&&m(e)}}),C||h?h?O.createElement(W,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},O.createElement(W,{marginBottom:1},O.createElement(el,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>O.createElement(W,{key:t,marginBottom:1,flexDirection:"column"},O.createElement(H,{dimColor:!0},t+1,". ",e.question),O.createElement(H,{color:"green"}," ",o.get(t)?.join(", ")||"No answer"))),O.createElement(Ue,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:I,initialIndex:0,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:"cyan"},e?he.pointer:" "),itemComponent:({label:e,isSelected:t})=>O.createElement(H,{color:t?"cyan":"white"},e)}),O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},he.arrowLeft," to go back and edit"))):O.createElement(W,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},O.createElement(W,{marginBottom:1},O.createElement(el,{questions:e,currentIndex:n,answeredQuestions:new Set(o.keys()),isReviewPage:!1})),O.createElement(W,{marginBottom:1},O.createElement(H,{bold:!0},C.question)),y||S?O.createElement(W,{flexDirection:"column"},P.map((e,t)=>{const n=x.get(e.label),r=v&&n&&l.has(n.label),o=!v&&n&&T?.includes(n.label),s=r||o;return O.createElement(W,{key:t,flexDirection:"column"},O.createElement(W,null,O.createElement(H,null," "),O.createElement(H,{color:s?"green":"white"}," ",t+1,"."," "),v&&(s?O.createElement(H,{color:"green"},"[",he.tick,"]"," "):O.createElement(H,{dimColor:!0},"[ ] ")),O.createElement(H,{color:s?"green":"white"},n?.label||""),!v&&s&&O.createElement(H,{color:"green"}," ",he.tick)),n?.description&&O.createElement(W,null,O.createElement(H,null," "),O.createElement(H,{dimColor:!0},v?" ":" ",n.description)))})):O.createElement(Ue,{key:`${n}-${w??"default"}`,items:P,initialIndex:w??R(),onSelect:$,onHighlight:m,indicatorComponent:({isSelected:e})=>O.createElement(H,{color:"cyan"},e?he.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=x.get(e),r=v&&n&&l.has(n.label),o=!v&&n&&T?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",c=a?.[2]||e;return O.createElement(W,{flexDirection:"column"},O.createElement(W,null,O.createElement(H,{color:t?"cyan":s?"green":"white"}," ",i,"."," "),v&&(s?O.createElement(H,{color:"green"},"[",he.tick,"]"," "):O.createElement(H,{dimColor:!0},"[ ] ")),O.createElement(H,{color:t?"cyan":s?"green":"white"},c),!v&&s&&O.createElement(H,{color:"green"}," ",he.tick)),n?.description&&O.createElement(H,{dimColor:!0},v?" ":" ",n.description))}}),O.createElement(W,null,O.createElement(H,{color:"cyan"},y?he.pointer:" "),O.createElement(H,{color:y?"cyan":void 0}," ",P.length+1,"."," "),v&&(l.has(i.trim())?O.createElement(H,{color:"green"},"[",he.tick,"] "):O.createElement(H,{dimColor:!0},"[ ] ")),O.createElement(Ve,{value:i,onChange:e=>{const t=i.trim();c(e),v&&d(n=>{const r=new Set(n);return t&&r.has(t)&&r.delete(t),e.trim()&&r.add(e.trim()),r})},onSubmit:N,placeholder:"Type something...",focus:y})),v&&O.createElement(W,null,O.createElement(H,{color:"cyan"},S?he.pointer:" "),O.createElement(H,{color:S?"cyan":void 0,bold:S}," ",n===e.length-1?"Submit":"Next")),e.length>1&&O.createElement(W,{marginTop:1},O.createElement(H,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function LiveAgentStatusInner({entry:e}){const t=Zo(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,a=e.metadata?.elapsedSeconds||0,i=e.metadata?.recentTools||[],[c,l]=_(".");return U(()=>{const e=setInterval(()=>{l(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),O.createElement(W,{flexDirection:"column",marginBottom:1,width:"90%"},O.createElement(W,null,O.createElement(H,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${t} `),o&&O.createElement(H,null," ","(",o,")")),O.createElement(W,{columnGap:1,marginLeft:1},O.createElement(H,null,"⎿"," "),O.createElement(H,{color:"gray"},"Running (",formatTime2(a)," | ",formatTokens(s),")",c)),i.length>0&&O.createElement(W,{flexDirection:"column",marginLeft:1},i.map((e,t)=>{const n=Zo(e.name);return O.createElement(W,{key:t,columnGap:1},O.createElement(H,{color:"gray"},"⎿"),O.createElement(H,{color:"gray"}," ",n),e.input&&O.createElement(H,{color:"gray"},"(",e.input,")"))})))}function LiveAgentStatus({entry:e}){return"tool"!==e.role?null:O.createElement(LiveAgentStatusInner,{entry:e})}wt(),En(),__name(LiveAgentStatusInner,"LiveAgentStatusInner"),__name(LiveAgentStatus,"LiveAgentStatus");var{setText:nl}=Ie,{runIDESetup:rl}=await Promise.resolve().then(()=>(ar(),sr));function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}__name(createKillShellPermissionRequest,"createKillShellPermissionRequest");var ol=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:o,updateFailedInfo:s,initialPrompt:a,skipOnboarding:i=!1})=>{const{exit:c}=K(),[l,d]=_(""),[u,m]=_("Ready..."),g=M(!1),[p,h]=_(null),[f,y]=_(o);U(()=>{if(f){const e=setTimeout(()=>{y(null)},3e4);return()=>clearTimeout(e)}},[f]);const{stdout:E}=q(),[w,b]=_(!1),[S,k]=_(!1),[C,v]=_(!1),[T,A]=_(!1),[P,x]=_(!1),[I,R]=_(!1),[$,D]=_(!1),[N,F]=_(!1),[L,B]=_(null),[z,G]=_(null),[J,Y]=_(getConfiguredModel()),[Q,Z]=_(!1),[ee,te]=_(!1),[ne,re]=_(!1),oe=M(null),se=M(null),[ae,ie]=_(0),[ce,le]=_(!1),{executeBash:de,executionState:ue}=la(),[me,ge]=_(""),[pe,he]=_([]),[fe,ye]=_([]),[Ee,we]=_(!1),[be,Se]=_([]),[ke,Ce]=_(crypto.randomUUID()),[ve,Te]=_(!1),[Ae,Pe]=_(!1),xe=M(null),[Ie,Re]=_(!1),[$e,De]=_(!1),[Ne,Fe]=_(!0),[Le,Oe]=_(!1),[_e,Me]=_(!1),[Ue,je]=_(null),[Be,We]=_(!1),He=M(!1),[ze,Ge]=_(!1),[qe,Ve]=_(0),[Ke,Je]=_(null),[Ye,Qe]=_(null),[Ze,Xe]=_(null),et=M(!1),tt=M(!1),nt=M(Ze);U(()=>{nt.current=Ze},[Ze]);const[rt,ot]=_(!1),[st,at]=_(""),[it,lt]=_(!1),[dt,ut]=_(!!r),[pt,ht]=_(""),ft=M(null),yt=M(null),Et=__name(()=>{ft.current&&clearTimeout(ft.current),yt.current&&clearTimeout(yt.current),oe.current&&clearTimeout(oe.current),se.current&&clearTimeout(se.current)},"cleanupTimers"),[wt,bt]=_(!1),[kt,Ct]=_(!1),vt=M(null),Tt=M(0),[At,Pt]=_(null),xt=j(()=>{vt.current=null,Pt(null),yt.current&&(clearTimeout(yt.current),yt.current=null)},[]);U(()=>{if(ze){Et();try{c()}catch{process.exit(0)}}},[ze,c]);const It=j(()=>{Me(!0),Oe(!1),We(!1),ma(),ie(e=>e+1),e&&Te(!0)},[e,t]),$t=__name(async()=>{try{const e=await isTasteLearningEnabled();lt(e),e&&await _a.initializeProject()}catch(e){}},"loadTasteStatus"),Dt=__name(async()=>{const e=await getConfiguredProvider();G(e);const t=await isOAuthEnforced();Z(t)},"loadCurrentProvider"),Nt=M([]),Ft=M(null),Lt=M(null),[Ot,_t]=_(null),[Mt,Ut]=_(null),{requestShellPermission:jt,service:Bt,respondToPrompt:Wt,clearSessionPermissions:Ht,setEnabled:zt}=ua({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{_t({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),Ft.current&&m("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{_t({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),Ft.current&&m("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?m("Permission granted"):m("Permission denied")},"onPermissionResponse")}),Gt=__name(e=>{ft.current&&clearTimeout(ft.current),ht(e),ft.current=setTimeout(()=>{ht(""),ft.current=null},5e3)},"showHintMessage");U(()=>()=>Et(),[]),U(()=>{Bt&&applyAutoAcceptMode({enabled:dt,service:Bt})},[dt,Bt]),U(()=>{(async()=>{if(await Bs.isProjectInitialized())if(De(!0),Fe(!1),$t(),Dt(),t){const e=await Bs.listSessions();if(e.length>0){const t=e[0];fn(t.id)}}else e&&Te(!0);else if(n)if(await Bs.initializeProject(),De(!0),Fe(!1),$t(),Dt(),t){const e=await Bs.listSessions();if(e.length>0){const t=e[0];fn(t.id)}}else e&&Te(!0);else isDirectoryEmpty()?(await Bs.initializeProject(),De(!0),Fe(!1),$t(),Dt()):(Re(!0),Fe(!1))})()},[e,t,n,c]),U(()=>{i||triggerTasteOnboarding({projectTrusted:$e,onboardingComplete:_e,isOnboardingMode:Le,tasteOnboardingCheckedRef:He,setIsOnboardingMode:Oe})},[$e,_e,Le,i]),U(()=>{if(Le&&!Ue){const e=Wo();je(e.id),he(t=>[...t,e])}else!Le&&Ue&&(he(e=>e.filter(e=>e.id!==Ue)),je(null))},[Le,Ue]),U(()=>{Nt.current=be},[be]),U(()=>{(async()=>{if(z&&"anthropic"===z&&Q)try{await Rt.getValidAccessToken()||m("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){m("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[z,Q]),U(()=>{if(!Ee)return void(g.current=!1);if(null!==p)return;const e=setInterval(()=>{g.current||m(Qo())},7e3);return()=>clearInterval(e)},[Ee,p]);const qt=j(()=>{const e=!Ee&&!Ot&&!Mt,t=Ft.current?.hasCheckpoints()??!1;e&&t&&bt(!0)},[Ee,Ot]),Vt=j(()=>{if(!Ft.current)return;Ft.current.interrupt(!0);const e=fe.length>0;if(we(!1),h(null),ye([]),m("Interrupted by user"),!e){const e=Bo("Interrupted by user");he(t=>[...t,e])}if(Nt.current.length>0){const e=Nt.current.join("\n");d(t=>t?e+"\n"+t:e),Se([]),Nt.current=[]}},[fe]),Kt=__name(()=>{ut(e=>{const t=!e;return t&&Ot&&(Wt({label:"Yes",value:"yes",description:"Allow this action",scope:void 0}),Ot.resolve(!0),_t(null)),t})},"handleToggleAutoAccept");async function getBillingLink(){if(Ye)return Ye;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return Qe(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return Qe(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}V((e,t)=>{if(t.shift&&t.tab||""===e)Kt();else if(C||T||P||I||$||L||N||wt||kt)At&&xt();else{if(""===e||t.ctrl&&"c"===e){if(Ee&&Ft.current)return void Vt();const e=Date.now(),t=e-Tt.current;return Tt.current=e,void("ctrl-c"===vt.current&&t<2e3?(yt.current&&(clearTimeout(yt.current),yt.current=null),Ge(!0)):(d(""),vt.current="ctrl-c",Pt("ctrl-c"),yt.current&&clearTimeout(yt.current),yt.current=setTimeout(()=>{vt.current=null,Pt(null),yt.current=null},2e3)))}if(t.ctrl&&"t"===e)return ma(),F(e=>!e),void ie(e=>e+1);if(getIsExpandToolShortcut(t,e))return ma(),le(e=>!e),void ie(e=>e+1);if(t.meta&&"p"===e||isAltP(e))R(!0);else{if(t.escape){if(Mt)return Mt.reject(new Error("Question cancelled by user")),Ut(null),void m("Question cancelled");Ot?(Wt({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),Ot.resolve(!1),_t(null),m("Permission denied")):Ee&&Ft.current&&Vt()}t.meta||t.ctrl}}}),U(()=>{const e=__name(()=>{ma(),ie(e=>e+1)},"handleResize");if(E)return E.on("resize",e),()=>{E.off("resize",e)}},[E]),U(()=>{Ft.current||!$e||ve||Ae||(Ft.current=new oa({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?ye(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(ye(t=>t.filter(t=>t.id!==e.id)),he(t=>[...t,e])):he(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Nt.current];return Nt.current=[],Se([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ve(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Je(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{h(e)},"onRetryUpdate"),onProviderChange:__name(e=>{G(e)},"onProviderChange"),onStatusUpdate:__name(e=>{g.current=!0,m(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&Bt){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 Bt.requestShellPermission(n).then(e=>e.allowed)}if("kill_shell"===e&&Bt){const e=createKillShellPermissionRequest(t);return Bt.requestShellPermission(e).then(e=>e.allowed)}if(Bt){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 Bt.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Ut({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const e=nt.current;return e?{sessionId:ke,secret:e.secret}:null},"getShareInfo")},ke),(async()=>{await sn()})())},[ke,ve,Ae,$e]),U(()=>{if(!$e)return;const e=createHistoryManager();return xe.current=e,e.init(),()=>{e.cleanup()}},[$e]),U(()=>{a&&$e&&!Ne&&Ft.current&&!ve&&!tt.current&&(tt.current=!0,Jt({role:"user",input:a}))},[a,$e,Ne,ve]),__name(getBillingLink,"getBillingLink");const Jt=__name(async({role:e,input:t,images:n,ideContext:r})=>{if(t.length)if(f&&y(null),Ve(0),"bash"===e){if(et.current)return;et.current=!0;const e=Uo(t);he([...pe,e]),d(""),await de(t,e=>{he(e)},()=>{ma(),ie(e=>e+1)}),et.current=!1}else{if(Ee)return Se(e=>[...e,t]),void d("");if(et.current)return;et.current=!0,we(!0),m(Qo()),d("");try{Ft.current&&await Ft.current.sendMessage(t,n,r)}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){m("Insufficient credits");const e=await getBillingLink(),t=Bo(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);he(e=>[...e,t])}else if(e.message.startsWith("Error:")){m("Error");const t=Bo(e.message);he(e=>[...e,t])}else{m("Error");const t=e.message||"An unexpected error occurred",n=Bo(t);he(e=>[...e,n])}}finally{we(!1),"Interrupted by user"!==u&&"Permission denied"!==u&&"Insufficient credits"!==u&&m("Ready..."),et.current=!1}}},"handleSubmit"),Yt=__name(()=>{he(e=>[...e,jo("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),Qt=__name(()=>{const e=Lo(`/${mt.TERMINAL_SETUP}`),t=setupVSCodeTerminal(),n=Ho(t.message,!t.success,t.details);he(t=>[...t,e,n])},"handleTerminalSetupCommand"),Zt=__name(async()=>{const e=await rl(),t=zo(e.status,e.ide,e.details);he(e=>[...e,t])},"handleIDESetupCommand"),Xt=__name(async()=>{if(he([]),ye([]),ma(),ut(!!r),Xe(null),ot(!1),at(""),Ft.current){const e=Ft.current.getSessionManager();e&&await e.deleteShareInfo(),Ft.current=null;const t=crypto.randomUUID();Ce(t),Ht(),Ft.current=new oa({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?ye(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(ye(t=>t.filter(t=>t.id!==e.id)),he(t=>[...t,e])):he(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Nt.current];return Nt.current=[],Se([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ve(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Je(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{h(e)},"onRetryUpdate"),onProviderChange:__name(e=>{G(e)},"onProviderChange"),onStatusUpdate:__name(e=>{g.current=!0,m(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&Bt){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 Bt.requestShellPermission(n).then(e=>e.allowed)}if("kill_shell"===e&&Bt){const e=createKillShellPermissionRequest(t);return Bt.requestShellPermission(e).then(e=>e.allowed)}if(Bt){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 Bt.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Ut({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const e=nt.current;return e?{sessionId:t,secret:e.secret}:null},"getShareInfo")},t)}ie(e=>e+1),Je(null),Ve(0)},"handleClearCommand"),en=__name(()=>{Ft.current?Ft.current.hasCheckpoints()?bt(!0):he(e=>[...e,Oo("No checkpoints available. Start sending messages to create checkpoints.")]):he(e=>[...e,Oo("No active conversation to rewind.")])},"handleRewindCommand"),tn=__name(async e=>{const{messageId:t,mode:n}=e;if(bt(!1),Ft.current)try{const e=Ft.current.listCheckpoints().find(e=>e.messageId===t);m("Restoring checkpoint...");const r=await Ft.current.restoreToCheckpoint({messageId:t,mode:n});if(r.success){const t=Ft.current.getSessionManager(),n=Ft.current.getMessages(),o=t.reconstructFeedFromMessages(n);he(o),ma(),ie(e=>e+1),e&&e.userPrompt&&d(e.userPrompt);const s=[];r.filesRestored>0&&s.push(`${r.filesRestored} file${r.filesRestored>1?"s":""} restored`),r.filesDeleted>0&&s.push(`${r.filesDeleted} file${r.filesDeleted>1?"s":""} deleted`),r.messagesRemoved>0&&s.push(`${r.messagesRemoved} message${r.messagesRemoved>1?"s":""} removed`);const a=s.length>0?`Restored to checkpoint: ${s.join(", ")}.`:"Restored to checkpoint.";he(e=>[...e,Oo(a)]),m("Ready...")}else he(e=>[...e,Bo(`Failed to restore: ${r.error}`)]),m("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;he(e=>[...e,Bo(t)]),m("Ready...")}},"handleRewindSelect"),nn=__name(()=>{bt(!1)},"handleRewindCancel"),rn=__name(async()=>{if(Ft.current)if(Ft.current.isRequestInProgress())he(e=>[...e,Oo("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{we(!0),m("Compacting conversation...");const e=await Ft.current.manualCompact();ma(),ie(e=>e+1);let t="Compacted conversation.";e.didCompact||(t="Conversation is already compact."),e.didCompact&&e.tokensSaved>0&&(t=`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`),he(e=>[...e,Oo(t)]),we(!1),m("Ready..."),Je({current:Ft.current.getContextTokensUsed()||0,limit:Us})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;he(e=>[...e,Bo(t)]),we(!1),m("Ready...")}else he(e=>[...e,Oo("No active conversation to compact.")])},"handleCompactCommand"),on=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await fn(t)}const t=parseCommandInput({input:e});if(!t)return;const{commandName:n,rawArguments:r,positionalArgs:o}=t;switch(n){case"/exit":return void Ge(!0);case"/clear":return void await Xt();case"/help":return void Yt();case"/share":return void an();case"/unshare":return void pn();case"/taste":return void v(!0);case"/learn-taste":return void await hn();case"/skills":return void A(!0);case"/provider":return void(isInternalTeamFlagEnforced()?x(!0):m("Provider selection not available"));case"/model":return void R(!0);case"/memory":return void D(!0);case"/init":return void cn();case"/agents":return void k(!0);case"/compact":return void await rn();case"/rewind":return void en();case"/login":return void await ln();case"/logout":return void await mn();case"/feedback":return void await gn();case"/terminal-setup":return void Qt();case"/ide":return void await Zt()}const s=getCustomCommandContent(n);if(s){const e=processCommandTemplate({template:s,rawArguments:r,positionalArgs:o});await Jt({input:e.content,role:"user"})}},"handleCommand"),sn=__name(async()=>{const e=Ft.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&Xe({url:t.url,secret:t.secret})}},"loadShareInfo"),an=__name(async()=>{if(ke){if(Ze)return await nl(Ze.url),m(""),ot(!0),void setTimeout(()=>{ot(!1)},3e3);try{m("Creating share link...");const e=Ft.current?.getMessages()||[],t=Gr.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new no({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:ct.ALPHA.SHARE.CREATE,body:{sessionId:ke,messages:t}}),o={url:r.url,secret:r.secret};Xe(o);const s=Ft.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await nl(r.url),m(""),ot(!0),setTimeout(()=>{ot(!1)},5e3)}catch(e){m(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else m("No active session to share")},"handleShareCommand"),cn=__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.`;he(e=>[...e,Oo(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;he(e=>[...e,Oo(t)])}},"handleInitCommand"),ln=__name(async()=>{const e=St();if(await getAuthKey(e)){let e="";try{const t=await loadCredentials();e=t?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const t=e&&"API Key"!==e&&"Manual API Key"!==e?` as ${e}`:"";return void he(e=>[...e,Oo(`Already logged in${t}`)])}Ct(!0)},"handleLoginCommand"),dn=j((e,t)=>{Ct(!1),e?(he(e=>[...e,Oo(t)]),Ft.current&&Ft.current.refreshRequest()):he(e=>[...e,Bo(t)]),m("Ready...")},[]),un=j(()=>{Ct(!1),he(e=>[...e,Oo("Authentication cancelled.")]),m("Ready...")},[]),mn=__name(async()=>{const e=await performLogout();e.success?(Ft.current&&Ft.current.refreshRequest(),e.wasAuthenticated?e.warnings.length>0?he(t=>[...t,Oo(`Successfully logged out from Command Code. Warnings: ${e.warnings.join(", ")}`)]):he(e=>[...e,Oo("Successfully logged out from Command Code.")]):he(e=>[...e,Oo("Not currently authenticated.")])):he(t=>[...t,Bo(`Logout failed: ${e.error}`)])},"handleLogoutCommand"),gn=__name(async e=>{const t=buildGitHubIssueUrl(e);try{await X(t,{wait:!1,background:!0}),he(e=>[...e,Oo(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`)])}catch(e){he(e=>[...e,Bo("Failed to open browser"),jo(createOSC8Link(t,"Open GitHub issue manually"))])}},"handleFeedbackCommand"),pn=__name(async()=>{if(ke){if(!Ze)return at("NOT SHARED: Session is not currently shared"),void setTimeout(()=>at(""),5e3);try{m("Removing share link...");const e=new no({baseUrl:getApiBaseUrl()});await e.delete({endpoint:ct.ALPHA.SHARE.DELETE,body:{sessionId:ke,secret:Ze.secret}});const t=Ft.current?.getSessionManager();t&&await t.deleteShareInfo(),at("UNSHARED: Sharing has stopped"),m(""),Xe(null),setTimeout(()=>{at("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;m(t),setTimeout(()=>m(""),5e3)}}else m("No active session to unshare")},"handleUnshareCommand"),hn=__name(async()=>{We(!0),Oe(!0);const e=Wo();je(e.id),he(t=>[...t,e])},"handleLearnCommand"),fn=__name(async e=>{const t=crypto.randomUUID();Lt.current=t;try{he([]),ye([]),Ft.current=null,ut(!1),Ce(e),Te(!1),Pe(!0),Ft.current=new oa({onFeedUpdate:__name(e=>{if(Lt.current!==t)return;const n=!0===e.metadata?.isAgent,r=e.metadata?.status;n&&"running"===r?ye(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):n&&r&&"running"!==r?(ye(t=>t.filter(t=>t.id!==e.id)),he(t=>[...t,e])):he(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Nt.current];return Nt.current=[],Se([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ve(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Je(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{h(e)},"onRetryUpdate"),onProviderChange:__name(e=>{G(e)},"onProviderChange"),onStatusUpdate:__name(e=>{g.current=!0,m(e)},"onStatusUpdate"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Ut({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const t=nt.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const{feedEntries:n,corruptedLines:r,totalLines:o}=await Ft.current.loadSession(e);if(Lt.current!==t)return;await sn();const s=[];if(0===n.length&&o>0?s.push(Bo(`Session could not be loaded. ${o} lines could not be parsed.`)):0===n.length?s.push(Oo("Session loaded but contains no messages.")):(r>0&&s.push(Oo(`Warning: ${r} message(s) could not be loaded.`)),s.push(...n)),Lt.current!==t)return;he(s),ma(),ie(e=>e+1)}catch(e){if(Lt.current!==t)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";he([Bo(`Failed to load session: ${n}. Starting fresh session.`)]),Te(!1),Pe(!1),Ce(crypto.randomUUID())}},"handleSelectSession"),yn=__name(async()=>{he([]),ye([]),Ft.current=null,ut(!1),Ce(crypto.randomUUID()),Te(!1),Pe(!1)},"handleNewSession"),En=__name(async()=>{try{await Bs.initializeProject(),Re(!1),e?(console.log("No conversations found to resume."),Ge(!0)):(De(!0),$t(),Dt())}catch(e){console.error("Failed to initialize project:",e),Re(!1),Ge(!0)}},"handleTrust"),wn=__name(()=>{Ge(!0)},"handleNoTrust"),bn=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void B({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),G(e),x(!1);const n=getProviderDisplayName(e);m(`Provider set to ${n}`),oe.current&&clearTimeout(oe.current),te(!0),oe.current=setTimeout(()=>{te(!1),oe.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),m("Failed to set provider"),x(!1)}},"handleProviderSelect"),Sn=__name(()=>{x(!1)},"handleProviderCancel"),kn=__name(e=>{const t=Object.values(gt).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),Cn=__name(async e=>{try{await setSelectedModel({model:e}),Y(e),R(!1);const t=kn(e);m(`Model set to ${t}`),se.current&&clearTimeout(se.current),re(!0),se.current=setTimeout(()=>{re(!1),se.current=null},5e3)}catch(e){console.error("Failed to set model:",e),m("Failed to set model"),R(!1)}},"handleModelSelect"),vn=__name(()=>{R(!1)},"handleModelCancel"),Tn=__name(()=>{if(L){B(null),x(!1),G(L.provider);const e=getProviderDisplayName(L.provider);m(`${e} authentication successful`),oe.current&&clearTimeout(oe.current),te(!0),oe.current=setTimeout(()=>{te(!1),oe.current=null},5e3)}},"handleAuthSuccess"),An=__name(()=>{B(null)},"handleAuthCancel");if(ze)return null;if(Ie)return O.createElement(O.Fragment,null,O.createElement(qi,{staticKey:ae}),O.createElement(Dc,{onTrust:En,onExit:wn}));if(Ne)return null;if(ve)return O.createElement(Ji,{onSelectSession:fn,onNewSession:yn});if(!$e)return null;if(Mt)return O.createElement(W,{flexDirection:"column",width:"100%"},O.createElement(Wi,{staticKey:ae,feed:pe,showHeader:!0,expandedToolOutput:ce,currentModel:J}),O.createElement(W,{marginY:1},O.createElement(tl,{questions:Mt.params.questions,onResponse:e=>{Mt.resolve(e),Ut(null),m("Answers submitted")}})));if(Ot){if("shell_command"===Ot.toolName){const e=Ot.params;return O.createElement(W,{flexDirection:"column",width:"100%"},O.createElement(Wi,{staticKey:ae,feed:pe,showHeader:!0,expandedToolOutput:ce,currentModel:J}),fe.map(e=>O.createElement(LiveAgentStatus,{key:e.id,entry:e})),O.createElement(W,{marginY:1},O.createElement(Yi,{request:e,onResponse:e=>{Wt(e);const t="no"!==e.value;Ot.resolve(t),_t(null),t?(m("Shell command allowed"),dt||Gt("Use shift+tab to enable auto-accept")):m("Shell command denied")},onToggleAutoAccept:Kt})))}if("kill_shell"===Ot.toolName){const e=createKillShellPermissionRequest(Ot.params);return O.createElement(W,{flexDirection:"column",width:"100%"},O.createElement(Wi,{staticKey:ae,feed:pe,showHeader:!0,expandedToolOutput:ce,currentModel:J}),O.createElement(W,{marginY:1},O.createElement(Yi,{request:e,onResponse:e=>{Wt(e);const t="no"!==e.value;Ot.resolve(t),_t(null),t?(m("Process termination allowed"),dt||Gt("Use shift+tab to enable auto-accept")):m("Process termination denied")},onToggleAutoAccept:Kt})))}{const e={action:Ot.toolName.includes("edit")?"edit":Ot.toolName.includes("write")?"create":Ot.toolName.includes("delete")?"delete":"edit",filePath:Ot.params.filePath||Ot.params.file_path||Ot.params.path||Ot.params.absolutePath||Ot.params.notebook_path||"unknown",description:`Allow ${Ot.toolName} operation`,oldContent:"edit_file"===Ot.toolName?Ot.params.oldContent:void 0,newContent:"edit_file"===Ot.toolName?Ot.params.newContent:void 0};return O.createElement(W,{flexDirection:"column",width:"100%"},O.createElement(Wi,{staticKey:ae,feed:pe,showHeader:!0,expandedToolOutput:ce,currentModel:J}),fe.map(e=>O.createElement(LiveAgentStatus,{key:e.id,entry:e})),O.createElement(W,{marginY:1},O.createElement(zi,{request:e,onResponse:e=>{Wt(e);const t="no"!==e.value;Ot.resolve(t),_t(null),t?(m("File operation allowed"),dt||Gt("Use shift+tab to enable auto-accept")):m("File operation denied")},onToggleAutoAccept:Kt})))}}return N?O.createElement(ki,{onClose:()=>{F(!1),ie(e=>e+1)}}):C?O.createElement(O.Fragment,null,O.createElement(qi,{staticKey:ae}),O.createElement(W,{flexDirection:"column",width:"100%"},O.createElement(W,{marginBottom:1},O.createElement(H,{dimColor:!0},"Press Esc to return to conversation")),O.createElement(Zi,{onClose:()=>v(!1),onSettingsChange:$t,staticKey:ae}))):T?O.createElement(O.Fragment,null,O.createElement(qi,{staticKey:ae}),O.createElement(W,{flexDirection:"column",width:"100%"},O.createElement(W,{marginBottom:1},O.createElement(H,{dimColor:!0},"Press Esc to return to conversation")),O.createElement(Qi,{onClose:()=>A(!1),staticKey:ae}))):O.createElement(W,{flexDirection:"column",width:"100%"},O.createElement(Wi,{staticKey:ae,feed:pe.filter(e=>"taste-onboarding"!==e.role),showHeader:!0,expandedToolOutput:ce,currentModel:J}),Ue&&O.createElement($c,{onComplete:It,autoLearn:Be}),fe.map(e=>O.createElement(LiveAgentStatus,{key:e.id,entry:e})),O.createElement(RetryMessage,{attempt:p}),!P&&!I&&!L&&!$&&!S&&!wt&&!kt&&!Ue&&O.createElement(Si,{queuedMessages:be,isProcessing:Ee,executionState:ue,status:u,input:l,setInput:d,onSubmit:Jt,showFileList:w,setShowFileList:b,fileSearchQuery:me,setFileSearchQuery:ge,onCommand:on,outputTokens:qe,contextUsage:Ke,tasteLearning:it,shareInfo:Ze,showShareNotification:rt,unshareNotificationMessage:st,updateStatus:f,updateFailedInfo:s,currentProvider:z,showProviderInfo:ee,autoAcceptMode:dt,onToggleAutoAccept:Kt,hintMessage:pt,historyManager:xe.current,pendingExitKey:At,onResetPendingExitKey:xt,onDoubleEscapeEmpty:qt,retryAttempt:p,onAltP:()=>R(!0)}),P&&O.createElement(W,{marginY:1},O.createElement(Gi,{onSelect:bn,onCancel:Sn,currentProvider:z})),I&&O.createElement(W,{marginY:1},O.createElement(Hi,{onSelect:Cn,onCancel:vn,currentModel:J})),S&&O.createElement(W,{marginY:1},O.createElement(ti,{onCancel:()=>k(!1)})),$&&O.createElement(W,{marginY:1},O.createElement(Ci,{onClose:()=>D(!1)})),wt&&Ft.current&&O.createElement(W,{marginY:1},O.createElement(Ki,{checkpoints:Ft.current.listCheckpoints(),onSelect:tn,onCancel:nn})),L&&O.createElement(W,{marginY:1},O.createElement(L.Component,{onSuccess:Tn,onCancel:An})),kt&&O.createElement(W,{marginY:1},O.createElement(Nc,{onComplete:dn,onCancel:un})))},"InteractiveCLI");dn(),Xt();var sl=__name(e=>e?{isValid:!0}:{isValid:!1,errorMessage:["Error: Interactive mode requires a TTY terminal.","Please run this command directly in your terminal, not through a pipe or redirect."].join("\n")},"validateTtyEnvironment"),al=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),il=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),cl=__name(({options:e})=>({resume:e.resume,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding}),"buildInteractiveCLIProps"),ll=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),dl=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),ul=__name(()=>{dl()},"initializeTerminal"),ml=__name(async(e={})=>{const t=sl(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),ul(),al(e)){const e=await Bs.isProjectInitialized(),t=e?await Bs.listSessions():[],n=il({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=cl({options:e}),r=ll();G(O.createElement(ol,{...n}),r)},"interactiveMode");wt(),Ct(),Lt(),hn(),En(),Dt();var gl=null,pl=!1,hl=new Set([co,lo,po]);async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n.trim())}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}async function isAuthenticated(){return null!==await getAuthKey()}function setupSignalHandlers(){if(pl)return;pl=!0;const e=__name(e=>{gl?.abort(),process.stderr.write(`\n${e}\n`),process.exit(130)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated.")),process.stdout.on("error",e=>{"EPIPE"===e.code&&process.exit(0),process.stderr.write(`Error writing to stdout: ${e.message}\n`),process.exit(1)})}async function printMode(e={}){setupSignalHandlers(),gl=new AbortController;let t=e.query||"";if(!t){process.stdin.isTTY&&(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1));try{t=await readStdin()}catch(e){const t=e instanceof Error?e.message:"Unknown error";process.stderr.write(`Error reading from stdin: ${t}\n`),process.exit(1)}}t.trim()||(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1)),await isAuthenticated()||(process.stderr.write('Error: Not authenticated. Please run "cmd login" first.\n'),process.exit(3)),e.dangerouslySkipPermissions&&process.stderr.write("Warning: Running with --dangerously-skip-permissions. File writes and shell commands will execute without prompts.\n");try{const n=await processQuery({query:t,signal:gl.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions});process.stdout.write(n),n.endsWith("\n")||process.stdout.write("\n"),process.exit(0)}catch(e){e instanceof Error&&"AbortError"===e.name&&(process.stderr.write("\nCancelled.\n"),process.exit(130)),e instanceof Jr&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof Yr&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof eo&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Vr&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof to&&(process.stderr.write("Error: The API server encountered an error. Please try again later.\n"),process.exit(7));const t=e instanceof Error?e.message:"Unknown error";/permission denied|access denied|not permitted|unauthorized/i.test(t)&&(process.stderr.write(`Error: ${t}\n`),process.exit(4)),process.stderr.write(`Error: ${t}\n`),process.exit(1)}}__name(readStdin,"readStdin"),__name(isAuthenticated,"isAuthenticated"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode");var fl=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===ut.ANTHROPIC&&(r=await Rt.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o=getEnvironmentContext(),s=await getMemoryContent([]),a=await getTasteContent(),i=generateSkillsXML(await loadAllSkillSummaries())||null,c=crypto.randomUUID(),l=await isTasteLearningEnabled(),d={[it.PROJECT_SLUG]:Bs.getCurrentProjectDirName(),[it.TASTE_LEARNING]:l.toString(),[it.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(d[it.OAUTH_TOKEN]=`Bearer ${r}`),{tools:e,config:o,memory:s,taste:a,skills:i,headers:d,sessionId:c}}async function callApi(e,t,n,r){const o={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:`anthropic:${getConfiguredModel()}`},s={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:o,threadId:t.sessionId},a=await e.post({body:s,stream:!0,endpoint:ct.ALPHA.GENERATE,headers:t.headers,signal:r});return Fe.fromReadableStream(a).finalMessage()}async function executeToolCall(e,t,n){if(hl.has(e.name)&&!n)return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool "${e.name}" requires permissions. Use --dangerously-skip-permissions to enable file writes and shell commands in print mode.`,is_error:!0};try{const n=await executeTool(e.name,e.input,{abortSignal:t});return{type:"tool_result",tool_use_id:e.id,content:n}}catch(t){if(t instanceof Jr||t instanceof Yr||t instanceof eo||t instanceof Vr||t instanceof to)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1}=e,o=getApiBaseUrl(),s=new no({baseUrl:o}),a=[{role:"user",content:t}],i=await setupConversationContext();let c=0,l="";for(;c<fl;){if(c++,n.aborted)throw new Error("Cancelled");const e=await callApi(s,i,a,n),t=e.content.filter(e=>"text"===e.type),o=e.content.filter(e=>"tool_use"===e.type),d=t.map(e=>e.text).join("");if(d&&(l+=d),0===o.length)break;const u=[];for(const e of o){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);u.push(t)}a.push({role:"assistant",content:e.content}),a.push({role:"user",content:u})}return c>=fl&&process.stderr.write(`Warning: Reached maximum conversation turns (${fl}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),l}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery");var yl=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),El=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),wl=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),t},"buildRuntimeOptions"),bl=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),Sl=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(void 0!==t.print){const n=Sl(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=yl(e);await El();const r=wl(t),o=bl({options:t,runtimeOptions:r,initialPrompt:n});ml(o)}__name(interactiveModeAction,"interactiveModeAction"),wt(),mn(),ar(),globalThis.COMMAND_CODE_CWD=process.cwd();var kl=__name(()=>process.cwd(),"getCwd"),Cl=__name(()=>process.argv.slice(2),"getArgs"),vl=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),Tl=__name(()=>{const e=kl(),t=Cl(),n=vl(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`)},"logStartupInfo");async function preRun(){Tl(),process.argv.includes("--ide-setup")&&(formatSetupResult(await runIDESetup()).forEach(e=>console.log(e)),process.exit(0)),await maybeRunPendingUpdate(),checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100)}__name(preRun,"preRun"),wt(),Ct(),mn(),Pn(),yn();var Al=getPackageJson();function displayCustomHelp(){const e=Al.version,t=getInvokedCommandName(),n=Ni.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(J.bold("Command Code")+J.gray(` v${e}`)),console.log(J.gray(Ii)),console.log(),console.log(J.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(J.bold("Options"));for(const e of Di){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ri)+J.gray(e.description))}console.log(),console.log(J.bold("Commands"));for(const e of Fi){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ri)+J.gray(e.description))}console.log(),console.log(J.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Ri)+J.gray(e.description));console.log(),console.log(J.bold("Keyboard Shortcuts"));for(const e of $i)console.log(" "+e.key.padEnd(Ri)+J.gray(e.description));console.log(),console.log(J.bold("Examples"));for(const e of Oi){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ri)+J.gray(e.description))}console.log(),console.log(J.cyan("❯")+" "+J.gray(_i.replace(/cmd/,t))),console.log(),console.log(J.bold("Links"));for(const e of Li)console.log(" "+e.key.padEnd(Ri)+J.cyan(e.description));console.log()}function createProgram(){const e=new ye;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(Al.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume","Resume a session (pick from history)").option("-c, --continue"," Continue the most recent session in the current directory").option("-t, --trust","Trust the project (skip initial trust permission prompt)").option("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").option("--ide-setup","Setup extension to fetch IDE context").addOption(new Ee(st).hideHelp()).addOption(new Ee(at).hideHelp()).addOption(new Ee("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ee("--local","Use local server").hideHelp()).addOption(new Ee("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(`[cmd] ${r&&r!==n?"subcommand":"running"}: ${n}`);const o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const a=t.args;a.length>0&&dlog(`[cmd] arguments: ${a.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),wt(),rr();var Pl=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=m.platform(),n=m.arch();let r,o,s,a;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,o=e.user?.id,s=e.org?.login,a=e.org?.id)}catch{}if(!o)try{const e=await loadCredentials();o=e?.userId}catch{}systemInfo({userName:r,userId:o,orgLogin:s,orgId:a,nodeVersion:e,platform:t,arch:n})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){Pl||(Pl=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=xe("Opening GitHub issues...").start();try{await X(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually")),console.log("")}}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal"),wt(),__name(openGitHubIssue,"openGitHubIssue");var xl=new ye("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);wt();var Il=new ye("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});wt();var Rl=new ye("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{const{waitUntilExit:t}=G(O.createElement(zc,{verbose:e.verbose,text:e.text}));await t()});wt(),Ct(),mn(),rr();var $l=new ye(mt.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{const{unmount:e}=G(O.createElement(Ic,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:_n.LEARN_TASTE_COMMAND,heading:"Learn taste render failed"}}),dlog(`[/learn-taste] render failed: ${e instanceof Error?e.message:String(e)}`),await shutdownTelemetry(),process.exit(1)}});function getTastePath(t){const{target:n}=t;switch(n){case"local-project":return e.join(process.cwd(),".commandcode","taste");case"local-global":return e.join(m.homedir(),".commandcode","taste");case"remote-project":case"remote-user":throw new Error(`Remote storage not yet implemented: ${n}`);default:throw new Error(`Unknown storage target: ${n}`)}}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"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 s=[];for(const e of t){const t=parseLearning({line:e});t&&s.push(t)}s.length>0&&r.push({category:normalizeCategory({category:o}),learnings:s,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}wt(),Ct(),wt(),wt(),wt(),wt(),wt(),Ct(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),wt(),__name(parseTasteBuckets,"parseTasteBuckets"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),wt(),__name(formatBucket,"formatBucket");var Dl=class{static{__name(this,"LocalProjectStorage")}target="local-project";async getAllBuckets(){const e=getTastePath({target:this.target});if(!y(e))return[];const t=[],n=getRootTasteFile({target:this.target});if(y(n)){let e=await P.readFile(n,"utf-8");const r=migrateHeader({content:e});r!==e&&(await P.writeFile(n,r,"utf-8"),e=r);const o=parseTasteBuckets({content:e,sourcePath:n});t.push(...o)}const r=await P.readdir(e,{withFileTypes:!0});for(const e of r)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(y(n)){let r=await P.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await P.writeFile(n,o,"utf-8"),r=o);const s=parseTasteBuckets({content:r,sourcePath:n});for(const t of s)t.category=e.name;t.push(...s)}}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 P.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:this.target}),o=t.learnings.length,s=await this.removeBucket({category:t.category});o<=5?await this.writeToRoot({bucket:t,rootFile:r,categoryPosition:s}):await this.writeToSubdirectory({bucket:t,rootFile:r,categoryPosition:s})}async removeBucket(t){const{category:n}=t,r=getRootTasteFile({target:this.target});let o=null;if(y(r)){let e=await P.readFile(r,"utf-8");e=migrateHeader({content:e});const t=e.split("\n");let s=-1,a=-1;const i=new RegExp(`^# ${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i");for(let e=0;e<t.length;e++)if(i.test(t[e])){s=e;for(let n=e+1;n<t.length;n++)if(t[n].startsWith("# ")){let r=n-1;for(;r>e&&""===t[r].trim();)r--;a=r;break}-1===a&&(a=t.length-1);break}if(-1!==s){const e=t.slice(0,s),n=a<t.length-1?t.slice(a+1):[];o={before:e.join("\n").trim(),after:n.join("\n").trim()};const i=[...e,...n].join("\n").trim();""===i?await P.rm(r,{force:!0}):await P.writeFile(r,i+"\n","utf-8")}}const s=getCategoryTasteFile({target:this.target,category:n}),a=e.dirname(s);return y(a)&&await P.rm(a,{recursive:!0,force:!0}),o}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(La)&&(e=La+"\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 P.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";y(n)&&(e=await P.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(La)||(e=La+"\n\n"+e):e=La+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o,await P.writeFile(n,e.trim()+"\n","utf-8")}}async writeToSubdirectory(t){const{bucket:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:this.target,category:n.category}),a=e.dirname(s);await P.mkdir(a,{recursive:!0});const i=formatBucket({bucket:n});await P.writeFile(s,i,"utf-8");const c=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=o.before;e=migrateHeader({content:e}),e&&!e.trim().startsWith(La)&&(e=La+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=c.trim(),o.after&&(e+="\n\n"+o.after),await P.writeFile(r,e.trim()+"\n","utf-8")}else{let e="";y(r)&&(e=await P.readFile(r,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(La)||(e=La+"\n\n"+e):e=La+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=c,await P.writeFile(r,e.trim()+"\n","utf-8")}}exists(){const e=getTastePath({target:this.target});return y(e)}};wt();var Nl=class{static{__name(this,"LocalGlobalStorage")}target="local-global";async getAllBuckets(){const e=getTastePath({target:this.target});if(!y(e))return[];const t=[],n=await P.readdir(e,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(y(n)){let r=await P.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await P.writeFile(n,o,"utf-8"),r=o);const s=parseTasteBuckets({content:r,sourcePath:n});for(const t of s)t.category=e.name;t.push(...s)}}return t}async getBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t});if(!y(n))return null;let r=await P.readFile(n,"utf-8");const o=migrateHeader({content:r});return o!==r&&(await P.writeFile(n,o,"utf-8"),r=o),parseTasteBuckets({content:r,sourcePath:n})[0]||null}async writeBucket(t){const{bucket:n}=t,r=getTastePath({target:this.target});await P.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:this.target,category:n.category}),s=e.dirname(o);await P.mkdir(s,{recursive:!0});const a=formatBucket({bucket:n});await P.writeFile(o,a,"utf-8")}async deleteBucket(t){const{category:n}=t,r=getCategoryTasteFile({target:this.target,category:n}),o=e.dirname(r);y(o)&&await P.rm(o,{recursive:!0,force:!0})}async listBuckets(){const e=await this.getAllBuckets(),t=[];for(const n of e){let e;try{e=(await P.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 y(e)}};async function prepareUploadFormData(t){const{packageName:n,bucket:r,description:o,type:s="category",isPublic:a=!1}=t,i=new FormData;if(i.append("name",n),o&&i.append("description",o),i.append("type",s),i.append("isPublic",String(a)),"category"===s){const e=formatBucket({bucket:r}),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",n)}else{const t=formatBucket({bucket:r}),n=new Blob([t],{type:"text/markdown"}),o=new File([n],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",o);const s=getTastePath({target:"local-project"}),a=e.join(s,r.category);if(y(a)){const e=getCategoryTasteFile({target:"local-project",category:r.category});if(y(e)){const t=await P.readFile(e,"utf-8"),n=new Blob([t],{type:"text/markdown"}),o=new File([n],"taste.md",{type:"text/markdown"});i.append(`files[${r.category}/taste.md]`,o)}}}return i}async function prepareMultiplePackagesUpload(e){const{buckets:t,projectName:n,description:r,isPublic:o=!1}=e,s=new FormData;s.append("name",n),r&&s.append("description",r),s.append("type","project"),s.append("isPublic",String(o));const a=getRootTasteFile({target:"local-project"});if(y(a)){const e=await P.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",n)}for(const e of t){const t=getCategoryTasteFile({target:"local-project",category:e.category});if(y(t)){const n=await P.readFile(t,"utf-8"),r=new Blob([n],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});s.append(`files[${e.category}/taste.md]`,o)}}return s}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}wt(),wt(),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),Ct(),wt(),__name(parseTasteContent,"parseTasteContent"),rr();var Fl=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()}${ct.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{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"list_packages_error"}),context:{component:_n.TASTE_REMOTE_STORAGE,heading:"Failed to list taste packages","http.status":n.status}}),t}const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const s=[];for(const e of o)try{const t=await this.getBucket({category:e.name});t&&s.push(t)}catch(t){trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"download_package_error"}),context:{component:_n.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${t instanceof Error?t.message:String(t)}`)}return s}async downloadPackage(e){const{namespace:t,packageName:n}=e,r=getApiBaseUrl(),o=`${r}${ct.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",t).replace(":packageName",n)}`;try{const e=await fetch(o,{method:"GET"});if(e.ok){const{data:t}=await e.json();return{type:t.type||"category",files:t.files||[],isPublic:!0}}if(404!==e.status){let t="Failed to download taste package";try{const n=await e.json();t=n.error?.message||n.message||`${t} (${e.status})`}catch{t=`${t} (${e.status})`}const n=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_public_error"}),context:{component:_n.TASTE_REMOTE_STORAGE,heading:"Failed to download taste package (public)","http.status":e.status}}),n}if(!await getAuthKey())throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`")}catch(e){if(e instanceof Error)throw e}const s=await getAuthKey();if(!s)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");const a=`${r}${ct.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",t).replace(":packageName",n)}`,i=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${s}`}});if(!i.ok){if(404===i.status)return null;let e="Failed to download taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"download_auth_error"}),context:{component:_n.TASTE_REMOTE_STORAGE,heading:"Failed to download taste package (authenticated)","http.status":i.status}}),t}const{data:c}=await i.json();return{type:c.type||"category",files:c.files||[],isPublic:c.isPublic??!1}}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 s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async writeBucket(e){const{bucket:t,namespace:n,isPublic:r=!1}=e,o=await getAuthKey();if(!o)throw new Error("No API key found. Please authenticate with: cmd login");const s=await prepareUploadFormData({packageName:t.category,bucket:t,type:"category",isPublic:r}),a=`${getApiBaseUrl()}${ct.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,i=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:s});if(!i.ok){let e="Failed to upload taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"upload_package_error"}),context:{component:_n.TASTE_REMOTE_STORAGE,heading:"Failed to upload taste package","http.status":i.status}}),t}await i.json()}async writeBuckets(e){const{buckets:t,projectName:n,namespace:r,isPublic:o=!1}=e,s=await getAuthKey();if(!s)throw new Error("No API key found. Please authenticate with: cmd login");const a=await prepareMultiplePackagesUpload({buckets:t,projectName:n,isPublic:o}),i=`${getApiBaseUrl()}${ct.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,c=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:a});if(!c.ok){let e="Failed to upload taste packages";try{const t=await c.json();e=t.error?.message||t.message||e}catch{}const n=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:n,label:"upload_packages_error"}),context:{component:_n.TASTE_REMOTE_STORAGE,heading:"Failed to upload taste packages","http.status":c.status,"package.count":t.length}}),n}await c.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()}${ct.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{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"list_buckets_error"}),context:{component:_n.TASTE_REMOTE_STORAGE,heading:"Failed to list buckets","http.status":n.status}}),t}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:"",isPublic:e.isPublic??!1,starCount:e.starCount??0,downloadCount:e.downloadCount??0,type:e.type??"category"}))}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 s=new Map(o);for(const e of t){const t=o.get(e.text);t?e.confidence>t.confidence?(s.set(e.text,e),r.updated++):(e.confidence,t.confidence,r.unchanged++):(s.set(e.text,e),r.added++)}for(const e of n)t.some(t=>t.text===e.text)||r.unchanged++;return{merged:Array.from(s.values()),details:r}}wt(),__name(mergeLearnings,"mergeLearnings"),wt();var Ll=/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"),s=[];let a=0;for(;a<o.length;){const e=o[a],t=a+1,n=e.trim();if(n.startsWith("-"))if(Ll.test(n))s.push({text:e,originalLineNum:t}),a++;else{let n=e,r=a+1;for(;r<o.length;){const e=o[r].trim();if(e.startsWith("#")||e.startsWith("-"))break;if(e.length>0&&(n=n+" "+e),Ll.test(e)){r++;break}r++}s.push({text:n,originalLineNum:t}),a=r}else s.push({text:e,originalLineNum:t}),a++}let i=null,c=null,l=0;for(const{text:e,originalLineNum:t}of s){if(!e.trim())continue;if(e.trim().startsWith("# ")){if("# Taste (Continuously Learned by CommandCode.ai)"===e.trim()||"# Taste (Continuously Learned by CommandCode)"===e.trim())continue;i&&0===l&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:c-1})||r.push({line:c,severity:"warning",message:`Category '${i}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),i=e.trim().substring(2).trim(),c=t,l=0;continue}if(e.trim().startsWith("-")){if(!i){r.push({line:t,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'});continue}l++;const n=validateLearningLine({line:e.trim(),lineNum:t});r.push(...n);continue}const n=e.trim();/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i.test(n)||r.push({line:t,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 i&&0===l&&c&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:c-1})||r.push({line:c,severity:"warning",message:`Category '${i}' 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(!Ll.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 s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),a=s.length>0?s[s.length-1]:null;if(!a)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=a[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=a&&void 0!==a.index?o.substring(0,a.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),s=0===r.length;let a;if(0===t.length)a=`✓ ${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":""}`),a=`${r.length>0?"✗":"⚠"} ${n} has ${e.join(", ")}`}return{valid:s,issues:t,summary:a}}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`${J.green(e)} ${J.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity),s=[r.length>0?J.red(t.summary):J.yellow(t.summary),""];if(r.length>0){s.push(J.bold(J.red("Errors:")));for(const e of r){const t=e.line?J.dim(` Line ${e.line}: `):" ";s.push(`${t}${J.red(e.message)}`),e.suggestion&&s.push(J.dim(` → ${e.suggestion}`))}s.push("")}if(o.length>0){s.push(J.bold(J.yellow("Warnings:")));for(const e of o){const t=e.line?J.dim(` Line ${e.line}: `):" ";s.push(`${t}${J.yellow(e.message)}`),e.suggestion&&s.push(J.dim(` → ${e.suggestion}`))}s.push("")}return s.join("\n").trim()}async function promptMergeStrategy(e){const{packageName:t,namespace:n,localBucket:r,remoteLearningsCount:o}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${r.learnings.length} learnings`),console.log(`Remote: ${o} learnings (from ${n})\n`);const s=await we.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} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});return we.isCancel(s)&&(we.cancel("Operation cancelled"),process.exit(0)),s}async function promptPushStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteBucket:o}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${o.learnings.length} learnings (in ${n})\n`);const s=await we.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 (${o.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"}],initialValue:"merge"});return we.isCancel(s)&&(we.cancel("Operation cancelled"),process.exit(0)),s}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalBucket:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists in global storage\n`)),console.log(`Local: ${n} learnings`),console.log(`Global: ${r.learnings.length} learnings\n`);const o=await we.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 we.isCancel(o)&&(we.cancel("Operation cancelled"),process.exit(0)),o}async function promptGlobalPullStrategy(e){const{packageName:t,localBucket:n,globalLearningsCount:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${n.learnings.length} learnings`),console.log(`Global: ${r} learnings\n`);const o=await we.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 we.isCancel(o)&&(we.cancel("Operation cancelled"),process.exit(0)),o}async function promptTypeMismatchStrategy(e){const{packageName:t,namespace:n,localType:r,remoteType:o,localLearningsCount:s,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, skipping push`)),"skip";const i=`https://commandcode.ai/${n}/${t}`;console.log(J.yellow(`\n${pe.warning} Pushing local project taste to individual package '${t}'\n`)),console.log(`Local: ${t} (${s} learnings)`),console.log(`Remote: ${t} (${a} learnings) in ${n}\n`),console.log(`Review package: ${J.cyan(i)}\n`);const c=await we.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});return we.isCancel(c)&&(we.cancel("Operation cancelled"),process.exit(0)),c}async function promptSameTypeStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteLearningsCount:o}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, skipping push`)),"skip";const s=`https://commandcode.ai/${n}/taste/${t}`;console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${o} learnings\n`),console.log(`Review taste package: ${J.cyan(s)}\n`);const a=await we.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${o} → ${r} learnings)`}],initialValue:"skip"});return we.isCancel(a)&&(we.cancel("Operation cancelled"),process.exit(0)),a}async function push(t){const n=void 0!==t.isPublic,{buckets:r,target:o,overwrite:s=!1,isPublic:a=!1}=t,i=new Dl,c={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!i.exists())return c.success=!1,c.errors.push({bucket:"all",error:"No taste directory found in project"}),c;const l=await i.getAllBuckets();if(0===l.length)return c.success=!1,c.errors.push({bucket:"all",error:"No taste packages found in project"}),c;for(const e of l){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){c.success=!1;const n=formatValidationIssues({result:t,verbose:!0});c.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(c.errors.length>0)return c;const d=r.length>0?l.filter(e=>r.includes(e.category)):l;if(r.length>0&&0===d.length){c.success=!1;for(const e of r)c.errors.push({bucket:e,error:"Taste package not found in project"});return c}let u,m;if("remote-project"===o||"remote-user"===o)try{const e=await getAuthenticatedEntity();e.success&&e.user?.userName&&(u=e.user.userName)}catch{}if("remote-project"===o&&0===r.length){const t=e.basename(process.cwd()),r=new Fl;if(!u)return c.success=!1,c.errors.push({bucket:"all",error:"Failed to get user namespace for remote push"}),c;try{const e=await r.downloadPackage({namespace:u,packageName:t});let o="overwrite";const i="project",l=e?.type??"category",m=d.reduce((e,t)=>e+t.learnings.length,0),g=e?.files?e.files.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0):0;if(o=s?"overwrite":e?l!==i?await promptTypeMismatchStrategy({packageName:t,namespace:u,localType:i,remoteType:l,localLearningsCount:m,remoteLearningsCount:g}):await promptSameTypeStrategy({packageName:t,namespace:u,type:i,localLearningsCount:m,remoteLearningsCount:g}):"overwrite","skip"===o)return c;await r.writeBuckets({buckets:d,projectName:t,namespace:u,type:"project",isPublic:n?a:e?.isPublic??!1});for(const e of d)c.bucketsPushed.push(e.category),c.filePaths[e.category]=`${u}/${t}`,c.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if(e)for(const e of d)c.overwritten.push(e.category);return c}catch(e){return c.success=!1,c.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),c}}switch(o){case"local-global":m=new Nl;break;case"remote-project":case"remote-user":m=new Fl;break;default:return c.success=!1,c.errors.push({bucket:"all",error:`Invalid target: ${o}`}),c}for(const e of d)try{const t=await m.getBucket({category:e.category});let n;if(n=s?"overwrite":t&&"local-global"===o?await promptGlobalPushStrategy({packageName:e.category,localLearningsCount:e.learnings.length,globalBucket:t}):"merge","skip"===n)continue;if("overwrite"===n){if("local-global"===o)await m.writeBucket({bucket:e});else{if(!u)throw new Error("Failed to get user namespace for remote push");await m.writeBucket({bucket:e,namespace:u,isPublic:a})}c.bucketsPushed.push(e.category),c.overwritten.push(e.category)}else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},c.mergeDetails[e.category]=r.details}else n=e,c.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if("local-global"===o)await m.writeBucket({bucket:n});else{if(!u)throw new Error("Failed to get user namespace for remote push");await m.writeBucket({bucket:n,namespace:u,isPublic:a})}c.bucketsPushed.push(e.category)}if("local-global"===o){const t=getCategoryTasteFile({target:"local-global",category:e.category});c.filePaths[e.category]=t}else"remote-project"!==o&&"remote-user"!==o||!u||(c.filePaths[e.category]=`${u}/${e.category}`)}catch(t){c.success=!1,c.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return c}async function pull(e){const{buckets:t,source:n,overwrite:r=!1}=e,o=new Dl,s={success:!0,bucketsPulled:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},a=__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 Nl;break;case"remote-project":case"remote-user":i=new Fl;break;default:return s.success=!1,s.errors.push({bucket:"all",error:`Invalid source: ${n}`}),s}try{c=await i.getAllBuckets()}catch(e){return s.success=!1,s.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),s}if(0===c.length)return s.success=!1,s.errors.push({bucket:"all",error:`No taste packages found in ${a}`}),s;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){s.success=!1;const n=formatValidationIssues({result:t,verbose:!0});s.errors.push({bucket:e.category,error:`Validation failed for taste package in ${a}:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in ${a} has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(s.errors.length>0)return s;const l=t.length>0?c.filter(e=>t.includes(e.category)):c;if(t.length>0&&0===l.length){s.success=!1;for(const e of t)s.errors.push({bucket:e,error:`Taste package not found in ${a}`});return s}for(const e of l)try{const t=await o.getBucket({category:e.category});let a;if(a=r?"overwrite":t&&"local-global"===n?await promptGlobalPullStrategy({packageName:e.category,localBucket:t,globalLearningsCount:e.learnings.length}):"merge","skip"===a)continue;if("overwrite"===a)await o.writeBucket({bucket:e}),s.bucketsPulled.push(e.category),s.overwritten.push(e.category);else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},s.mergeDetails[e.category]=r.details}else n=e,s.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),s.bucketsPulled.push(e.category)}const i=getCategoryTasteFile({target:"local-project",category:e.category});s.filePaths[e.category]=i}catch(t){s.success=!1,s.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return s}async function pullRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new Dl,s=new Fl,a={success:!0,bucketsPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};try{const e=await s.downloadPackage({namespace:t,packageName:n});if(!e)return a.success=!1,a.errors.push({bucket:n,error:"Taste package not found in remote"}),a;const{type:i,files:c}=e;for(const e of c){const t=validateTasteFile({content:e.content,filePath:e.file});if(!t.valid){a.success=!1;const r=formatValidationIssues({result:t,verbose:!0});a.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(a.errors.length>0)return a;"project"===i?await pullProjectPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:a}):await pullCategoryPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:a})}catch(e){a.success=!1,a.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return a}async function pullProjectPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:s,result:a}=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:s,result:a})}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:s,result:a})}}async function processBucket(e){const{bucket:t,namespace:n,overwrite:r,targetStorage:o,result:s}=e;try{const e=await o.getBucket({category:t.category});let a;if(a=r?"overwrite":e?await promptMergeStrategy({packageName:t.category,namespace:n,localBucket:e,remoteLearningsCount:t.learnings.length}):"merge","skip"===a)return void s.skipped.push(t.category);if("overwrite"===a)await o.writeBucket({bucket:t}),s.bucketsPulled.push(t.category),s.overwritten.push(t.category);else{let n;if(e){const r=mergeLearnings({source:t.learnings,target:e.learnings});n={...t,learnings:r.merged},s.mergeDetails[t.category]=r.details}else n=t,s.mergeDetails[t.category]={added:t.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),s.bucketsPulled.push(t.category)}const i=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=i}catch(e){s.success=!1,s.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:s,result:a}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return a.success=!1,void a.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:s,result:a})}async function pushRemote(e){const t=void 0!==e.isPublic,{namespace:n,packageName:r,overwrite:o=!1,isPublic:s=!1}=e,a=new Dl,i=new Fl,c={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!a.exists())return c.success=!1,c.errors.push({bucket:r,error:"No taste directory found in project"}),c;try{const e=await a.getBucket({category:r});if(!e)return c.success=!1,c.errors.push({bucket:r,error:`Taste package '${r}' not found in local project`}),c;const l=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!l.valid){c.success=!1;const e=formatValidationIssues({result:l,verbose:!0});return c.errors.push({bucket:r,error:`Validation failed:\n${e}`}),c}if(l.issues.filter(e=>"warning"===e.severity).length>0){console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`);const e=formatValidationIssues({result:l,verbose:!0});console.warn(e+"\n")}const d=await i.downloadPackageToBucket({namespace:n,packageName:r});let u;u=o?"overwrite":d?await promptPushStrategy({packageName:r,namespace:n,localLearningsCount:e.learnings.length,remoteBucket:d}):"merge";const m=t?s:d?.isPublic??!1;if("skip"===u)return c;if("overwrite"===u)await i.writeBucket({bucket:e,namespace:n,isPublic:m}),c.bucketsPushed.push(r),c.overwritten.push(r);else{let t;if(d){const n=mergeLearnings({source:e.learnings,target:d.learnings});t={...e,learnings:n.merged},c.mergeDetails[r]=n.details}else t=e,c.mergeDetails[r]={added:e.learnings.length,updated:0,unchanged:0};await i.writeBucket({bucket:t,namespace:n,isPublic:m}),c.bucketsPushed.push(r)}c.filePaths[r]=`${n}/${r}`}catch(e){c.success=!1,c.errors.push({bucket:r,error:e instanceof Error?e.message:String(e)})}return c}async function list(e){const{location:t}=e;let n;switch(t){case"local-project":n=new Dl;break;case"local-global":n=new Nl;break;case"remote-project":case"remote-user":n=new Fl;break;default:throw new Error(`Invalid location: ${t}`)}return n instanceof Nl||n instanceof Fl?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 Nl;break;case"remote-project":case"remote-user":o=new Fl;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(!y(o))return r.success=!1,r.errors.push({file:"all",error:"No taste directory found in "+("local-global"===n?"global":"project")}),r;const s=[];if(t.length>0)for(const e of t){const t=getCategoryTasteFile({target:n,category:e});y(t)?s.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});y(e)&&s.push({path:e,displayName:"taste.md"});const t=await P.readdir(o,{withFileTypes:!0});for(const e of t)if(e.isDirectory()){const t=getCategoryTasteFile({target:n,category:e.name});y(t)&&s.push({path:t,displayName:`${e.name}/taste.md`})}}if(0===s.length&&r.errors.length>0)return r;if(0===s.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 s){let t=await P.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await P.writeFile(e.path,n,"utf-8"),t=n);const o=validateTasteFile({content:t,filePath:e.displayName}),s=o.issues.filter(e=>"error"===e.severity),a=o.issues.filter(e=>"warning"===e.severity);r.totalErrors+=s.length,r.totalWarnings+=a.length,o.valid||(r.success=!1);const i=formatValidationIssues({result:o});r.filesLinted.push({file:e.displayName,valid:o.valid,errors:s.length,warnings:a.length,formatted:i})}return r}async function open6(e){const{package:t,target:n}=e;try{let e;switch(n){case"local-project":e=new Dl;break;case"local-global":e=new Nl;break;case"remote-project":case"remote-user":e=new Fl;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,s=await findCategoryLineNumber({filePath:o,category:t});return await qe([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}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(t){const{filePath:n,category:r}=t;try{const t=await P.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const o=t.split("\n");for(let e=0;e<o.length;e++)if(o[e].trim().toLowerCase()===`# ${r.toLowerCase()}`)return e+1;return 1}catch{return 1}}function getEditorSetupInstructions(){const e=Ke.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 t=e.join(m.homedir(),".commandcode","taste",".metadata.json");if(y(t))try{await P.unlink(t)}catch{}}__name(validateTasteFile,"validateTasteFile"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(validateLearningLine,"validateLearningLine"),__name(buildResult,"buildResult"),__name(formatValidationIssues,"formatValidationIssues"),wt(),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptPushStrategy,"promptPushStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),__name(push,"push"),wt(),__name(pull,"pull"),wt(),__name(pullRemote,"pullRemote"),__name(pullProjectPackage,"pullProjectPackage"),__name(processBucket,"processBucket"),__name(pullCategoryPackage,"pullCategoryPackage"),wt(),__name(pushRemote,"pushRemote"),wt(),__name(list,"list"),wt(),__name(deleteBuckets,"deleteBuckets"),wt(),__name(lint,"lint"),wt(),__name(open6,"open"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),wt(),__name(runMigrations,"runMigrations"),__name(removeMetadataFile,"removeMetadataFile");var Ol=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 open6(e)}};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 we.select({message:"Select namespace to push to\n",options:r,initialValue:t});return we.isCancel(o)&&(we.cancel("Operation cancelled"),process.exit(0)),o}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new no({baseUrl:e}),n=await t.get({endpoint:ct.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}}function createTasteCommand(){const e=new ye(mt.TASTE);e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments();const t=new Ol;return e.command("push").description("Push taste packages from project to remote or global storage (prompts on conflicts)").argument("[package]","Package name (optional if using --all)").option("--all","Push all packages").option("--remote","Push to remote (default)").option("-g, --global","Push to global storage").addOption(new Ee("--local","Use local server").hideHelp()).option("--public","Make this package publicly discoverable").option("--overwrite","Overwrite target without prompting (default: interactive merge)").addOption(new Ee("--staging","Push to staging environment").hideHelp()).action(async(e,n)=>{try{let r;if(n.global||n.remote||(n.remote=!0),n.global&&n.remote&&(console.error(J.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),e||n.all||(console.error(J.red("Error: Please specify a package name or use --all flag")),console.error(J.gray("Usage: cmd taste push <package> (pushes to remote by default)")),console.error(J.gray(" cmd taste push --all (pushes whole project)")),console.error(J.gray(" cmd taste push <package> -g (for global)")),process.exit(1)),e&&n.all&&(console.error(J.red("Error: Cannot use both package name and --all flag")),process.exit(1)),n.remote)if(n.all)r=await t.push({buckets:[],target:"remote-project",overwrite:n.overwrite,isPublic:n.public});else{let o,s;if(e&&e.includes("/")){const[t,n]=e.split("/");t&&n||(console.error(J.red("Error: Invalid namespace/package format")),console.error(J.gray("Usage: cmd taste push --remote username/packageName")),console.error(J.gray(" cmd taste push --remote org-name/packageName")),process.exit(1)),o=t,s=n}else{e||(console.error(J.red("Error: Please specify a package name")),console.error(J.gray("Usage: cmd taste push <namespace>/<package>")),console.error(J.gray(" or: cmd taste push <package> (interactive namespace selection)")),process.exit(1)),s=e;let n;(await t.list({location:"local-project"})).some(e=>e.category===s)||(console.error(J.red(`Error: Taste package '${s}' not found in local project`)),process.exit(1));try{n=await fetchUserNamespaces()}catch(e){throw e}o=n.orgs.length>0?await promptNamespaceSelection(n):n.userName}r=await t.pushRemote({namespace:o,packageName:s,overwrite:n.overwrite,isPublic:n.public})}else{const o="local-global",s=n.all?[]:[e];r=await t.push({buckets:s,target:o,overwrite:n.overwrite})}if(!r.success){for(const e of r.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(J.red(`Error: ${t}`))}process.exit(1)}let o=!1;if(n.all&&r.bucketsPushed.length>0){const e=r.filePaths?.[r.bucketsPushed[0]];if(e)if(n.overwrite)console.log(J.green(`✓ Replaced taste in ${e}`));else if(r.mergeDetails){let t=0,n=0,s=0;for(const e of Object.values(r.mergeDetails))t+=e.added??0,n+=e.updated??0,s+=e.unchanged??0;const a=[];t>0&&a.push(`${t} ${1===t?"learning":"learnings"} added`),n>0&&a.push(`${n} ${1===n?"learning":"learnings"} updated`),s>0&&a.push(`${s} ${1===s?"learning":"learnings"} unchanged`),a.length>0?console.log(J.green(`✓ Pushed taste to ${e} (${a.join(", ")})`)):console.log(J.green(`✓ Pushed taste to ${e}`)),(t>0||n>0)&&s>0&&(o=!0)}else console.log(J.green(`✓ Pushed taste to ${e}`));else console.log(J.green("✓ Pushed taste to remote"))}else if(1===r.bucketsPushed.length){const e=r.bucketsPushed[0],t=r.filePaths?.[e];if(n.overwrite)n.remote&&t?console.log(J.green(`✓ Replaced '${e}' taste package in ${t}`)):(console.log(J.green(`✓ Replaced '${e}' taste package in global`)),t&&console.log(J.gray(` Path: ${t}`)));else if(r.mergeDetails?.[e]){const s=r.mergeDetails[e],a=[];s.added>0&&a.push(`${s.added} ${1===s.added?"learning":"learnings"} added`),s.updated>0&&a.push(`${s.updated} ${1===s.updated?"learning":"learnings"} updated`),s.unchanged>0&&a.push(`${s.unchanged} ${1===s.unchanged?"learning":"learnings"} unchanged`),n.remote&&t?console.log(J.green(`✓ Pushed '${e}' taste package to ${t} (${a.join(", ")})`)):(console.log(J.green(`✓ Pushed '${e}' taste package to global (${a.join(", ")})`)),t&&console.log(J.gray(` Path: ${t}`))),(s.added>0||s.updated>0)&&s.unchanged>0&&(o=!0)}else n.remote&&t?console.log(J.green(`✓ Pushed '${e}' taste package to ${t}`)):(console.log(J.green(`✓ Pushed '${e}' taste package to global`)),t&&console.log(J.gray(` Path: ${t}`)))}else if(r.bucketsPushed.length>0){const e=n.remote?"remote":"global";if(console.log(J.green(`✓ Pushed ${r.bucketsPushed.length} taste packages (${r.bucketsPushed.join(", ")}) to ${e}`)),!n.overwrite&&r.mergeDetails)for(const e of Object.values(r.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){o=!0;break}}o&&console.log(J.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("pull").argument("[package]","Package name (optional if using --all)").option("-g, --global","Pull from global").addOption(new Ee("--local","Use local server").hideHelp()).option("--remote","Pull from remote").option("--all","Pull all packages").option("--overwrite","Overwrite local without prompting (default: interactive merge)").addOption(new Ee("--staging","Use staging environment").hideHelp()).description("Pull packages from storage to project (prompts on conflicts)").action(async(e,n)=>{try{let r,o;if(n.global||n.remote||(n.remote=!0),n.global&&n.remote&&(console.error(J.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),n.remote&&n.all&&(console.error(J.red("Error: The --all flag is not supported for remote pull")),console.error(J.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),n.remote&&!e&&(console.error(J.red("Error: Please provide both namespace and package name")),process.exit(1)),n.remote&&e&&!e.includes("/")&&(console.error(J.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),e||n.all||(console.error(J.red("Error: Please specify a package name or use --all flag")),console.error(J.gray("Usage: cmd taste pull <namespace>/<package> (remote by default)")),console.error(J.gray(" cmd taste pull <package> -g (from global)")),console.error(J.gray(" cmd taste pull --all -g (all from global)")),process.exit(1)),e&&n.all&&(console.error(J.red("Error: Cannot use both package name and --all flag")),process.exit(1)),n.remote){e.includes("/")||(console.error(J.red("Error: Package name must include namespace")),console.error(J.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1));const[s,a]=e.split("/");s&&a||(console.error(J.red("Error: Invalid namespace/package format")),console.error(J.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),o=s,r=await t.pullRemote({namespace:o,packageName:a,overwrite:n.overwrite})}else{const o="local-global",s=n.all?[]:[e];r=await t.pull({buckets:s,source:o,overwrite:n.overwrite})}const s=n.remote?o?`${o}`:"remote":"global";if(!r.success){for(const e of r.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(J.red(`Error: ${t}`))}process.exit(1)}if(r.skipped&&r.skipped.length>0)for(const e of r.skipped)console.log(J.yellow(`⊘ Skipped '${e}' - kept local version`));let a=!1;if(1===r.bucketsPulled.length){const e=r.bucketsPulled[0],t=r.filePaths?.[e];if(n.overwrite)console.log(J.green(`✓ Replaced '${e}' taste package in project`)),t&&console.log(J.gray(` Saved to: ${t}`));else if(r.mergeDetails?.[e]){const n=r.mergeDetails[e],o=[];n.added>0&&o.push(`${n.added} ${1===n.added?"learning":"learnings"} added`),n.updated>0&&o.push(`${n.updated} ${1===n.updated?"learning":"learnings"} updated`),n.unchanged>0&&o.push(`${n.unchanged} ${1===n.unchanged?"learning":"learnings"} unchanged`),console.log(J.green(`✓ Pulled '${e}' taste package from ${s} (${o.join(", ")})`)),t&&console.log(J.gray(` Saved to: ${t}`)),(n.added>0||n.updated>0)&&n.unchanged>0&&(a=!0)}else console.log(J.green(`✓ Pulled '${e}' taste package from ${s}`)),t&&console.log(J.gray(` Saved to: ${t}`))}else if(r.bucketsPulled.length>0){const e=` (${r.bucketsPulled.join(", ")})`;if(console.log(J.green(`✓ Pulled ${r.bucketsPulled.length} taste packages${e} from ${s}`)),!n.overwrite&&r.mergeDetails)for(const e of Object.values(r.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){a=!0;break}}a&&console.log(J.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("list").option("-g, --global","List global packages").addOption(new Ee("--local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ee("--staging","Use staging environment").hideHelp()).description("List available packages").action(async e=>{try{let n,r;e.global&&e.remote&&(console.error(J.red("Error: Cannot specify both --global and --remote flags")),process.exit(1)),e.remote?(n="remote-project",r="remote"):e.global?(n="local-global",r="global"):(n="local-project",r="project");const o=await t.list({location:n});if(0===o.length)return void console.log(J.yellow(`No taste packages found in ${r}`));let s;console.log(J.hex("#E4CCFF").bold("\nTaste Packages")),s="remote-project"===n?"Stored in your commandcode.ai account":"local-global"===n?"Stored globally in ~/.commandcode/taste":"Stored locally in .commandcode/taste",console.log(J.dim(s+"\n"));let a=0;const i=__name(e=>{let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ★${e.starCount}`.length),e.downloadCount&&(t+=` ↓${e.downloadCount}`.length),t},"getDisplayLength"),c=Math.max(...o.map(i));for(const e of o){a+=e.learningCount;const t=getTimeAgo(e.lastUpdated),n=" ".repeat(c-i(e)+2),r=J.white(e.category),o=e.isPublic?J.green(" [public]"):"",s=e.isPublic&&e.starCount?J.yellow(` ★${e.starCount}`):"",l=e.downloadCount?J.gray(` ↓${e.downloadCount}`):"";console.log(` ${r}${o}${s}${l}${n}${J.dim.gray(`(${e.learningCount} learnings, updated ${t})`)}`)}console.log(J.dim(`\nTotal: ${o.length} packages, ${a} learnings\n`))}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.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,n)=>{try{e||n.all||(console.error(J.red("Error: Please specify a package name or use --all flag")),console.error(J.gray("Usage: cmd taste lint <package>")),console.error(J.gray(" cmd taste lint --all")),process.exit(1)),e&&n.all&&(console.error(J.red("Error: Cannot use both package name and --all flag")),process.exit(1));const r=await t.lint({packages:e?[e]:[],target:n.global?"local-global":"local-project"});if(r.errors.length>0){for(const e of r.errors)console.error(J.red(`Error: ${e.error}`));process.exit(1)}for(const e of r.filesLinted)console.log(e.formatted);if(r.filesLinted.length>1)if(console.log(""),0===r.totalErrors&&0===r.totalWarnings)console.log(J.green(`✓ All ${r.filesLinted.length} taste files are valid`));else{const e=[];r.totalErrors>0&&e.push(J.red(`${r.totalErrors} error${r.totalErrors>1?"s":""}`)),r.totalWarnings>0&&e.push(J.yellow(`${r.totalWarnings} warning${r.totalWarnings>1?"s":""}`)),console.log(`Summary: ${e.join(", ")} across ${r.filesLinted.length} files`)}r.success||process.exit(1)}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("open").argument("<package>","Package name to open").option("-g, --global","Open from global").description("Open a package in your editor").action(async(e,n)=>{try{const r=n.global?"local-global":"local-project",o=await t.open({package:e,target:r});o.success||(console.error(J.red(o.error)),process.exit(1)),console.log(J.green(`✓ Opened '${e}' taste package from ${n.global?"global":"project"}`))}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}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 formatVersion(e,t,n=!1){const r=n?Q.bold(Q.green(t)):Q.white(t);return`${Q.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${Q.bold(Q.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(Q.dim(`Run ${Q.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(Q.dim("Try updating manually:")),console.log(Q.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(Q.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=xe("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.stop(),console.log(""),console.log(`${Q.green(pe.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${Q.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=xe("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.text=`Updating ${t.currentVersion} ${pe.arrowRight} ${t.latestVersion}...`,(await performAutoUpdate({silent:!0,updateInfo:t})).success||(e.fail("Update failed"),trackError({error:sanitizeErrorForTelemetry({error:new Error("Update failed"),label:"cli_update_failed"}),context:{component:_n.UPDATE_COMMAND,heading:"CLI update failed","update.current_version":t.currentVersion,"update.target_version":t.latestVersion}}),showManualUpdateHint(t.latestVersion),await shutdownTelemetry(),process.exit(1)),e.succeed(`Updated to v${t.latestVersion}`),showUpdateSuccessHint()):e.succeed(`Up to date ${Q.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}wt(),wt(),__name(promptNamespaceSelection,"promptNamespaceSelection"),wt(),Ct(),__name(fetchUserNamespaces,"fetchUserNamespaces"),__name(createTasteCommand,"createTasteCommand"),__name(getTimeAgo,"getTimeAgo"),wt(),Ct(),rr(),__name(formatVersion,"formatVersion"),__name(showVersionDetails,"showVersionDetails"),__name(showUpdateSuccessHint,"showUpdateSuccessHint"),__name(showManualUpdateHint,"showManualUpdateHint"),__name(showCheckFailure,"showCheckFailure"),__name(checkAction,"checkAction"),__name(performUpdateAction,"performUpdateAction"),__name(updateAction,"updateAction");var _l=new ye("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);wt();var Ml=__name((e,t)=>`${pe.info} ${e}: ${Q.cyan(t)}`,"formatInfoLine"),Ul=__name(e=>Q.bold(`${e}:`),"formatSectionHeader"),jl=__name(e=>Q.red(e),"formatError"),Bl=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),Wl=__name(e=>["",Ul("User Information"),Ml("Name",e.name),Ml("Email",e.email),Ml("Username",e.userName)],"buildUserOutput"),Hl=__name(e=>["",Ul("Organization"),Ml("Name",e.name),Ml("Login",e.login)],"buildOrgOutput"),zl=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),Gl=__name((e,t)=>{zl(Wl(e)),t&&zl(Hl(t)),console.log("")},"displayUserInfo"),ql=__name(e=>null!==e&&e.length>0,"validateApiKey"),Vl=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=xe("Fetching user information...").start();try{const t=await getAuthKey();ql(t)||(e.fail(jl('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();Vl(n)||(e.fail(jl("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),Gl(n.user,n.org)}catch(t){e.fail(jl(`Error: ${Bl(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var Kl=new ye("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var Jl=createProgram();Jl.action(interactiveModeAction),Jl.addCommand(Il),Jl.addCommand(Rl),Jl.addCommand(Kl),Jl.addCommand(_l),Jl.addCommand(xl),Jl.addCommand(createTasteCommand()),Jl.addCommand($l),Jl.addCommand(wr),Jl.addCommand(vr),Jl.addCommand(Rr),setupCommanderHooks(Jl),Jl.parse();
2
+ import*as e from"path";import t,{relative as n,dirname as r,join as o,isAbsolute as s,resolve as a,basename as i}from"path";import{fileURLToPath as c,pathToFileURL as l}from"url";import d,{z as u}from"zod";import*as m from"os";import g,{tmpdir as p}from"os";import*as h from"fs";import f,{existsSync as y,readFileSync as E,promises as w,constants as b,readdirSync as S,statSync as k,createReadStream as C}from"fs";import{execSync as v,exec as T,spawn as A}from"child_process";import*as P from"fs/promises";import x,{mkdir as I,writeFile as D,readFile as R,unlink as $}from"fs/promises";import*as F from"crypto";import N,{randomUUID as O}from"crypto";import L,{useState as _,useRef as M,useEffect as U,useCallback as j,useMemo as B}from"react";import{Box as z,Text as W,Static as H,render as G,useStdout as q,useInput as V,useApp as K}from"ink";import J from"chalk";import Y from"strip-ansi";import Q from"picocolors";import Z from"sharp";import X from"open";import ee from"@opentelemetry/sdk-node";import te from"@opentelemetry/exporter-trace-otlp-http";import ne from"@opentelemetry/resources";import re from"@opentelemetry/semantic-conventions";import oe from"@opentelemetry/sdk-trace-node";import{trace as se,SpanStatusCode as ae,context as ie}from"@opentelemetry/api";import{v4 as ce}from"uuid";import*as le from"net";import de from"net";import{promisify as ue}from"util";import"dotenv/config";import me from"dedent";import ge from"log-symbols";import pe,{mainSymbols as he}from"figures";import fe from"readline/promises";import{Command as ye,Option as Ee}from"commander";import*as we from"@clack/prompts";import{cancel as be,select as Se,isCancel as ke,note as Ce,confirm as ve,password as Te}from"@clack/prompts";import Ae from"ink-spinner";import*as Pe from"http";import xe from"ora";import Ie from"@crosscopy/clipboard";import De from"gray-matter";import{minimatch as Re}from"minimatch";import{glob as $e}from"glob";import{quote as Fe}from"shell-quote";import{MessageStream as Ne}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import Oe from"@sindresorhus/slugify";import{EventEmitter as Le}from"events";import _e from"strip-json-comments";import*as Me from"readline";import Ue from"ink-select-input";import je from"ignore";import Be from"ink-gradient";import{Marked as ze}from"marked";import We from"marked-terminal";import*as He from"diff";import Ge from"semver";import qe from"open-editor";import Ve from"ink-text-input";import*as Ke from"process";var Je,Ye,Qe,Ze,Xe,et,tt,nt,rt,ot,st,at,it,ct,lt,dt,ut,mt,gt,pt,ht,ft,yt,Et=Object.defineProperty,wt=Object.getOwnPropertyNames,__name=(e,t)=>Et(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[wt(e)[0]])(e=0)),t},bt=__esm({"../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/esm_shims.js"(){}}),St=__esm({"src/utils/telemetry/constants.ts"(){bt(),Je="https://api.axiom.co/v1/traces",Ye="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",Qe="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",Ze="xaat-add69148-8f73-4833-921d-bc843285c95f",Xe="command-code-cli",et="command_code_cli_tracing",tt=["apikey","api_key","api-key","token","secret","authorization","auth","password","passwd","credential","auth_key","authkey","access_token","access-token","refresh_token","refresh-token","client_secret","clientsecret","private_key","privatekey","bearer","key"],nt=["content","body"],rt=200,ot=1e3}});function getStudioAuthUrl(e){return"local"===e?"http://localhost:3000/settings/api":"staging"===e?"https://staging.commandcode.ai/settings/api":"https://commandcode.ai/settings/api"}var kt,Ct,vt=__esm({"../shared/src/constants.ts"(){bt(),at="--xco",it={INTERNAL_TEAM_FLAG_HEADER:`x-${(st="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage"},ct={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"},DEVREL_THREAD:{CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",DATA:"/alpha/devrel-thread/data",UPDATE:"/alpha/devrel-thread/update"},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",DELETE:"/beta/taste/packages/:namespace/:packageName"}}},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"},PROFILE:{GET:"/internal/profile/:login",PACKAGES:"/internal/profile/:login/packages",PACKAGE_GET:"/internal/profile/:login/packages/:packageName",PACKAGE_DOWNLOAD:"/internal/profile/:login/packages/:packageName/download",FOLLOWERS:"/internal/profile/:login/followers",FOLLOWING:"/internal/profile/:login/following"},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"},FOLLOW:"/internal/orgs/:orgId/follow",FOLLOWERS:"/internal/orgs/:orgId/followers"},USER:{SETTINGS:"/internal/user/settings",AVATAR:"/internal/user/avatar",FOLLOW:"/internal/users/:userId/follow",FOLLOWERS:"/internal/users/:userId/followers",FOLLOWING:"/internal/users/:userId/following"},USAGE:{LIST:"/internal/usage",SUMMARY:"/internal/usage/summary"},TASTE:{PACKAGES:{LIST:"/internal/taste/packages",BATCH:"/internal/taste/packages",GET:"/internal/taste/packages/:namespace/:packageName",FILES:"/internal/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/internal/taste/packages/:namespace/:packageName/download",DELETE:"/internal/taste/packages/:namespace/:packageName",UPDATE:"/internal/taste/packages/:namespace/:packageName/update",STAR:"/internal/taste/packages/:namespace/:packageName/star",PIN:"/internal/taste/packages/:namespace/:packageName/pin"}}}},lt={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")},PACKAGES:{FILES:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+/download")}},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_-]+"),FOLLOW:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/followers")},USER:{FOLLOW:new RegExp("/internal/users/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/users/[a-zA-Z0-9-]+/followers"),FOLLOWING:new RegExp("/internal/users/[a-zA-Z0-9-]+/following")},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"),UPDATE:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/update"),STAR:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/star"),PIN:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/pin")}}}},Object.values(lt.ALPHA.TASTE),Object.values(lt.BETA.TASTE_PACKAGES),ct.ALPHA.GENERATE,ct.ALPHA.AGENT.GENERATE,ct.ALPHA.WHOAMI,ct.ALPHA.NAMESPACES,ct.ALPHA.SHARE.CREATE,ct.ALPHA.SHARE.DELETE,ct.ALPHA.SHARE.APPEND,ct.ALPHA.DEVREL_THREAD.CREATE,ct.ALPHA.DEVREL_THREAD.DELETE,ct.ALPHA.DEVREL_THREAD.UPDATE,ct.ALPHA.TASTE.LEARN,ct.ALPHA.TASTE.DELETE,ct.ALPHA.TASTE.GET,ct.ALPHA.TASTE.UPDATE,Object.values(ct.BETA.TASTE.PACKAGES),ct.INTERNAL.ADMIN.USERS,ct.INTERNAL.ADMIN.ORGS,ct.INTERNAL.ADMIN.ENTITY_TYPE,ct.INTERNAL.USER.AVATAR,ct.INTERNAL.USER.SETTINGS,ct.INTERNAL.API_KEYS.LIST,ct.INTERNAL.API_KEYS.CREATE,ct.INTERNAL.API_KEYS.DELETE,ct.INTERNAL.USAGE.LIST,ct.INTERNAL.USAGE.SUMMARY,ct.INTERNAL.ADMIN.GRANT_CREDITS,ct.INTERNAL.ADMIN.GRANT_ORG_CREDITS,ct.INTERNAL.BILLING.CREDITS.GET,ct.INTERNAL.BILLING.CUSTOMERS.GET,ct.INTERNAL.BILLING.CUSTOMERS.UPSERT,ct.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,ct.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,ct.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,ct.INTERNAL.BILLING.CUSTOMERS.INVOICES,ct.INTERNAL.BILLING.SUBSCRIPTIONS.GET,ct.INTERNAL.ORGS.LIST,ct.INTERNAL.ORGS.GET,ct.INTERNAL.ORGS.CREATE,ct.INTERNAL.ORGS.UPDATE,ct.INTERNAL.ORGS.DELETE,ct.INTERNAL.ORGS.MEMBERS.LIST,ct.INTERNAL.ORGS.MEMBERS.ADD,ct.INTERNAL.ORGS.MEMBERS.UPDATE,ct.INTERNAL.ORGS.MEMBERS.REMOVE,ct.INTERNAL.ORGS.INVITATIONS.LIST,ct.INTERNAL.ORGS.INVITATIONS.SEND,ct.INTERNAL.ORGS.INVITATIONS.ACCEPT,ct.INTERNAL.ORGS.INVITATIONS.CANCEL,ct.INTERNAL.TASTE.PACKAGES.LIST,Object.values(lt.INTERNAL.ORGS),Object.values(lt.INTERNAL.USER),Object.values(lt.INTERNAL.TASTE.PACKAGES),dt={INTERNAL:{PROFILE:{GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+"),PACKAGES:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages"),FOLLOWING:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/following"),FOLLOWERS:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/followers"),PACKAGE_GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+"),PACKAGE_DOWNLOAD:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+/download")}}},Object.values(dt.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl"),ut={ANTHROPIC:"anthropic"},mt="anthropic:claude-haiku-4-5-20251001",d.enum(["owner","admin","member"]),gt={LEARN_TASTE:"learn-taste",TASTE:"taste",TERMINAL_SETUP:"terminal-setup"},(pt={SONNET_4_5:{id:"claude-sonnet-4-5-20250929",label:"Default",name:"Sonnet 4.5",description:"recommended"},OPUS_4_5:{id:"claude-opus-4-5-20251101",label:"Opus 4.5",name:"Opus 4.5",description:""},OPUS_4_6:{id:"claude-opus-4-6",label:"Opus 4.6",name:"Opus 4.6",description:""}}).SONNET_4_5.id,pt.OPUS_4_5.id,pt.OPUS_4_6.id,ht=pt.SONNET_4_5.id,new Set([].map(e=>e.toLowerCase())),ft=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],yt={TIER_1_THRESHOLD:.5,TIER_2_THRESHOLD:.8,TIER_3_THRESHOLD:.9,TIER_1_KEEP_COUNT:20,TIER_2_KEEP_COUNT:10,KEEP_RECENT_TOKENS:3e4}}}),Tt=__esm({"src/utils/env.ts"(){bt(),kt=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),Ct=__name(()=>{const e=kt();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag")}});function getAuthDir(){return t.join(g.homedir(),".commandcode")}function getAuthFile(e){const n=e??kt(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??kt(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var At,Pt,xt=__esm({"src/utils/auth/auth-paths.ts"(){bt(),vt(),Tt(),__name(getAuthDir,"getAuthDir"),__name(getAuthFile,"getAuthFile"),__name(getConfigFile,"getConfigFile")}});function normalizePathForComparison(e){const n=t.normalize(e);return"win32"===process.platform?n.toLowerCase():n}function areSamePath(e,t){return normalizePathForComparison(e)===normalizePathForComparison(t)}function getCanonicalPath(e){try{return f.realpathSync(e)}catch(n){const r=n.code;return"ENOENT"!==r&&console.error(`Warning: Could not resolve canonical path for "${e}" (${r}). Path comparison may be less reliable.`),t.normalize(e)}}function canonicalizeForLookup(e){try{let n=t.resolve(e);const r=[];for(;!f.existsSync(n);){const o=t.dirname(n);if(o===n)return t.normalize(e);r.unshift(t.basename(n)),n=o}return t.join(getCanonicalPath(n),...r)}catch{return t.normalize(e)}}function formatDirectoryForDisplay(e){const n=canonicalizeForLookup(t.normalize(e)),r=getCanonicalPath(process.cwd()),o=g.homedir();if(isPathInDirectory(n,r)){const e=t.relative(r,n);return e?`./${e}`:"."}if(o&&isPathInDirectory(n,o)){const e=t.relative(o,n);return e?`~/${e}`:"~"}return n}function isPathInDirectory(e,n){const r=normalizePathForComparison(e),o=normalizePathForComparison(n),s=o.endsWith(t.sep)?o:o+t.sep;return r===o||r.startsWith(s)}function findSensitiveDirectoryConflict(e){const n=[t.normalize(e),getCanonicalPath(e)];for(const e of At){const r=[t.normalize(e),getCanonicalPath(e)];for(const e of n)for(const t of r)if(isPathInDirectory(e,t)||isPathInDirectory(t,e))return t}return null}function resolveDirectoryPath(e){let n=e.trim();return n.startsWith("~")&&(n=t.join(g.homedir(),n.slice(1))),t.isAbsolute(n)||(n=t.resolve(process.cwd(),n)),t.normalize(n)}function createSkippedResult(e){const{inputPath:t,absolutePath:n,code:r}=e,o=formatDirectoryForDisplay(n);return{status:"skipped",inputPath:t,absolutePath:n,displayPath:o,code:r,message:"ALREADY_IN_WORKSPACE"===r?`${o} is already accessible from the current workspace`:`${o} is already added`}}function createErrorResult(e){const{inputPath:t,code:n,message:r}=e;return{status:"error",inputPath:t,code:n,message:r}}function addDirectory(e){const t=e.trim();if(!t)return createErrorResult({inputPath:e,code:"EMPTY_PATH",message:"Directory path cannot be empty"});const n=resolveDirectoryPath(e);let r,o;try{r=f.statSync(n)}catch(n){return"ENOENT"===n.code?createErrorResult({inputPath:e,code:"NOT_FOUND",message:`Directory does not exist: ${t}`}):createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}if(!r.isDirectory())return createErrorResult({inputPath:e,code:"NOT_A_DIRECTORY",message:`${formatDirectoryForDisplay(n)} is not a directory`});try{f.accessSync(n,f.constants.R_OK),o=getCanonicalPath(n)}catch{return createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}const s=findSensitiveDirectoryConflict(o);if(s)return createErrorResult({inputPath:e,code:"SENSITIVE_DIRECTORY",message:`Cannot add ${formatDirectoryForDisplay(o)} because it overlaps sensitive path ${formatDirectoryForDisplay(s)}`});const a=getCanonicalPath(process.cwd());return isPathInDirectory(o,a)?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_IN_WORKSPACE"}):Pt.some(e=>isPathInDirectory(o,e)||isPathInDirectory(e,o))?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_ADDED"}):(Pt.push(o),{status:"added",inputPath:e,absolutePath:o,displayPath:formatDirectoryForDisplay(o)})}function getAdditionalDirectories(){return[...Pt]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Pt.findIndex(e=>areSamePath(t,e));return-1!==n&&(Pt.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Pt.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t)}var It=__esm({"src/utils/additional-dirs.ts"(){bt(),At=new Set(["/etc","/root","/proc","/sys","/dev",t.join(g.homedir(),".ssh"),t.join(g.homedir(),".gnupg"),t.join(g.homedir(),".aws")]),Pt=[],__name(normalizePathForComparison,"normalizePathForComparison"),__name(areSamePath,"areSamePath"),__name(getCanonicalPath,"getCanonicalPath"),__name(canonicalizeForLookup,"canonicalizeForLookup"),__name(formatDirectoryForDisplay,"formatDirectoryForDisplay"),__name(isPathInDirectory,"isPathInDirectory"),__name(findSensitiveDirectoryConflict,"findSensitiveDirectoryConflict"),__name(resolveDirectoryPath,"resolveDirectoryPath"),__name(createSkippedResult,"createSkippedResult"),__name(createErrorResult,"createErrorResult"),__name(addDirectory,"addDirectory"),__name(getAdditionalDirectories,"getAdditionalDirectories"),__name(removeAdditionalDirectory,"removeAdditionalDirectory"),__name(isPathInAdditionalDirs,"isPathInAdditionalDirs"),__name(isPathInWorkspace,"isPathInWorkspace")}});function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${g.platform()}-${g.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return f.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 getAccessibleDirectoryStructure(){return[...getRootDirectoryStructure(),...getAdditionalDirectories().map(e=>`scope:${formatDirectoryForDisplay(e)}`)]}function isGitRepository(){try{return v("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return v("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){try{const e=v("git branch -r",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]});return e.includes("origin/main")?"main":e.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=v("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),n=t.filter(e=>e.startsWith(" M")).length,r=t.filter(e=>e.startsWith("A ")).length,o=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,a=[];return n>0&&a.push(`M ${n}`),r>0&&a.push(`A ${r}`),o>0&&a.push(`D ${o}`),s>0&&a.push(`?? ${s}`),a.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=v("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository(),t=getAdditionalDirectories();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getAccessibleDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[],...t.length>0?{additionalDirectories:t}:{}}}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("ghostty"===t)return{name:"Ghostty",type:"ghostty",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}var Dt,Rt,$t,Ft,Nt,Ot,Lt=__esm({"src/utils/environment.ts"(){bt(),It(),__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(getAccessibleDirectoryStructure,"getAccessibleDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext"),__name(detectTerminal,"detectTerminal"),__name(getIsTerminalIterm2,"getIsTerminalIterm2")}}),_t=__esm({"src/auth/index.ts"(){bt(),vt(),Tt(),(e=>{e.OAuth=u.object({type:u.literal("oauth"),refresh:u.string(),access:u.string(),expires:u.number()}),e.ApiKey=u.object({type:u.literal("api"),key:u.string()}),e.Info=u.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const n=__name(()=>t.join(g.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=kt(),r="local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json";return t.join(n(),r)},"getAuthFile");async function get(e){try{const t=await x.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await x.mkdir(o,{recursive:!0});let a={};try{const e=await x.readFile(s,"utf-8");a=JSON.parse(e)}catch{}a[e]=t,await x.writeFile(s,JSON.stringify(a,null,2)),await x.chmod(s,384)}async function remove(e){const t=r();try{const n=await x.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await x.unlink(t):(await x.writeFile(t,JSON.stringify(r,null,2)),await x.chmod(t,384))}catch{}}async function list2(){try{const e=await x.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")})(Dt||(Dt={}))}}),Mt=__esm({"src/utils/constants.ts"(){bt(),vt(),Rt="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing",$t='OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.',Ft=">"}}),Ut=__esm({"src/auth/anthropic.ts"(){bt(),_t(),Mt(),ir(),(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 N.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return N.createHash("sha256").update(e).digest("base64url")}function generateState(){return N.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),o=generateState();return{url:`https://claude.ai/oauth/authorize?${new URLSearchParams({code:"true",client_id:t,response_type:"code",redirect_uri:r,scope:"org:create_api_key user:profile user:inference",code_challenge:n,code_challenge_method:"S256",state:o}).toString()}`,verifier:e,state:o}}async function exchangeCodeForTokens(e,o,s){const a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:s})});if(!a.ok){const e=await a.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:Bn.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const i=await a.json();await Dt.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 Dt.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 trackError({error:sanitizeErrorForTelemetry({error:new Error("OAuth token refresh failed"),label:"token_refresh_failed"}),context:{component:Bn.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await Dt.remove("anthropic");const o=await r.json();return await Dt.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 trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:Bn.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await Dt.remove("anthropic")}}}async function getValidAccessToken(){const e=await Dt.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")})(Nt||(Nt={}))}});function isWordBoundary(e){return!e||0===e.length||Ot.test(e)}function findPreviousWordBoundary(e,t){if(!e||t<=0)return 0;let n=Math.min(t,e.length);for(;n>0&&isWordBoundary(e[n-1]||"");)n--;for(;n>0&&!isWordBoundary(e[n-1]||"");)n--;return n}function findNextWordBoundary(e,t){if(!e)return 0;if(t>=e.length)return e.length;let n=Math.max(0,t);for(;n<e.length&&isWordBoundary(e[n]||"");)n++;for(;n<e.length&&!isWordBoundary(e[n]||"");)n++;return n}function deleteWordBackwards(e,t){if(!e||t<=0)return{text:e||"",cursor:0};const n=findPreviousWordBoundary(e,t);return{text:e.slice(0,n)+e.slice(t),cursor:n}}function clampCursor(e,t){return Math.max(0,Math.min(e,t))}function findLineStart(e,t){if(!e||t<=0)return 0;for(let n=Math.min(t,e.length)-1;n>=0;n--)if("\n"===e[n])return n+1;return 0}function findLineEnd(e,t){if(!e)return 0;if(t>=e.length)return e.length;for(let n=Math.max(0,t);n<e.length;n++)if("\n"===e[n])return n;return e.length}function moveCursorUp(e,t){if(!e)return 0;const n=findLineStart(e,t);if(0===n)return t;const r=t-n,o=n-1,s=findLineStart(e,o),a=o-s;return s+Math.min(r,a)}function moveCursorDown(e,t){if(!e)return 0;const n=findLineStart(e,t),r=findLineEnd(e,t);if(r===e.length)return t;const o=t-n,s=r+1,a=findLineEnd(e,s)-s;return s+Math.min(o,a)}function insertTextAt(e,t,n){const r=e||"",o=clampCursor(t,r.length);return{text:r.slice(0,o)+n+r.slice(o),cursor:o+n.length}}function deleteCharBefore(e,t){return!e||t<=0?{text:e||"",cursor:0}:{text:e.slice(0,t-1)+e.slice(t),cursor:t-1}}function deleteCharAt(e,t){return!e||t>=e.length?{text:e||"",cursor:t}:{text:e.slice(0,t)+e.slice(t+1),cursor:t}}var jt,Bt,zt,Wt,Ht,Gt,qt,Vt,Kt,Jt,Yt,Qt=__esm({"src/utils/text-navigation.ts"(){bt(),Ot=/\s|[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/,__name(isWordBoundary,"isWordBoundary"),__name(findPreviousWordBoundary,"findPreviousWordBoundary"),__name(findNextWordBoundary,"findNextWordBoundary"),__name(deleteWordBackwards,"deleteWordBackwards"),__name(clampCursor,"clampCursor"),__name(findLineStart,"findLineStart"),__name(findLineEnd,"findLineEnd"),__name(moveCursorUp,"moveCursorUp"),__name(moveCursorDown,"moveCursorDown"),__name(insertTextAt,"insertTextAt"),__name(deleteCharBefore,"deleteCharBefore"),__name(deleteCharAt,"deleteCharAt")}});function isWordLeftSequence(e){return!!jt.has(e)||!!Jt.test(e)}function isWordRightSequence(e){return!!Bt.has(e)||!!Yt.test(e)}function isHomeSequence(e){return zt.has(e)}function isEndSequence(e){return Wt.has(e)}function isForwardDeleteSequence(e){return Ht.has(e)}function isDeleteWordSequence(e){return Gt.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===qt.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===qt.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===qt.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===qt.CTRL_U}function isAltP(e){return Kt.has(e)}function isCtrlKey({inputChar:e,key:t,letter:n,ctrlCode:r}){return!(!t.ctrl||e.toLowerCase()!==n.toLowerCase())||void 0!==r&&e.charCodeAt(0)===r}var Zt=__esm({"src/utils/keyboard-sequences.ts"(){bt(),jt=new Set(["","b","","",""]),Bt=new Set(["","f","","",""]),zt=new Set(["","[1~","[7~","OH"]),Wt=new Set(["","[4~","[8~","OF"]),Ht=new Set(["[3~"]),Gt=new Set(["",""]),qt={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},Vt={ALT_P:112,ALT_P_NO_META:960},Kt=new Set([String.fromCharCode(27,Vt.ALT_P),String.fromCharCode(Vt.ALT_P_NO_META),""]),Jt=/^\x1b\[1;[359]D$/,Yt=/^\x1b\[1;[359]C$/,__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(isAltP,"isAltP"),__name(isCtrlKey,"isCtrlKey")}});function processWordLeft(e,t){return{value:e,cursor:findPreviousWordBoundary(e,t),handled:!0}}function processWordRight(e,t){return{value:e,cursor:findNextWordBoundary(e,t),handled:!0}}function processLineStart(e,t){return{value:e,cursor:findLineStart(e,t),handled:!0}}function processLineEnd(e,t){return{value:e,cursor:findLineEnd(e,t),handled:!0}}function processDeleteWord(e,t){const n=deleteWordBackwards(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processDeleteToEnd(e,t){const n=findLineEnd(e,t);return{value:e.slice(0,t)+e.slice(n),cursor:t,handled:!0}}function processDeleteToStart(e,t){const n=findLineStart(e,t);return{value:e.slice(0,n)+e.slice(t),cursor:n,handled:!0}}function processForwardDelete(e,t){const n=deleteCharAt(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processBackspace(e,t){const n=deleteCharBefore(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processCursorLeft(e,t,n){return n?t<=0?{value:e,cursor:t,handled:!0}:{value:e,cursor:t-1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorRight(e,t,n){return n?t>=e.length?{value:e,cursor:t,handled:!0}:{value:e,cursor:t+1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorUp(e,t,n){return n?{value:e,cursor:moveCursorUp(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorDown(e,t,n){return n?{value:e,cursor:moveCursorDown(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCharacterInput(e,t,n){const r=n.replace(/[\x00-\x1F\x7F]|\x1b.*/g,"");if(0===r.length)return{value:e,cursor:t,handled:!1};const o=insertTextAt(e,t,r);return{value:o.text,cursor:o.cursor,handled:!0}}function processRawInput(e,t,n){return isWordLeftSequence(e)?processWordLeft(t,n):isWordRightSequence(e)?processWordRight(t,n):isHomeSequence(e)?processLineStart(t,n):isEndSequence(e)?processLineEnd(t,n):isCtrlA(e)?processLineStart(t,n):isCtrlE(e)?processLineEnd(t,n):isDeleteWordSequence(e)?processDeleteWord(t,n):isCtrlK(e)?processDeleteToEnd(t,n):isCtrlU(e)?processDeleteToStart(t,n):isForwardDeleteSequence(e)?processForwardDelete(t,n):{value:t,cursor:n,handled:!1}}function isIgnoredKey(e,t){return!(!t.ctrl||"c"!==e)||!!t.tab||!(!t.shift||!t.tab)}function processInkInput(e,t,n,r,o){const s=t;return s.meta&&t.leftArrow?processLineStart(n,r):s.meta&&t.rightArrow?processLineEnd(n,r):s.meta&&"b"===e?processWordLeft(n,r):s.meta&&"f"===e?processWordRight(n,r):t.ctrl&&"a"===e?processLineStart(n,r):t.ctrl&&"e"===e?processLineEnd(n,r):t.ctrl&&"w"===e?processDeleteWord(n,r):t.ctrl&&"k"===e?processDeleteToEnd(n,r):t.ctrl&&"u"===e?processDeleteToStart(n,r):t.leftArrow?processCursorLeft(n,r,o):t.rightArrow?processCursorRight(n,r,o):t.upArrow?processCursorUp(n,r,o):t.downArrow?processCursorDown(n,r,o):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!s.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}var Xt,en,tn,nn=__esm({"src/components/text/input-handlers.ts"(){bt(),Qt(),Zt(),__name(processWordLeft,"processWordLeft"),__name(processWordRight,"processWordRight"),__name(processLineStart,"processLineStart"),__name(processLineEnd,"processLineEnd"),__name(processDeleteWord,"processDeleteWord"),__name(processDeleteToEnd,"processDeleteToEnd"),__name(processDeleteToStart,"processDeleteToStart"),__name(processForwardDelete,"processForwardDelete"),__name(processBackspace,"processBackspace"),__name(processCursorLeft,"processCursorLeft"),__name(processCursorRight,"processCursorRight"),__name(processCursorUp,"processCursorUp"),__name(processCursorDown,"processCursorDown"),__name(processCharacterInput,"processCharacterInput"),__name(processRawInput,"processRawInput"),__name(isIgnoredKey,"isIgnoredKey"),__name(processInkInput,"processInkInput")}});function startEarlyInputCapture(){Xt||(Xt=!0,en=[],tn=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&en.push(t)},"earlyInputHandler"),process.stdin.on("data",tn))}function stopEarlyInputCapture(){Xt&&tn&&(process.stdin.off("data",tn),tn=null,Xt=!1)}function consumeBufferedInput(){const e=en.join("");return en=[],e}function hasBufferedInput(){return en.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("")||e.startsWith(""))}var rn=__esm({"src/utils/early-input-buffer.ts"(){bt(),Xt=!1,en=[],tn=null,__name(startEarlyInputCapture,"startEarlyInputCapture"),__name(stopEarlyInputCapture,"stopEarlyInputCapture"),__name(consumeBufferedInput,"consumeBufferedInput"),__name(hasBufferedInput,"hasBufferedInput"),__name(isControlSequenceToSkip,"isControlSequenceToSkip")}});function useCursorState({value:e,focus:t,showCursor:n}){const[r,o]=_((e||"").length),s=M(r),a=M(e);U(()=>{s.current=r},[r]),U(()=>{const i=a.current;if(a.current=e,e===i)return;if(!t)return;if(!n)return;const c=(e||"").length,l=(i||"").length;(Math.abs(c-l)>1||r>c)&&(o(c),s.current=c)},[e,t,n,r]);const i=j(e=>{o(e),s.current=e},[]);return{cursor:r,setCursor:i,cursorRef:s}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o}){const s=M(!1);U(()=>{if(!e)return;const a=process.stdin,i=__name(e=>{const s=processRawInput(e.toString(),t.current,n.current);if(!s.handled)return;o(!0);const a=clampCursor(s.cursor,s.value.length);r(s.value,a),setTimeout(()=>o(!1),0)},"handleRawInput");if(a.on("data",i),!s.current&&hasBufferedInput()){s.current=!0;const e=consumeBufferedInput();e&&i(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",i)}},[e,t,n,r,o])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){V((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void a?.(n.current);const c=processInkInput(e,i,n.current,r.current,t);if(!c.handled)return;const l=clampCursor(c.cursor,c.value.length);s(c.value,l)},{isActive:e})}function useSyncedRef(e){const t=M(e);return U(()=>{t.current=e},[e]),t}var on=__esm({"src/components/text/hooks.ts"(){bt(),Qt(),nn(),rn(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef")}});function renderPlaceholder(e,t){return t?0===e.length?J.inverse(" "):J.inverse(e[0])+J.grey(e.slice(1)):J.grey(e)}function renderValue(e,t,n){if(!n)return e;if(0===e.length)return J.inverse(" ");let r="";for(let n=0;n<e.length;n++)n===t?"\n"===e[n]?r+=J.inverse(" ")+"\n":r+=J.inverse(e[n]):r+=e[n];return t===e.length&&(r+=J.inverse(" ")),r}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(Y(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",c=0,l=!0;for(const e of a){const t=Y(e).length;c+t>(l?s:o)&&c>0&&(i+="\n"+r,c=n,l=!1),i+=e,c+=t}return i}function getDisplayValue(e,t,n,r,o){const s=r&&o;return t&&0===e.length?renderPlaceholder(t,s):renderValue(e,n,s)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}var sn=__esm({"src/components/text/render-utils.ts"(){bt(),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue")}});function createStdinUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n.current(r),t.current=r)}}function createInkUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n(r),t.current=r)}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:a,onCursorChange:i,prefix:c="",prefixColor:l}){const d=M(!1),u=useSyncedRef(e),m=useSyncedRef(s),{cursor:g,setCursor:p,cursorRef:h}=useCursorState({value:e,focus:n,showCursor:o});L.useEffect(()=>{i?.(g)},[g,i]);const f=j(createStdinUpdateHandler(p,u,m),[p,u,m]),y=j(()=>createInkUpdateHandler(p,u,s),[p,u,s])(),E=j(e=>{d.current=e},[]),w=j(()=>d.current,[]);useRawStdinHandler({focus:n,valueRef:u,cursorRef:h,onUpdate:f,setHandled:E}),useInkInputHandler({focus:n,showCursor:o,valueRef:u,cursorRef:h,isHandledByStdin:w,onUpdate:y,onSubmit:a});const{stdout:b}=q(),S=b?.columns??80,k=getMaskedValue(e,r),C=wrapWithIndent(__name(()=>{if(!c)return"";if(!l)return c;const e={white:Q.white,green:Q.green,red:Q.red,blue:Q.blue,yellow:Q.yellow,cyan:Q.cyan,magenta:Q.magenta,gray:Q.gray,grey:Q.gray}[l];return e?e(c):c},"getColoredPrefix")()+getDisplayValue(k,t,g,o,n),S,c?.length??0);return L.createElement(W,{wrap:"wrap"},C)}var an=__esm({"src/components/text/text-input.tsx"(){bt(),on(),sn(),Qt(),__name(createStdinUpdateHandler,"createStdinUpdateHandler"),__name(createInkUpdateHandler,"createInkUpdateHandler"),__name(TextInput,"TextInput")}});async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=Z(n),s=await o.metadata();if(!s.width||!s.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const a=1200;let i,c,{width:l,height:d}=s;(l>a||d>a)&&(l>d?(d=Math.round(d*a/l),l=a):(l=Math.round(l*a/d),d=a)),t.includes("png")&&s.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}}var cn=__esm({"src/utils/image-compression.ts"(){bt(),__name(compressImageForSharing,"compressImageForSharing")}});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}}var ln=__esm({"src/utils/clipboard-image.ts"(){bt(),cn(),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText")}});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,o,s=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");if(s=s.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){r=e.slice(0,t.index);const s=e.slice(t.index+t[0].length);if(n){const e=s.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(o=s.slice(0,e.index))}else o=s}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:s,textBeforePaste:r,pastedContent:o}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}var dn,un,mn,gn,pn=__esm({"src/utils/bracketed-paste.ts"(){bt(),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode")}});function getIcon(e){if(mn[e])return mn[e];const t=e.split(":")[0];return mn[t]?mn[t]:mn.default}function formatTime(e){return`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}`}function parseMessage(e){const t=e.match(/^\[([^\]]+)\]\s*(.*)/);return t?{category:t[1],text:t[2]}:{category:"",text:e}}function showStartup(){if(!gn){gn=!0;try{h.mkdirSync(dn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${un}\n════════════════════════════════════════════════════════════════\n\n`;h.appendFileSync(un,t,"utf-8")}catch{}}}function dlog(e,t){if("true"===process.env.DEBUG){showStartup();try{const n=formatTime(new Date),{category:r,text:o}=parseMessage(e);let s;if(r){s=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${o}`}else s=`${n} ${mn.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",h.appendFileSync(un,s,"utf-8")}catch{}}}function dlogSection(e){if("true"===process.env.DEBUG){showStartup();try{const t=`\n──── ${e} ${"─".repeat(Math.max(0,50-e.length))}\n`;h.appendFileSync(un,t,"utf-8")}catch{}}}var hn,fn=__esm({"src/utils/dlog.ts"(){bt(),dn=e.join(m.homedir(),".commandcode","logs"),un=e.join(dn,"command.log"),mn={Startup:">",CLI:"$",Config:"#",Auth:"@",Onboarding:"*",LearningAgent:"&",Import:"<",API:"~",Sessions:"+",Observer:"!",Flow:"^",Handler:">",Helper:"-",Codex:"+",UI:"|",Hook:"%",ObserverAPI:"~",ContextEngine:"~",Updater:"^",default:"-"},__name(getIcon,"getIcon"),__name(formatTime,"formatTime"),__name(parseMessage,"parseMessage"),gn=!1,__name(showStartup,"showStartup"),"true"===process.env.DEBUG&&showStartup(),__name(dlog,"dlog"),__name(dlogSection,"dlogSection")}});async function loadUserConfig(){try{const e=getConfigFile();return parseJSON(await P.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();h.writeFileSync(t,JSON.stringify(e,null,2)),h.chmodSync(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t=await loadUserConfig(),n=getConfiguredModel(),r={...t,...e,model:e.model??n};await saveUserConfig(r)}async function isTasteLearningEnabled(){return(await loadUserConfig()).tasteLearning??!0}async function setTasteLearning(e){const{tasteLearning:t}=e;await updateUserConfig({tasteLearning:t})}async function isOAuthEnforced(){if(null!==hn)return hn;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),hn=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),hn=!0,!0;const e=await loadUserConfig();return(hn=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),hn}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error($t)}function getConfiguredModel(){try{const e=getConfigFile();return(parseJSON(h.readFileSync(e,"utf-8"))||{}).model??ht}catch{return ht}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}var yn,En,wn=__esm({"src/utils/user-config.ts"(){bt(),vt(),xt(),Mt(),fn(),Sn(),kn(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),hn=null,__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel")}}),bn=__esm({"src/components/anthropic-auth.tsx"(){bt(),an(),Ut(),Mt(),ln(),pn(),wn(),yn=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=_(""),[s,a]=_(null),[i,c]=_(!1),[l,d]=_(null),[u,m]=_(!0),[g,p]=_(!1),[h,f]=_(!1);U(()=>{const{url:e,verifier:t,state:n}=Nt.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=j(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||h){if(!h||t.isPasteEnd){if(h&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}o(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}},[h]);V((e,n)=>{if(n.escape&&t(),u&&!g)if("y"!==e&&"Y"!==e)"n"!==e&&"N"!==e||t();else{if(!s)return;X(s.url).then(()=>{p(!0),m(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),p(!0),m(!1)})}});const E=__name(async()=>{if(r.trim()&&s&&!i){c(!0),d(null);try{const t=r.split("#")[0].trim();await Nt.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),c(!1),n&&n(t)}}},"handleSubmit");return u&&!g?L.createElement(z,{flexDirection:"column"},L.createElement(z,{marginBottom:1},L.createElement(W,{bold:!0,color:"cyan"},"Anthropic Authentication")),L.createElement(z,{marginBottom:1},L.createElement(W,null,"Open the Anthropic auth page?",L.createElement(W,{dimColor:!0}," (Y/n)")))):L.createElement(z,{flexDirection:"column"},L.createElement(z,{marginBottom:1},L.createElement(W,{bold:!0,color:"cyan"},"Anthropic Authentication")),L.createElement(z,{marginBottom:1},L.createElement(W,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),L.createElement(z,{marginBottom:1},L.createElement(W,{dimColor:!0},"After authorizing, copy the code and paste it below:")),l&&L.createElement(z,{marginBottom:1},L.createElement(W,{color:"red"},"Error: ",l)),L.createElement(z,null,L.createElement(W,null,"Authorization code: "),L.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:y,onSubmit:E,placeholder:"Paste code here..."})),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function getProviderDisplayName(e){if(!e)return"None";const t=En[e];return t?.displayName||e}function getProviderConfig(e){return En[e]}function isInternalTeamFlagPresent(){return process.argv.includes(st)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(at)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(h.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(En).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var Sn=__esm({"src/utils/provider-config.ts"(){bt(),vt(),Ut(),bn(),xt(),kn(),En={"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:yn,checkAuth:__name(async()=>!!await Nt.getValidAccessToken(),"checkAuth")}},__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalTeamFlagPresent,"isInternalTeamFlagPresent"),__name(isInternalTeamDisableFlagPresent,"isInternalTeamDisableFlagPresent"),__name(isInternalTeamFlagEnforced,"isInternalTeamFlagEnforced"),__name(getProviderOptions,"getProviderOptions")}});function isInternalTeamDisableOAuthFlagPresent(){return process.argv.includes(at)}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=getConfigFile(),t=await x.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,s=isInternalTeamFlagPresent();return isInternalTeamDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):s||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)}function formatTime2(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function formatTokens(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}var kn=__esm({"src/utils/utils.ts"(){bt(),xt(),Lt(),Sn(),wn(),vt(),__name(isInternalTeamDisableOAuthFlagPresent,"isInternalTeamDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut"),__name(formatTime2,"formatTime"),__name(formatTokens,"formatTokens")}});function isLocalDevelopmentBuild(){try{const e=process.argv[1];if(!e)return!1;if(e.includes("/usr/local/bin/dmd"))return!0;const t=f.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var Cn=__esm({"src/utils/is-local-dev.ts"(){bt(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":kt()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return Qe;case"local":return Ze;default:return Ye}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(h.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var vn=__esm({"src/utils/telemetry/config.ts"(){bt(),xt(),kn(),Tt(),Cn(),St(),St(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}});function getPackageJson(){const e=import.meta.url,t=c(e),n=r(t);return JSON.parse(E(o(n,"./../package.json"),"utf8"))}var Tn,An,Pn,xn,In,Dn,Rn=__esm({"src/utils/package.ts"(){bt(),__name(getPackageJson,"getPackageJson")}});function createAxiomExporter(){return new An({url:Je,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":et}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return Pn({[xn]:Xe,[In]:e.version,"process.executable.name":t,"process.runtime.name":"node","process.runtime.version":process.version,"process.pid":process.pid})}function createTelemetrySDK(){const e=createAxiomExporter(),t=createServiceResource();return new Tn({resource:t,spanProcessors:[new Dn(e)],autoDetectResources:!1})}var $n,Fn,Nn,On,Ln,_n=__esm({"src/utils/telemetry/sdk-factory.ts"(){bt(),St(),vn(),Rn(),({NodeSDK:Tn}=ee),({OTLPTraceExporter:An}=te),({resourceFromAttributes:Pn}=ne),({ATTR_SERVICE_NAME:xn,ATTR_SERVICE_VERSION:In}=re),({SimpleSpanProcessor:Dn}=oe),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function generateSessionId(){return`sess_${ce().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return F.createHash("sha256").update(e).digest("hex").substring(0,12)}function getCliVersion(){try{const e=getPackageJson();if("string"==typeof e.version&&""!==e.version.trim())return e.version}catch{}return"unknown"}function buildSessionAttributes(e){const{sessionId:t,projectPath:n,gitBranch:r,cliVersion:o}=e;return{"session.id":t,"session.start_time":(new Date).toISOString(),"session.project_hash":hashPath(n),"session.branch_hash":r?hashPath(r):"unknown","session.cli_version":o,"session.platform":`${m.platform()}-${m.arch()}`,"session.node_version":process.version}}function startSession(){Ln={},Fn=null,Nn=null,$n=generateSessionId(),On=Date.now();try{const e=se.getTracer(Xe),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:$n,projectPath:n,gitBranch:r,cliVersion:t});Fn=e.startSpan("session:cli",{attributes:o}),Nn=Fn.spanContext(),Fn.end()}catch{Fn=null,Nn=null}return $n}function getTraceId(){return Nn?Nn.traceId:null}function getSessionContext(){return Nn?se.setSpanContext(ie.active(),Nn):ie.active()}function endSession(e={}){const{status:t="success"}=e;if(Nn&&On){const e=se.getTracer(Xe),n=Date.now()-On,r=se.setSpanContext(ie.active(),Nn),o=e.startSpan("session:end",{attributes:{"session.id":$n||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Ln}},r);"error"===t?o.setStatus({code:ae.ERROR}):o.setStatus({code:ae.OK}),o.end()}Fn=null,Nn=null,$n=null,On=null,Ln={}}var Mn=__esm({"src/utils/telemetry/session.ts"(){bt(),St(),Rn(),Lt(),$n=null,Fn=null,Nn=null,On=null,Ln={},__name(generateSessionId,"generateSessionId"),__name(hashPath,"hashPath"),__name(getCliVersion,"getCliVersion"),__name(buildSessionAttributes,"buildSessionAttributes"),__name(startSession,"startSession"),__name(getTraceId,"getTraceId"),__name(getSessionContext,"getSessionContext"),__name(endSession,"endSession")}});function setSpanStatus(e,t){"error"===t?e.setStatus({code:ae.ERROR}):e.setStatus({code:ae.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=se.getTracer(Xe),o=getSessionContext();return r.startSpan(t,{attributes:n},o)}function endSpan(e){const{span:t,status:n="success"}=e;setSpanStatus(t,n),t.end()}function recordError(e){const{span:t,error:n,additionalAttributes:r}=e;if(t.recordException(n),t.setStatus({code:ae.ERROR,message:n.message}),t.setAttribute("error.type",n.name),t.setAttribute("error.message",n.message),n.stack&&t.setAttribute("error.stack",n.stack),r)for(const[e,n]of Object.entries(r))void 0!==n&&t.setAttribute(e,n)}var Un=__esm({"src/utils/telemetry/spans.ts"(){bt(),St(),Mn(),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});function isSecretKey(e){const t=e.toLowerCase();return tt.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return nt.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString(e){return e.length<=rt?e:`${e.substring(0,rt-3)}...`}function normalizeError(e){return e instanceof Error?e:new Error(String(e))}function sanitizeErrorForTelemetry(e){const{error:t,label:n="error"}=e,r=new Error(n);return r.name=t.name||"Error",r}function sanitizeValue(e){const{value:t,key:n,visited:r}=e;if(isContentKey(n)||isSecretKey(n))return"[redacted]";if(null==t)return t;if("string"==typeof t)return t.length>rt?truncateString(t):t;if("number"==typeof t||"boolean"==typeof t)return t;if("object"==typeof t){if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map((e,t)=>sanitizeValue({value:e,key:String(t),visited:r}));const e={};for(const[n,o]of Object.entries(t))e[n]=sanitizeValue({value:o,key:n,visited:r});return e}return"[Unsupported]"}function sanitizeParams(e){const t=new WeakSet;t.add(e);const n={};for(const[r,o]of Object.entries(e))n[r]=sanitizeValue({value:o,key:r,visited:t});return n}function sanitizeEndpoint(e){return e.split("?")[0]}var jn=__esm({"src/utils/telemetry/sanitization.ts"(){bt(),St(),__name(isSecretKey,"isSecretKey"),__name(isContentKey,"isContentKey"),__name(safeStringify,"safeStringify"),__name(truncateString,"truncateString"),__name(normalizeError,"normalizeError"),__name(sanitizeErrorForTelemetry,"sanitizeErrorForTelemetry"),__name(sanitizeValue,"sanitizeValue"),__name(sanitizeParams,"sanitizeParams"),__name(sanitizeEndpoint,"sanitizeEndpoint")}});function createTrackingHandle(e){const{span:t,startTime:n,durationAttr:r,statusAttr:o}=e;return{span:t,end:__name(e=>{const s=Date.now()-n;if(t.setAttribute(r,s),"status"in e)t.setAttribute(o,e.status),e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r,errorBody:o}=e;if(t.setAttribute("http.status_code",n),o){const e="string"==typeof o?o:safeStringify(o);t.setAttribute("http.response_body",e.substring(0,ot))}r?(recordError({span:t,error:r}),endSpan({span:t,status:"error"})):endSpan({span:t,status:n>=400?"error":"success"})}},"end")}}function trackToolStart(e){const{toolName:t,params:n}=e;return createTrackingHandle({span:createSpan({name:`tool:${t}`,attributes:{"tool.name":t,"tool.params":safeStringify(n?sanitizeParams(n):{})}}),startTime:Date.now(),durationAttr:"tool.duration_ms",statusAttr:"tool.status"})}function trackError(e){const{error:t,context:n}=e,r=normalizeError(t),{component:o,heading:s,code:a,...i}=n,c={"error.type":r.name,"error.message":r.message,"error.component":o,"error.heading":s};void 0!==a&&(c["error.code"]=String(a));for(const[e,t]of Object.entries(i))null!=t&&(c[e]="object"==typeof t?safeStringify(t):String(t));const l=createSpan({name:`error:${r.name}`,attributes:c});recordError({span:l,error:r}),l.end()}function trackAPICallStart(e){const{method:t,endpoint:n}=e,r=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${r}`,attributes:{"http.method":t,"http.url":r}}),startTime:Date.now(),durationAttr:"http.duration_ms",statusAttr:"http.status"})}function getSupportId(){const e=getTraceId();return e?`req_${e}`:"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,nodeVersion:s,platform:a,arch:i}=e,c={"whoami.node_version":s,"whoami.platform":a,"whoami.arch":i,"whoami.os":`${a}-${i}`};t&&(c["whoami.user_name"]=t),n&&(c["whoami.user_id"]=n),r&&(c["whoami.org_login"]=r),o&&(c["whoami.org_id"]=o),endSpan({span:createSpan({name:"whoami",attributes:c}),status:"success"})}var Bn,zn,Wn,Hn=__esm({"src/utils/telemetry/events.ts"(){bt(),Un(),Mn(),St(),jn(),jn(),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(trackError,"trackError"),__name(trackAPICallStart,"trackAPICallStart"),__name(getSupportId,"getSupportId"),__name(systemInfo,"systemInfo")}}),Gn=__esm({"src/utils/telemetry/components.ts"(){bt(),Bn={AUTH_FLOW:"auth-flow",ANTHROPIC_OAUTH:"anthropic-oauth",ANTHROPIC_CLIENT:"anthropic-client",UNHANDLED_REJECTION:"unhandled-rejection",UNCAUGHT_EXCEPTION:"uncaught-exception",SESSION_MANAGER:"session-manager",UPDATE_COMMAND:"update-command",LEARN_TASTE_COMMAND:"learn-taste-command",LEARNING_AGENT:"learning-agent",TASTE_REMOTE_STORAGE:"taste-remote-storage",CHECKPOINT_MANAGER:"checkpoint-manager",FILE_HISTORY:"file-history",API_REQUEST:"api-request",CONTEXT_ENGINE:"context-engine",CLI_ERROR_HANDLER:"cli-error-handler"}}});function initTelemetry(){if(Wn)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(zn=createTelemetrySDK()).start(),Wn=!0,!0}catch{return zn=null,Wn=!1,!1}}async function shutdownTelemetry(){if(zn&&Wn)try{endSession(),await zn.shutdown()}catch{}finally{zn=null,Wn=!1}}function shutdownTelemetrySync(){if(Wn)try{endSession()}catch{}}function isTelemetryInitialized(){return Wn}var qn,Vn,Kn,Jn,Yn,Qn,Zn,Xn,er,tr,nr,rr,or,sr,ar,ir=__esm({"src/utils/telemetry/telemetry.ts"(){bt(),_n(),vn(),Mn(),Un(),Hn(),Gn(),zn=null,Wn=!1,__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized")}}),cr=__esm({"src/components/vscode-context/ipc-client.ts"(){bt(),fn(),qn=t.join(g.homedir(),".commandcode","ide"),Vn=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),Kn=__name(e=>{if("win32"===process.platform)return null;try{const t=v(`ps -o ppid= -p ${e}`,{encoding:"utf-8",timeout:1e3}),n=parseInt(t.trim(),10);return Number.isNaN(n)||n<=1?null:n}catch{return null}},"getParentPid"),Jn=__name((e,t,n=Kn)=>{const r=new Map;for(const t of e)r.set(t.session.pid,t);let o=t;for(let e=0;e<10&&null!==o;e++){const e=r.get(o);if(e)return e;o=n(o)}return null},"findAncestorSession"),Yn=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),Qn=__name((e,n)=>{try{f.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{f.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),Zn=__name((e,n={})=>{const{sessionDir:r=qn,parentPidFn:o=Kn,startPid:s=process.ppid}=n;try{if(!f.existsSync(r))return null;const n=`${e}-`,a=f.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),i=[];for(const e of a)try{const n=t.join(r,e),o=JSON.parse(f.readFileSync(n,"utf-8"));if(!Vn(o.pid)){Qn(n,r);continue}i.push({session:o,file:e})}catch{continue}if(0===i.length)return null;const c=Jn(i,s,o);if(c)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:c.session.socketPath,ideName:c.session.ideName}),c.session.socketPath;const l=process.cwd();let d=null,u=0;for(const{session:e}of i)for(const n of e.workspaceFolders)(l===n||l.startsWith(n+t.sep))&&n.length>u&&(d=e,u=n.length);return d&&dlog("[VSCode:IPC] Discovered session via workspace match",{socketPath:d.socketPath,ideName:d.ideName}),d?.socketPath??null}catch{return null}},"discoverSocketPath"),Xn=__name(()=>{const e=Yn();return e?Zn(e):null},"resolveSocketPath"),er=__name(()=>({type:"request",id:O(),payload:{action:"getContext"}}),"createContextRequest"),tr=__name(e=>{if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&!!["request","response","error"].includes(t.type)&&"object"==typeof t.payload&&null!==t.payload},"isValidIPCMessage"),nr=__name((e,t)=>{try{const n=JSON.parse(e.toString());return tr(n)?"response"!==n.type||n.id!==t?null:n.payload:(dlog("[VSCode:IPC] Invalid message structure"),null)}catch{return null}},"parseResponse"),rr=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??Xn()}get isConnected(){return this.connected}async connect(e=2e3){if(!this.socketPath)return dlog("[VSCode:IPC] No socket path resolved"),!1;const t=this.socketPath;return dlog("[VSCode:IPC] Connecting to socket",{path:t,timeout:e}),new Promise(n=>{const r=__name(()=>{this.socket?.off("error",o)},"cleanup"),o=__name(e=>{clearTimeout(s),r(),this.connected=!1,dlog("[VSCode:IPC] Connection error",{error:e.message}),n(!1)},"handleError"),s=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),r(),this.socket?.destroy(),n(!1)},e);try{this.socket=de.connect(t),this.socket.on("connect",()=>{clearTimeout(s),r(),this.connected=!0,dlog("[VSCode:IPC] Connected successfully"),this.socket.on("close",()=>{this.connected=!1}),this.socket.on("error",()=>{this.connected=!1}),n(!0)}),this.socket.on("error",o)}catch(e){clearTimeout(s),r(),dlog("[VSCode:IPC] Connection exception",{error:e}),n(!1)}})}async getContext(e=5e3){const t=this.socket;if(!t||!this.connected)return dlog("[VSCode:IPC] Cannot get context - not connected"),null;const n=er();return new Promise(r=>{const o=__name(()=>{t.off("data",a),t.off("error",i)},"cleanup"),s=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),o(),r(null)},e),a=__name(e=>{clearTimeout(s),o();const t=nr(e,n.id);t||dlog("[VSCode:IPC] Invalid response received"),r(t)},"handleData"),i=__name(e=>{clearTimeout(s),o(),dlog("[VSCode:IPC] Socket error during request",{error:e.message}),r(null)},"handleError");t.on("data",a),t.on("error",i);try{t.write(JSON.stringify(n)+"\n")}catch(e){clearTimeout(s),o(),dlog("[VSCode:IPC] Failed to send request",{error:e}),r(null)}})}disconnect(){this.socket&&(dlog("[VSCode:IPC] Disconnecting"),this.socket.end(),this.socket=null,this.connected=!1)}static async isAvailable(e=1e3){const t=new _VSCodeIPCClient;if(!t.socketPath)return dlog("[VSCode:IPC] Availability check",{available:!1,reason:"no socket path"}),!1;const n=await t.connect(e);return t.disconnect(),dlog("[VSCode:IPC] Availability check",{available:n}),n}}}}),lr={};function getVsixPath(){try{const e=t.dirname(c(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return f.existsSync(n)?n:null}catch{return null}}async function getExtensionStatus(e){if(!e)return{installed:!1,version:null,connected:!1};const[t,n]=await Promise.all([checkInstalled(e),rr.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await or(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp(`${sr}@([\\d.]+)`,"i"));return n?{installed:!0,version:n[1]}:{installed:!1,version:null}}catch{return{installed:!1,version:null}}}async function installExtension(e){if(!e)return{success:!1,error:"No IDE detected"};const t=getVsixPath();if(!t)return{success:!1,error:"VSIX not bundled"};try{return await or(`${e} --install-extension "${t}" --force`,{timeout:3e4}),dlog(`[IDE] Extension installed for ${e}`),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function installExtensionAsync(e){e&&installExtension(e).catch(()=>{})}async function isAutoInstallEnabled(){try{return!1!==(await loadUserConfig()).autoInstallExtension}catch{return!0}}async function ensureExtensionInstalled(){if(process.env.CI)return;const e=Yn();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:J.green("✔"),installed:J.green("✔"),needs_reload:J.yellow("◌"),failed:J.red("✖"),not_in_ide:J.yellow("◌")},n={connected:`Connected to ${e.ide}`,installed:`Installed for ${e.ide}`,needs_reload:`${e.ide} extension needs reload`,failed:e.ide?`${e.ide} install failed`:"Install failed",not_in_ide:"Not in IDE"};return["",`${t[e.status]} ${n[e.status]}`,...(e.details??[]).map(e=>J.dim(` ${e}`)),""]}async function runIDESetup(){const e=Yn(),t=e?ar[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new rr,r=await n.connect(500);if(n.disconnect(),r)return{status:"connected",ide:t};const{installed:o}=await checkInstalled(e);return o?{status:"needs_reload",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:(await installExtension(e)).success?{status:"installed",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:{status:"failed",ide:t,details:[`Make sure "${e}" is available in your PATH.`,"Then run /ide to retry installation."]}}((e,t)=>{for(var n in t)Et(e,n,{get:t[n],enumerable:!0})})(lr,{detectIDE:()=>Yn,ensureExtensionInstalled:()=>ensureExtensionInstalled,formatSetupResult:()=>formatSetupResult,getExtensionStatus:()=>getExtensionStatus,installExtension:()=>installExtension,installExtensionAsync:()=>installExtensionAsync,isAutoInstallEnabled:()=>isAutoInstallEnabled,runIDESetup:()=>runIDESetup});var dr=__esm({"src/utils/ide-installer.ts"(){bt(),cr(),fn(),wn(),or=ue(T),sr="commandcode.commandcode-vscode",__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled"),ar={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"},__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup")}});bt(),bt();var ur=process.argv.includes("-d")||process.argv.includes("--debug");ur&&(process.env.DEBUG="true"),ur||(process.removeAllListeners("warning"),process.on("warning",()=>{})),bt(),bt(),ir();var{red:mr,yellow:gr,dim:pr}=J,hr=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:o=!0,skipTelemetry:s=!1}=e;if(n){if(s||trackError({error:sanitizeErrorForTelemetry({error:n,label:"cli_error"}),context:{component:Bn.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${ge.error} ${mr(t)}`),console.log(`${ge.error} ${mr("ERROR →")} ${n.name}`),console.log(`${ge.info} ${mr("REASON →")} ${n.message}`),console.log(`${ge.info} ${mr("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${ge.info} ${pr(`Request ID: ${e}`)}`),console.log(`${pr(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${ge.warning} ${gr(t)}\n`);if(!o)return!1;process.exit(0)}},"handleError");function handleUnhandledErrors(){process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:Bn.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),hr({heading:me`CRITICAL: Unhandled Promise Rejection!
3
+ This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:t,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})}),process.on("uncaughtException",e=>{trackError({error:sanitizeErrorForTelemetry({error:e,label:"uncaught_exception"}),context:{component:Bn.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),hr({heading:me`CRITICAL: Uncaught Exception!
4
+ This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}async function findAvailablePort(e=5959,t=10){for(let n=0;n<t;n++){const t=e+n;if(await checkPortAvailable(t))return t}throw new Error(`No available port found after ${t} attempts starting from port ${e}`)}async function checkPortAvailable(e){return new Promise(t=>{const n=le.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}ir(),__name(handleUnhandledErrors,"handleUnhandledErrors"),bt(),bt(),vt(),bt(),bt(),vt(),bt(),bt(),bt(),bt(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable");var fr=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}};function createAuthServer(e,t){let n,r;const o=new Promise((e,t)=>{n=e,r=t}),s=Pe.createServer((e,o)=>{const a=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],i=e.headers.origin||"",c=a.includes(i)?i:a[0];if(o.setHeader("Access-Control-Allow-Origin",c),o.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type"),o.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return o.writeHead(204),void o.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return o.writeHead(404),void o.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return o.writeHead(405),void o.end(JSON.stringify(e))}let l="";e.on("data",t=>{l+=t.toString(),l.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(l);if(e.error){const t=e,n={success:!0};return o.writeHead(200),o.end(JSON.stringify(n)),"access_denied"===t.error?r(new fr(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void s.close()}const a=e;if(!(a.apiKey&&a.state&&a.userId&&a.userName&&a.keyName)){const e={success:!1,error:"Missing required fields"};return o.writeHead(400),void o.end(JSON.stringify(e))}if(a.state!==t){const e={success:!1,error:"Invalid state token"};return o.writeHead(403),void o.end(JSON.stringify(e))}const i={success:!0};o.writeHead(200),o.end(JSON.stringify(i)),n(a),s.close()}catch{const e={success:!1,error:"Invalid JSON"};o.writeHead(400),o.end(JSON.stringify(e))}}),e.on("error",()=>{o.writeHead(500),o.end(JSON.stringify({success:!1,error:"Request error"}))})});return s.on("error",e=>{r(e)}),s.listen(e,"127.0.0.1"),{server:s,waitForCallback:o}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}function generateStateToken(){return F.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await X(e),!0}catch(e){return console.error("[CLI Auth] Failed to open browser:",e instanceof Error?e.message:"Unknown error"),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"browser_open_failed"}),context:{component:Bn.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(kt()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer"),Tt(),xt(),ir(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl");var yr=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}};async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await P.mkdir(t,{recursive:!0,mode:448});const r=JSON.stringify({apiKey:e.apiKey,userId:e.userId,userName:e.userName,keyName:e.keyName,authenticatedAt:e.authenticatedAt},null,2);await P.writeFile(n,r,{mode:384}),await P.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await P.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}function getApiBaseUrl(){const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials"),bt(),__name(getApiBaseUrl,"getApiBaseUrl"),vt(),ir();var Er=12e4;async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${ct.ALPHA.WHOAMI}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});return 401===n.status?{valid:!1,error:"invalid_key"}:n.ok?{valid:!0,user:await n.json()}:(process.env.DEBUG&&console.error(`API key validation failed with status ${n.status}`),{valid:!1,error:"server_error"})}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"apikey_validation_network_error"}),context:{component:Bn.AUTH_FLOW,heading:"API key validation network error"}}),process.env.DEBUG&&console.error("API key validation network error:",e),{valid:!1,error:"network_error"}}}function sanitizeApiKey(e){const t=String.fromCharCode(27),n=e.replaceAll(t+"[200~","").replaceAll(t+"[201~","").replaceAll("[200~","").replaceAll("[201~","");return Array.from(n).filter(e=>{const t=e.charCodeAt(0);return t>31&&127!==t}).join("").trim()}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:o=Er}=e,[s,a]=_("initializing"),[i,c]=_("Starting authentication..."),[l,d]=_(""),[u,m]=_(null),g=M(null),p=M(!1),h=M(!1),f=M(null),y=M(t),E=M(n),w=M(r);U(()=>{y.current=t,E.current=n,w.current=r});const b=j(()=>{f.current&&(clearTimeout(f.current),f.current=null),g.current&&(stopServer(g.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),g.current=null)},[]),S=j(()=>{h.current||(h.current=!0,p.current=!0,b(),w.current())},[b]),k=j((e,t)=>{h.current||(h.current=!0,b(),y.current(e,t))},[b]),C=j((e,t)=>{h.current||(h.current=!0,b(),E.current(e,t))},[b]),v=j(async e=>{const t=sanitizeApiKey(e);if(!t)return;a("validating"),c("Validating API key...");const n=await validateApiKey(t);if(p.current)return;if(h.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return a("invalid_key"),c(e),void(f.current=setTimeout(()=>{p.current||h.current||(a("manual_entry"),c("Paste a valid API key below.")),f.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(h.current)return;await storeCredentials(e),a("success"),k(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:Bn.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),c("Failed to save API key. Please try again."),a("manual_entry")}},[k]);return U(()=>{let e=!0;return __name(async()=>{if(!p.current)try{const t=await findAvailablePort(5959,10);if(!e||p.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);m(r);const{server:s,waitForCallback:i}=createAuthServer(t,n);if(g.current=s,!e||p.current)return void await stopServer(s);a("waiting_browser"),c("Opening browser for authentication...");const l=await openBrowser(r);if(!e||p.current)return;if(!l)return b(),c("Could not open browser. Paste your API key below."),void a("manual_entry");c("Complete login in your browser...");const d=new Promise((e,t)=>{setTimeout(()=>{t(new yr("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([i,d]);if(!e||p.current)return;if(h.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(h.current)return;if(await storeCredentials(n),!e||p.current||h.current)return;a("browser_success"),k(n,"browser")}catch(t){if(h.current)return;if(!e||p.current)return;if(t instanceof fr)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:Bn.AUTH_FLOW,heading:"Authorization denied by user"}}),a("denied"),void C("denied","Authorization denied by user.");b(),t instanceof yr&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:Bn.AUTH_FLOW,heading:"Browser auth timed out"}}),c("Browser auth timed out. Paste your API key below.")):(trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_failed"}),context:{component:Bn.AUTH_FLOW,heading:"Browser auth failed"}}),c("Browser auth failed. Paste your API key below.")),a("manual_entry")}}catch(t){if(h.current)return;if(!e||p.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:Bn.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),b(),a("manual_entry"),c("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,b()}},[o,k,C,b]),{authState:s,statusMessage:i,browserUrl:u,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:v,cancel:S,hasCompleted:h.current}}function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){switch(e){case"waiting_browser":return"Authorize in browser, or paste API key here";case"invalid_key":return"That key was invalid. Try again.";default:return"Paste your API key and press Enter"}}function getAuthUrlLabel(e){return"waiting_browser"===e?"Authenticating via:":"Get your API key from:"}__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow"),bt(),an(),vt(),Tt(),bt(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel");var wr=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const a=__name(()=>{switch(e){case"initializing":case"waiting_browser":case"validating":default:return L.createElement(Ae,{type:"dots"});case"browser_success":case"success":return L.createElement(W,{color:"green"},pe.tick);case"denied":case"invalid_key":return L.createElement(W,{color:"red"},pe.cross);case"manual_entry":return L.createElement(W,{color:"yellow"},pe.arrowDown);case"error":return L.createElement(W,{color:"red"},pe.warning)}},"getStatusIcon"),i=__name(()=>getAuthStatusColor(e),"getStatusColor");if("browser_success"===e||"success"===e||"denied"===e)return null;const c="initializing"===e||"waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,l=n&&("waiting_browser"===e||"manual_entry"===e);return L.createElement(z,{flexDirection:"column",paddingY:1},L.createElement(z,{marginBottom:1},L.createElement(z,{marginRight:1},a()),L.createElement(W,{color:i()},t)),c&&L.createElement(z,{flexDirection:"column"},L.createElement(z,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?"yellow":"gray",paddingX:1},L.createElement(W,{dimColor:!0},"API Key: "),L.createElement(z,{flexGrow:1},L.createElement(TextInput,{value:r,onChange:o,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},getAuthHelpText(e))),l&&L.createElement(z,{marginTop:1,flexDirection:"column"},L.createElement(W,{dimColor:!0},getAuthUrlLabel(e)),L.createElement(W,{color:"cyan",dimColor:!0},n||getStudioAuthUrl(kt())))),"validating"===e&&L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"initializing"===e||"invalid_key"===e)&&L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Ctrl+C to cancel")))},"AuthFlowUI"),br=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a,cancel:i}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return V((e,t)=>{t.ctrl&&"c"===e&&i()}),L.createElement(wr,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey");function heading({text:e,sub:t,dim:n,green:r}){const o=t?` ${t}`:"";return r?`${Q.bgGreen(Q.black(` ${e} `))}${o}`:n?`${Q.bgBlack(Q.white(` ${e} `))}${o}`:`${Q.bold(Q.bgCyan(Q.black(` ${e} `)))}${o}`}async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=Nt.createAuthorizationUrl(),r=await ve({message:"Open the Anthropic auth page?"});if(ke(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await X(e),console.log(),console.log(Q.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(Q.dim(" Open this URL in your browser:")),console.log(),console.log(Q.cyan(` ${e}`)),console.log(),console.log(Q.yellow(" Copy your authorization code and paste it below.")),console.log());const o=await Te({message:"Paste your authorization code:",mask:"*"});if(ke(o))return{success:!1,error:"No API key provided"};if(!o.trim())return{success:!1,error:"No authorization code provided"};const s=o.split("#")[0].trim();return await Nt.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}Mt(),Tt(),bt(),__name(heading,"heading"),Sn(),wn(),bt(),Ut(),__name(performAnthropicAuth,"performAnthropicAuth"),bt();var Sr=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},kr=class extends Error{static{__name(this,"AuthorizationDeniedError")}constructor(e){super(e),this.name="AuthorizationDeniedError"}};async function readAuthFile(e){try{const t=getAuthFile(e),n=await x.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async function getAuthKey(e){const t=await readAuthFile(e);return t&&t.apiKey||null}async function checkAuthStatus(e){const t=await readAuthFile(e);return t&&t.apiKey?{authenticated:!0,apiKey:t.apiKey,userName:t.userName}:{authenticated:!1,apiKey:null}}async function statusAction(){const e=xe("Checking authentication status...").start();try{const t=kt(),n=await checkAuthStatus(t);n.error&&(e.fail(Q.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(Q.red("Not authenticated")),console.log(""),console.log(`${Q.dim("Run")} ${Q.cyan("cmd auth login")} ${Q.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${Q.green(pe.tick)} ${Q.bold("Authenticated")} with ${Q.cyan("Command Code")}`),n.userName&&console.log(`${Q.dim("Logged in as")} ${Q.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(Q.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}bt(),vt(),xt(),Tt(),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction");var Cr=new ye("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction),vr=__name(({message:e})=>L.createElement(L.Fragment,null,L.createElement(W,{color:"cyan"},L.createElement(Ae,{type:"dots"})),L.createElement(W,null," ",e)),"LoadingIndicator"),Tr=__name(({message:e})=>L.createElement(L.Fragment,null,L.createElement(W,{color:"green"},pe.tick),L.createElement(W,null," ",e)),"SuccessIndicator"),Ar=__name(({children:e})=>L.createElement(z,{flexDirection:"column"},L.createElement(W,null," "),L.createElement(z,null,e)),"StatusContainer");function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,a]=_("loading"),[i,c]=_(null);return U(()=>{n().then(e=>{c(e),a(o?"success":"done")})},[n,o]),U(()=>{if("done"===s&&null!==i&&r(i),"success"===s&&null!==i){const e=setTimeout(()=>r(i),100);return()=>clearTimeout(e)}},[s,i,r]),"done"===s?null:L.createElement(Ar,null,"loading"===s?L.createElement(vr,{message:e}):L.createElement(Tr,{message:t}))}async function checkExistingAuth(e){const t=await checkAuthStatus(e);return t.authenticated?{isAuthenticated:!0,userName:t.userName}:{isAuthenticated:!1}}function getAuthFileName(e){return"local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json"}function isGenericUserName(e){return!e||"API Key"===e}function isGenericUserNameForOutro(e){return isGenericUserName(e)||"Manual API Key"===e}function formatUserDisplay(e,t=!1){return(t?isGenericUserNameForOutro(e):isGenericUserName(e))?t?" successfully":"":` as ${Q.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${Q.green(pe.tick)} ${Q.bold("Already logged in")}${t}`,"",`${Q.dim("Run")} ${Q.cyan("cmd")} ${Q.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${Q.green(pe.tick)} ${Q.bold("Logged in")}${n}`,"",`${Q.dim("API key stored in")} ${Q.cyan(`~/.commandcode/${t}`)}`,`${Q.dim("Run")} ${Q.cyan("cmd")} ${Q.dim("to get started.")}`].join("\n")}function isLoginSuccess(e){return e.success}function isLoginDenied(e){return"denied"===e.reason}function isLoginCancelled(e){return"cancelled"===e.reason}function createLoginError(e){return isLoginDenied(e)?new kr(e.message):isLoginCancelled(e)?new Sr(e.message):new Error(e.message)}function processLoginResult(e){return isLoginSuccess(e)?{success:!0,userName:e.config?.userName}:{success:!1,error:createLoginError(e)}}function needsProviderSelection(e){return e.length>1}function getDefaultProvider(e){return e[0]?.value??""}function isAnthropicProvider(e){return"anthropic"===e}function isUserCancellation(e){return e instanceof Sr||e instanceof kr}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),we.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await Se({message:"Select provider",options:e});if(ke(t))throw be(`${pe.cross} No provider selected.`),new Sr("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){be(`${pe.cross} ${e}`)}function showAnthropicAuthNote(){Ce("Command Code authentication complete. Now authenticating with Anthropic...")}function printMessage(e){console.log(""),console.log(e),console.log("")}function renderTaskWithSpinner(e,t,n,r=!0){return new Promise(o=>{const s=__name(e=>{a(),o(e)},"handleComplete"),{unmount:a}=G(L.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:s,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=G(L.createElement(br,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__name(isGenericUserName,"isGenericUserName"),__name(isGenericUserNameForOutro,"isGenericUserNameForOutro"),__name(formatUserDisplay,"formatUserDisplay"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(isLoginSuccess,"isLoginSuccess"),__name(isLoginDenied,"isLoginDenied"),__name(isLoginCancelled,"isLoginCancelled"),__name(createLoginError,"createLoginError"),__name(processLoginResult,"processLoginResult"),__name(needsProviderSelection,"needsProviderSelection"),__name(getDefaultProvider,"getDefaultProvider"),__name(isAnthropicProvider,"isAnthropicProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage,"getErrorMessage"),__name(showAuthIntro,"showAuthIntro"),__name(promptProviderSelection,"promptProviderSelection"),__name(selectProvider,"selectProvider"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(showAnthropicAuthNote,"showAnthropicAuthNote"),__name(printMessage,"printMessage"),__name(renderTaskWithSpinner,"renderTaskWithSpinner"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow");var Pr=__name(({env:e,onComplete:t})=>{const[n,r]=_("checking"),[o,s]=_(null);return U(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),U(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),L.createElement(Ar,null,"checking"===n&&L.createElement(vr,{message:"Checking authentication status..."}),"logged_in"===n&&L.createElement(Tr,{message:"Authenticated"}),"not_logged_in"===n&&L.createElement(Tr,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=G(L.createElement(Pr,{env:e,onComplete:e=>{n(),t(e)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function saveConfigWithSpinner(e){await renderTaskWithSpinner("Saving configuration...","Configuration saved",()=>updateUserConfig({provider:e}),!0)}async function executeLoginFlow(){const e=processLoginResult(await runLoginWithApiKeyFlow());if(!e.success)throw showLoginCancelMessage(e.error.message),e.error;return e.userName}async function handleAnthropicAuth(e){isAnthropicProvider(e)&&(showAnthropicAuthNote(),await performAnthropicAuth())}async function finalizeLogin(e,t,n){await saveConfigWithSpinner(e),printMessage(buildSuccessMessage(t,getAuthFileName(n)))}async function runLogin(){const e=kt(),t=await checkAuthWithSpinner(e);if(t.isAuthenticated)return printMessage(buildAlreadyLoggedInMessage(t.userName)),!0;showAuthIntro();const n=await executeLoginFlow();let r="command-code";return isInternalTeamFlagEnforced()&&(r=await selectProvider(),await handleAnthropicAuth(r)),await finalizeLogin(r,n,e),!0}async function loginAction(){try{await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${pe.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleAnthropicAuth,"handleAnthropicAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var xr=new ye("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction);async function safeRemoveFile(e,t){try{return await x.unlink(e),{existed:!0}}catch(e){return"ENOENT"===e.code?{existed:!1}:{existed:!0,warning:`Could not remove ${t}: ${e.message}`}}}function collectWarnings(...e){return e.map(e=>e.warning).filter(e=>void 0!==e)}async function performLogout(){try{const e=await safeRemoveFile(getAuthFile(),"auth file"),t=collectWarnings(e);return{success:!0,wasAuthenticated:e.existed,warnings:t}}catch(e){return{success:!1,wasAuthenticated:!1,warnings:[],error:e instanceof Error?e.message:"Unknown error"}}}bt(),bt(),xt(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout");var Ir=__name(()=>L.createElement(L.Fragment,null,L.createElement(W,{color:"cyan"},L.createElement(Ae,{type:"dots"})),L.createElement(W,null," Logging out...")),"LoadingIndicator"),Dr=__name(()=>L.createElement(L.Fragment,null,L.createElement(W,{color:"green"},pe.tick),L.createElement(W,null," Logged out")),"SuccessIndicator"),Rr=__name(({errorMessage:e})=>L.createElement(L.Fragment,null,L.createElement(W,{color:"red"},pe.cross),L.createElement(W,{color:"red"}," Logout failed: ",e)),"ErrorIndicator"),$r=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return L.createElement(Ir,null);case"success":return L.createElement(Dr,null);case"error":return L.createElement(Rr,{errorMessage:t})}},"StatusDisplay"),Fr=__name(({onComplete:e})=>{const[t,n]=_("loading"),[r,o]=_(""),[s,a]=_(null);return U(()=>{performLogout().then(e=>{a(e),e.success?n("success"):(o(e.error||"Unknown error"),n("error"))})},[]),U(()=>{if(("success"===t||"error"===t)&&s){const t=setTimeout(()=>e(s),100);return()=>clearTimeout(t)}},[t,s,e]),L.createElement(z,{flexDirection:"column"},L.createElement(W,null," "),L.createElement(z,null,L.createElement($r,{status:t,errorMessage:r})))},"LogoutSpinner");function printWarnings(e){e.length>0&&(console.warn(Q.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(Q.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=G(L.createElement(Fr,{onComplete:n=>{t(),e(n)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction");var Nr=new ye("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction);Tt(),xt(),new ye("auth").description("Manage authentication with Command Code").addCommand(xr).addCommand(Nr).addCommand(Cr),bt(),vt();var Or="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",Lr="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n";function getMaxLineWidth(e){return Math.max(...e.split("\n").map(e=>e.length))}__name(getMaxLineWidth,"getMaxLineWidth");var _r=getMaxLineWidth(Or),Mr=getMaxLineWidth(Lr),Ur=_r+1,jr=Mr+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var Br=__name(e=>{const t=e??getTerminalWidth();return t>=Ur?Or:t>=jr?Lr:zr},"getResponsiveCommandLogo"),zr="⌘ CMD\n",Wr=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),Hr=__name(e=>{console.log(J.white(Br())),console.log(""),console.log(`${pe.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),Gr=__name(async e=>{const t=fe.createInterface({input:process.stdin,output:process.stdout});try{const n=await t.question(e);return t.close(),{answer:n,cancelled:!1}}catch{return t.close(),{answer:"",cancelled:!0}}},"promptYesNo"),qr=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.log(""),console.log(`${pe.cross} Authentication failed. Please try again with: cmd login`),!1)}catch{return!1}},"attemptLogin"),Vr=__name(()=>{console.log(""),console.log(`${pe.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),Kr=__name(()=>{console.log(""),console.log(`${pe.info} Authentication cancelled. You can authenticate later with: cmd login`)},"showCancelledMessage");async function checkAuthAndPromptLogin(){try{if(await getAuthKey())return!0;Hr(Ct());const{answer:e,cancelled:t}=await Gr(`Would you like to sign in now? ${J.dim("(y/n)")}: `);return t?(Kr(),!1):Wr(e)?(console.log(""),qr()):(Vr(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin"),bt(),bt(),vt(),bt();var Jr=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(!t.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const n=t.relative(this.projectRoot,e);if(!n.startsWith("../../../"))return n.startsWith("../")?n:`./${n}`}catch(e){}if(this.options.useHomeShorthand&&e.startsWith(this.homeDir))return e.replace(this.homeDir,"~");const n=t.basename(e);return t.dirname(e),this.isUserPath(e)?`<user-home>/${t.relative(this.homeDir,e)}`:`<system-path>/${n}`}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))}};bt(),bt();var Yr=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 Qr({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Zr(e,o,n,r);case 401:return new Xr(e,o,n,r);case 403:return new eo(e,o,n,r);case 404:return new to(e,o,n,r);case 409:return new no(e,o,n,r);case 422:return new ro(e,o,n,r);case 429:return new oo(e,o,n,r);default:return e>=500?new so(e,o,n,r):new _APIError(e,o,n,r)}}},Qr=class extends Yr{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)}},Zr=class extends Yr{static{__name(this,"BadRequestError")}status=400},Xr=class extends Yr{static{__name(this,"AuthenticationError")}status=401},eo=class extends Yr{static{__name(this,"PermissionDeniedError")}status=403},to=class extends Yr{static{__name(this,"NotFoundError")}status=404},no=class extends Yr{static{__name(this,"ConflictError")}status=409},ro=class extends Yr{static{__name(this,"UnprocessableEntityError")}status=422},oo=class extends Yr{static{__name(this,"RateLimitError")}status=429},so=class extends Yr{static{__name(this,"InternalServerError")}};ir();var ao=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}),o=trackAPICallStart({method:e.method,endpoint:t});let s;try{s=await this.makeRequest({url:n,options:e,headers:r})}catch(e){const t=new Qr({cause:e instanceof Error?e:void 0});throw o.end({statusCode:0,error:t}),t}if(!s.ok){const{error:e}=await this.handleErrorResponse({response:s});throw o.end({statusCode:s.status,error:e}),e}return o.end({statusCode:s.status}),e.stream?s.body:s.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const s=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return o&&clearTimeout(o),s}catch(e){throw o&&clearTimeout(o),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};return e.headers.forEach((e,t)=>{n[t]=e}),{error:Yr.generate(e.status,t,e.statusText,n),errorBody:t}}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"})}};Ut(),bt(),Ut(),bt(),bt(),bt(),bt();var io=u.object({name:u.string().min(1,"Skill name is required").max(64,"Skill name must be 64 characters or less").regex(/^[a-z0-9-]+$/,"Skill name must contain only lowercase letters, numbers, and hyphens").refine(e=>!e.startsWith("-")&&!e.endsWith("-"),"Skill name cannot start or end with a hyphen").refine(e=>!e.includes("--"),"Skill name cannot contain consecutive hyphens"),description:u.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:u.string().optional(),compatibility:u.array(u.string()).optional(),metadata:u.record(u.string(),u.any()).optional(),"allowed-tools":u.array(u.string()).optional()});function getPersonalSkillsDir(){return t.join(g.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return t.join(process.cwd(),".commandcode","skills")}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await x.access(n);const e=(await x.readdir(n,{withFileTypes:!0})).filter(e=>e.isDirectory());return(await Promise.all(e.map(async e=>{try{const r=t.join(n,e.name,"SKILL.md");await x.access(r);const o=await x.readFile(r,"utf-8"),{data:s}=De(o),a=io.parse(s);return{name:a.name,description:a.description,filePath:r}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}async function loadAllSkillSummaries(){const[e,t]=await Promise.all([loadSkillSummariesFromDirectory({dir:getPersonalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir()})]);return{personal:e,project:t}}function escapeXML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function generateSkillsXML(e){const{personal:n,project:r}=e,o=[...n,...r];return 0===o.length?"":`<available_skills>\n${o.map(e=>{const n=t.normalize(e.filePath);return`<skill>\n<name>\n${escapeXML(e.name)}\n</name>\n<description>\n${escapeXML(e.description)}\n</description>\n<location>\n${escapeXML(n)}\n</location>\n</skill>`}).join("\n")}\n</available_skills>`}function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}u.object({name:u.string(),description:u.string(),license:u.string().optional(),compatibility:u.array(u.string()).optional(),metadata:u.record(u.string(),u.any()).optional(),"allowed-tools":u.array(u.string()).optional(),content:u.string(),filePath:u.string()}),u.object({name:u.string(),description:u.string(),filePath:u.string()}),vt(),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),bt(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),bt(),bt(),bt(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath"),bt();var co=u.object({absolutePath:u.string().describe("The absolute path to the file to read"),offset:u.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:u.number().optional().describe("Optional number of lines to read")});u.object({content:u.union([u.string(),u.instanceof(Buffer)]),contentType:u.enum(["text","binary"]),fileType:u.string(),size:u.number(),linesRead:u.number().optional()});var lo=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};async function readFileContent(t){const{absolutePath:n,offset:r,limit:o}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new lo("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=e.normalize(n);try{await P.access(s,h.constants.F_OK|h.constants.R_OK)}catch{throw new lo(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await P.stat(s)).isFile())throw new lo("Path does not point to a file","NOT_A_FILE");const a=getFileType(s),i=isBinaryFile(a);if(void 0!==r&&void 0===o||void 0===r&&void 0!==o)throw new lo("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new lo("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new lo("Limit must be > 0","INVALID_LIMIT");try{if(i){const e=await P.readFile(s);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==r&&void 0!==o){const e=await readTextFileLines(s,r,o);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await P.readFile(s,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof lo)throw e;throw new lo(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var uo={".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(t){const n=e.extname(t).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",...uo}[n]||"unknown"}function isBinaryFile(e){return Object.values(uo).includes(e)}async function readTextFileLines(e,t,n){const r=(await P.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),a=r.slice(o,s);return{content:a.join("\n"),linesRead:a.length}}async function processFileReferences(t){const n=[];let r=t;const o=[...t.matchAll(/@([^\s@]+)/g)];for(const t of o){const o=t[0],s=t[1];try{const t=e.isAbsolute(s)?s:e.resolve(process.cwd(),s),a=await readFileContent({absolutePath:t});if("binary"===a.contentType)continue;const i=String(a.content),c=e.relative(process.cwd(),t),l=1e5;if(i.length>l){n.push({token:o,resolvedPath:t,content:"",tooLarge:!0});const e=`${c}`;r=r.replace(o,e);continue}n.push({token:o,resolvedPath:t,content:i});const d=`{${c}: ${i}}`;r=r.replace(o,d)}catch(e){continue}}return{displayContent:t,processedContent:r,fileReferences:n}}function reconstructContent(t,n){let r=t;for(const t of n){const n=`{${e.relative(process.cwd(),t.resolvedPath)}: ${t.content}}`;r=r.replace(t.token,n)}return r}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),bt(),bt();var mo="read_file",go="edit_file",po="write_file",ho="read_directory",fo="read_multiple_files",yo="grep",Eo="shell_command",wo="think",bo="todo_write",So="ask_user_question",ko="kill_shell",Co="web_search",vo="web_fetch",To=__name(e=>e===Co,"isWebSearchTool"),Ao=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],Po=__name(({serverToolBlock:e,contentBlocks:t})=>{const n=t.find(t=>("web_search_tool_result"===t.type||"web_fetch_tool_result"===t.type)&&t.tool_use_id===e.id);return Ao.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:To(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage");function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",o=e.relative(n,t);return o.startsWith("..")?r&&t.startsWith(r)?t.replace(r,"~"):t:""===o?e.basename(t):o}function replacePathsInText(t){if(!t||"string"!=typeof t)return t;let n=t;return n=n.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,t=>e.isAbsolute(t)?toRelativePath(t):t),n=n.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),n}bt(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText");var xo=u.object({id:u.string(),timestamp:u.number(),type:u.literal("image"),source:u.object({type:u.enum(["base64","url"]),media_type:u.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:u.string()})}),Io=u.object({id:u.string(),timestamp:u.number(),input:u.string(),output:u.string().optional(),metadata:u.record(u.string(),u.any()).optional(),images:u.array(xo).optional().default([])}),Do=Io.extend({role:u.literal("user")}),Ro=Io.extend({role:u.literal("assistant")}),$o=Io.extend({role:u.literal("tool"),name:u.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),Fo=Io.extend({role:u.literal("bash"),command:u.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),No=Io.extend({role:u.literal("system")}),Oo=Io.extend({role:u.literal("error")}),Lo=Io.extend({role:u.literal("info")}),_o=Io.extend({role:u.literal("taste-onboarding")}),Mo=Io.extend({role:u.literal("command-result"),hasError:u.boolean().optional(),details:u.string().optional()}),Uo=Io.extend({role:u.literal("ide-status"),status:u.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:u.string().nullable(),details:u.array(u.string()).optional()}),jo=u.discriminatedUnion("role",[Do,Ro,$o,Fo,No,Oo,Lo,_o,Mo,Uo]),Bo=__name((e,t)=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),zo=__name(e=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e}),"createInfoEntry"),Wo=__name(e=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),Ho=__name((e,t,n)=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Go=__name(e=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),qo=__name(e=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Vo=__name(e=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),Ko=__name(()=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Jo=__name((e,t=!1,n)=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),Yo=__name((e,t,n)=>jo.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),Qo=__name(({name:e,input:t})=>{const n=Date.now();return jo.parse({id:crypto.randomUUID(),timestamp:n,role:"tool",name:e,input:t,output:void 0,metadata:{isAgent:!0,status:"running",startTime:n,tokensUsed:0}})},"createAgentToolEntry"),Zo=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return jo.parse(n)},"updateEntryWithOutput"),Xo=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),es=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),ts=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),ns=["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…"],rs=__name(()=>ns[Math.floor(Math.random()*ns.length)],"getRandomLLMStatus"),os=__name(e=>{switch(e){case mo:return"Read";case go:return"Edit";case po:return"Write";case ho:return"List";case fo:return"Read Multiple";case yo:return"Search";case Eo:return"Shell";case bo:return"Todos";case wo:return"Thinking…";case Co:return"Web Search";case vo:return"Web Fetch";case So:return"Question";case"explore":return"Explore";case ko:return"Kill Shell";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),ss=__name((e,t)=>{try{switch(e){case mo:case po:const e=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(e);case go:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case ho:return toRelativePath(t.path||"directory");case yo:const n=t.path||"files";return`"${t.pattern}" in ${toRelativePath(n)}`;case Eo: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 bo:let r;try{r="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=as(r);return`${e?e.length:0} items`}catch{return"items"}case wo:return t.content||"planning";case fo:const o=t.include||[];return Array.isArray(o)?o.join(", "):"multiple files";case Co:return t.query||"search";case vo:return t.url||"fetch";case So:return"User answered questions";case ko:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";default:{let e=t?.messages||[];if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return JSON.stringify(t||{})}if(Array.isArray(e)&&e.length>0&&e[0]&&"object"==typeof e[0]&&"content"in e[0]){const t=e[0].content;if("string"==typeof t){const e=t.trim(),n=e.indexOf("."),r=n>0?e.slice(0,n):e;return r.length>80?r.slice(0,80)+"...":r}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),as=__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");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")}bt(),bt(),bt(),__name(formatOutput,"formatOutput");var is={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=co.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while reading file`}},"execute")};bt(),bt();var cs=u.object({filePath:u.string().describe("The absolute path to the file to edit"),oldValue:u.string().describe("The text to replace"),newValue:u.string().describe("The new text to insert"),replacementCount:u.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:u.boolean().optional().describe("Whether to replace all occurrences (default: false)")});u.object({path:u.string(),replacementsCount:u.number(),oldContent:u.string(),newContent:u.string()}),u.object({name:u.string(),message:u.string(),code:u.string().optional()}),bt(),bt(),bt();var ls=u.object({backupFileName:u.string().nullable(),version:u.number().int().positive(),backupTime:u.string().datetime()}),ds=u.object({messageId:u.string().uuid(),trackedFileBackups:u.record(u.string(),ls),timestamp:u.string().datetime()});u.object({type:u.literal("file-history-snapshot"),messageId:u.string().uuid(),snapshot:ds,isSnapshotUpdate:u.boolean()}),u.object({maxFileSize:u.number().int().positive().default(10485760),retentionDays:u.number().int().positive().default(30)});var us=class extends Error{static{__name(this,"CheckpointError")}code;constructor(e,t){super(e),this.name="CheckpointError",this.code=t}};function getPathHash(e){const{filePath:t}=e;return`${N.createHash("sha256").update(t).digest("hex").slice(0,16)}-${t.length}`}function getBackupFileName(e){const{filePath:t,version:n}=e;return`${getPathHash({filePath:t})}@v${n}`}function getCommandCodeBasePath(){return t.join(g.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:n}=e;return t.join(getCommandCodeBasePath(),"file-history",n)}function getBackupFilePath(e){const{sessionId:n,backupFileName:r}=e;return t.join(getFileHistoryPath({sessionId:n}),r)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await x.statfs(t);return e.bavail*e.bsize}catch{return-1}}async function hasEnoughDiskSpace(e){const{fileSizeBytes:t,targetPath:n}=e,r=2*t,o=await getAvailableDiskSpace({targetPath:n});return-1===o||o>=r}async function ensureDirectoryExists(e){const{dirPath:t}=e;await x.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await x.writeFile(r,n);const e=await x.stat(r),o="string"==typeof n?Buffer.byteLength(n,"utf-8"):n.length;if(e.size!==o)throw new Error(`Write verification failed: expected ${o} bytes, got ${e.size}`);await x.rename(r,t)}catch(e){try{await x.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await x.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await x.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function truncateString2(e){const{text:t,maxLength:n}=e;return t.length<=n?t:n<=3?t.slice(0,n):t.slice(0,n-3)+"..."}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60),a=Math.floor(s/24);return a>0?`${a}d ago`:s>0?`${s}h ago`:o>0?`${o}m ago`:"just now"}function getFileName(e){const{filePath:n}=e;return t.basename(n)}function isWithinRetentionPeriod(e){const{timestamp:t,retentionDays:n}=e,r=new Date(t).getTime();return Date.now()-r<=24*n*60*60*1e3}bt(),bt(),vt(),__name(getPathHash,"getPathHash"),__name(getBackupFileName,"getBackupFileName"),__name(getCommandCodeBasePath,"getCommandCodeBasePath"),__name(getFileHistoryPath,"getFileHistoryPath"),__name(getBackupFilePath,"getBackupFilePath"),__name(getAvailableDiskSpace,"getAvailableDiskSpace"),__name(hasEnoughDiskSpace,"hasEnoughDiskSpace"),__name(ensureDirectoryExists,"ensureDirectoryExists"),__name(atomicWriteFile,"atomicWriteFile"),__name(getFileSizeBytes,"getFileSizeBytes"),__name(fileExists,"fileExists"),__name(getCurrentTimestamp,"getCurrentTimestamp"),__name(truncateString2,"truncateString"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod"),ir();var ms={maxFileSize:10485760,retentionDays:30},gs=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...ms,...n},this.status={enabled:!0,pausedReason:null,pausedAt:null},this.trackedState={files:new Map,versions:new Map},this.noticeDismissed=!1}getStatus(){return{...this.status}}getTrackedState(){return{files:new Map(this.trackedState.files),versions:new Map(this.trackedState.versions)}}shouldShowPausedNotice(){return null!==this.status.pausedReason&&!this.noticeDismissed}dismissPausedNotice(){this.noticeDismissed=!0}async checkAndResumeIfPossible(){if("disk_full"===this.status.pausedReason){const e=getFileHistoryPath({sessionId:this.sessionId});await hasEnoughDiskSpace({fileSizeBytes:104857600,targetPath:e})&&(this.status.pausedReason=null,this.status.pausedAt=null,this.noticeDismissed=!1)}}async backupFile(e){const{filePath:t}=e;if(await this.checkAndResumeIfPossible(),this.status.pausedReason)return{success:!1,backup:null,skipped:!0,skipReason:"disk_full"};if(!await fileExists({filePath:t})){const e=1,n={backupFileName:null,version:e,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,n),this.trackedState.versions.set(t,e),{success:!0,backup:n,skipped:!0,skipReason:"new_file"}}const n=await getFileSizeBytes({filePath:t});if(n>this.config.maxFileSize)return{success:!1,backup:null,skipped:!0,skipReason:"file_too_large"};const r=getFileHistoryPath({sessionId:this.sessionId});if(!await hasEnoughDiskSpace({fileSizeBytes:n,targetPath:r}))return this.status.pausedReason="disk_full",this.status.pausedAt=getCurrentTimestamp(),this.noticeDismissed=!1,{success:!1,backup:null,skipped:!0,skipReason:"disk_full"};try{const e=await x.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,o=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const s=getBackupFilePath({sessionId:this.sessionId,backupFileName:o});await atomicWriteFile({filePath:s,content:e});const a={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,a),this.trackedState.versions.set(t,n),{success:!0,backup:a,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:Bn.FILE_HISTORY,heading:"File backup failed"}}),{success:!1,backup:null,skipped:!0,skipReason:"read_error"}}}async restoreFile(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName)return void(await fileExists({filePath:t})&&await x.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new us(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:Bn.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await x.readFile(r);await atomicWriteFile({filePath:t,content:o})}async verifyRestoreOperation(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName){if(!await fileExists({filePath:t}))return{canRestore:!0};try{return await x.access(t,x.constants.W_OK),{canRestore:!0}}catch{return{canRestore:!1,error:"Cannot delete file: permission denied"}}}const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});return await fileExists({filePath:r})?{canRestore:!0}:{canRestore:!1,error:`Backup file missing: ${n.backupFileName}`}}getTrackedFileBackups(){const e={};for(const[t,n]of this.trackedState.files)e[t]=n;return e}loadTrackedState(e){const{trackedFileBackups:t}=e;this.trackedState.files.clear(),this.trackedState.versions.clear();for(const[e,n]of Object.entries(t))this.trackedState.files.set(e,n),this.trackedState.versions.set(e,n.version)}async cleanupOrphanedBackups(e){const{referencedBackups:t}=e,n=getFileHistoryPath({sessionId:this.sessionId});let r=0;try{const e=await x.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await x.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await x.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}};bt(),ir();var ps=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new gs({sessionId:t,config:r}),this.sessionStore=n||null,this.snapshots=[],this.config={maxFileSize:r?.maxFileSize||10485760,retentionDays:r?.retentionDays||30}}getFileHistoryManager(){return this.fileHistoryManager}setSessionStore(e){const{sessionStore:t}=e;this.sessionStore=t}async backupFile(e){const{filePath:t}=e,n=await this.fileHistoryManager.backupFile({filePath:t,sessionId:this.fileHistoryManager.getSessionId()});if(n.success&&this.snapshots.length>0){const e=this.snapshots[this.snapshots.length-1];e.trackedFileBackups=this.fileHistoryManager.getTrackedFileBackups(),this.sessionStore&&this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0}).catch(()=>{})}return{success:n.success,backup:n.backup}}async createSnapshot(e){const{messageId:t}=e,n={messageId:t,trackedFileBackups:{},timestamp:getCurrentTimestamp()};return this.snapshots.push(n),this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:n,isUpdate:!1}),n}async updateCurrentSnapshot(){if(0===this.snapshots.length)return;const e=this.snapshots[this.snapshots.length-1],t=this.fileHistoryManager.getTrackedFileBackups(),n=this.snapshots.length>1?this.snapshots[this.snapshots.length-2]:null,r=n?.trackedFileBackups||{},o={};for(const[e,n]of Object.entries(t)){const t=r[e];(!t||t.version!==n.version||t.backupFileName!==n.backupFileName)&&(o[e]=n)}e.trackedFileBackups=o,this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0})}listCheckpoints(){const e=[];for(let t=0;t<this.snapshots.length;t++){const n=this.snapshots[t];t>0&&this.snapshots[t-1];let r="";if(this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:n.messageId}),t=this.sessionStore.getMessageAtIndex({index:e});t&&(r=truncateString2({text:t.content,maxLength:100}))}const o=Object.keys(n.trackedFileBackups);let s=null;if(o.length>0){const e=o[0];n.trackedFileBackups[e]&&(s={additions:0,deletions:0,fileName:getFileName({filePath:e})})}e.push({messageId:n.messageId,timestamp:n.timestamp,userPrompt:r,fileCount:Object.keys(n.trackedFileBackups).length,filesModified:o,codeChanges:s})}return e.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime())}getSnapshot(e){const{messageId:t}=e;return this.snapshots.find(e=>e.messageId===t)||null}async restore(e){const{messageId:t,mode:n}=e;if(!this.getSnapshot({messageId:t}))return{success:!1,error:"Snapshot not found",filesRestored:0,filesDeleted:0,messagesRemoved:0};const r=this.snapshots.findIndex(e=>e.messageId===t);let o=0,s=0,a=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return trackError({error:sanitizeErrorForTelemetry({error:new Error(`Restore verification failed:\n${t.join("\n")}`),label:"restore_verification_failed"}),context:{component:Bn.CHECKPOINT_MANAGER,heading:"Checkpoint restore verification failed","checkpoint.failures":t.length}}),{success:!1,error:`Restore verification failed:\n${t.join("\n")}`,filesRestored:0,filesDeleted:0,messagesRemoved:0};for(const t of e)await this.fileHistoryManager.restoreFile({filePath:t.filePath,backup:t.backup}),null===t.backup.backupFileName?s++:o++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(a=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const i=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&i.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&i.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:i}),{success:!0,filesRestored:o,filesDeleted:s,messagesRemoved:a}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}};bt();var hs=null;function initializeCheckpointService(e){const{sessionId:t}=e;return hs=new ps({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return hs?hs.backupFile({filePath:t}):{success:!0,backup:null}}function createFileEditError(e,t){const n=new Error(e);return n.name="FileEditError",n.code=t,n}async function editFile(t){const{filePath:n,oldValue:r,newValue:o,replaceAll:s=!1,replacementCount:a=1}=t;if(!n)throw createFileEditError("filePath is required","INVALID_PATH");if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!r)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==o)throw createFileEditError("newValue is required","INVALID_INPUT");if(!s&&a<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await w.access(n,b.F_OK|b.R_OK|b.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${n}`,"FILE_ACCESS_ERROR")}let i;try{const e=await readFileContent({absolutePath:n});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");i=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const c=(i.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===c)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let l,d;if(s)l=c;else if(l=a,l>c)throw createFileEditError(`Expected ${l} replacements, but only found ${c} occurrences`,"INSUFFICIENT_MATCHES");let u=0;if(s||l===c)d=i.split(r).join(o),u=c;else{d=i;for(let e=0;e<l;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+o+d.substring(e+r.length),u++)}}if(0===u)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await w.writeFile(n,d,"utf-8"),{path:n,replacementsCount:u,oldContent:i,newContent:d}}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}__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit"),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),bt(),__name(formatOutput2,"formatOutput");var fs={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=cs.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while editing file`}},"execute")};bt(),bt();var ys=u.object({path:u.string().describe("The absolute path to the directory to read"),exclude:u.array(u.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:u.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});u.object({files:u.array(u.string()),directories:u.array(u.string())});var Es=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}};async function readDirectory(t){const{path:n,exclude:r=[],respectGitIgnore:o=!1}=t;if(!e.isAbsolute(n))throw new Es("Path must be absolute, not relative","INVALID_PATH");try{if(!(await P.stat(n)).isDirectory())throw new Es("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Es)throw e;throw new Es(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await P.readdir(n);let s=[];o&&(s=await loadGitIgnorePatterns(n));const a=[...r,...s],i=[],c=[];for(const r of t){if(shouldIgnoreEntry(r,a))continue;const t=e.join(n,r);try{const e=await P.stat(t);e.isDirectory()?c.push(r):e.isFile()&&i.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:i.sort(),directories:c.sort()}}catch(e){if(e instanceof Es)throw e;throw new Es(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(t){const n=[];try{if(!await isInGitRepository(t))return n;let r=e.resolve(t);const o=await findGitRoot(t);for(;r&&isWithinGitRoot(r,o);){const t=e.join(r,".gitignore");try{const e=(await P.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch(e){}const o=e.dirname(r);if(o===r)break;r=o}}catch(e){}return n}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await P.stat(t)).isDirectory())return n}catch{}const t=e.dirname(n);if(t===n)throw new Error("Not in a git repository");n=t}}function isWithinGitRoot(t,n){const r=e.resolve(t),o=e.resolve(n);return"win32"===process.platform?r.toLowerCase().startsWith(o.toLowerCase()):r.startsWith(o)}function shouldIgnoreEntry(e,t){for(const n of t)if(Re(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")}bt(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),bt(),__name(formatOutput3,"formatOutput");var ws={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=ys.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while reading directory`}},"execute")};bt(),bt();var bs=u.object({filePath:u.string().describe("The absolute path where the file should be written"),content:u.string().describe("The content to write to the file")});async function writeFile2({filePath:e,content:t}){if(!s(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=r(e);return y(n)||await I(n,{recursive:!0}),await backupFileBeforeEdit({filePath:e}),await D(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}`}u.object({success:u.boolean(),message:u.string(),path:u.string().optional()}),bt(),__name(writeFile2,"writeFile"),bt(),__name(formatOutput4,"formatOutput");var Ss={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=bs.parse(e),n=await writeFile2(t);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")};bt(),bt();var ks=u.object({include:u.array(u.string()).describe("Array of glob patterns to include files"),exclude:u.array(u.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:u.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:u.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:u.string().optional().describe("Base directory for relative paths. Default: current working directory")}),Cs=u.object({filePath:u.string(),content:u.string(),fileType:u.string(),size:u.number()});u.object({content:u.string(),filesRead:u.array(u.string()),errors:u.array(u.object({file:u.string(),error:u.string()})),fileDetails:u.array(Cs)});var vs=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}};bt();var Ts=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const o=new Set;for(const s of e)try{(await $e(s,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>o.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${s}": ${e}`)}return Array.from(o).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:n,exclude:r=[],gitIgnore:o=!0,defaultExclude:s=!0,targetDirectory:a=process.cwd()}=e;if(!n||0===n.length)throw new vs("At least one include pattern must be provided","NO_PATTERNS");const i=t.resolve(a),c={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];s&&e.push(...Ts);const a=await findMatchingFiles({include:n,exclude:e,gitIgnore:o,targetDirectory:i});for(const e of a)try{const n=t.resolve(i,e),r=await readFileContent({absolutePath:n}),o=processFileResult({content:r,filePath:e});c.fileDetails.push(o),c.content+=`\n// File: ${e} (${r.fileType})\n`,c.content+=o.content,c.content+="\n",c.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);c.errors.push({file:e,error:n}),c.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return c}catch(e){if(e instanceof vs)throw e;throw new vs(`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"),bt(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var As={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=ks.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while reading multiple files`}},"execute")};bt(),bt();var Ps=u.object({pattern:u.string().min(1,"Pattern is required"),include:u.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},u.array(u.string()).optional()),directory:u.string().optional()});bt(),bt();var xs=1e5,Is=5e4;function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=A(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",a="";o.stdout?.on("data",e=>{try{const t=e.toString();if(s.length+t.length>xs)return a="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",void o.kill("SIGTERM");s+=t}catch(e){a+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,o.kill("SIGTERM")}}),o.stderr?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>Is)return void(a+="\n[Error output truncated: too large]");a+=t}catch(e){a+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),o.on("close",e=>{0===e?n(s):1!==e||a?r(new Error(a||`Command failed with exit code ${e}`)):n("")}),o.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,o]=t;return{file:n,line:parseInt(r,10),column:1,content:o.trim(),match:o.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",o=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)o.splice(-1,0,"--glob",e);o.splice(-1,0,"--glob","!node_modules/**"),o.splice(-1,0,"--glob","!.git/**"),o.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:o,command:"rg"})}catch(s){if(!(s instanceof Error&&s.message.includes("ENOENT")))throw s;if(r="grep",o=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)o.splice(-1,0,"--include",e);o.splice(-1,0,"--exclude-dir=node_modules"),o.splice(-1,0,"--exclude-dir=.git"),o.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:o,command:"grep"})}if(!e.trim())return[];const s=e.trim().split("\n"),a=[];for(const e of s){const t=parseGrepLine(e);t&&a.push(t)}return a}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"),bt(),__name(formatGrepResults,"formatGrepResults");var Ds={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=Ps.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while searching files`}},"execute")};bt(),bt();var Rs=u.object({pattern:u.string().min(1,"Pattern is required"),path:u.string().optional()}),$s=class extends Error{static{__name(this,"GlobError")}code;constructor(e,t){super(e),this.name="GlobError",this.code=t}};async function globSearch(e){const{pattern:n,path:r="."}=e;if(!n)throw new $s("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new $s("Search path must be within the current working directory or an added directory","INVALID_PATH");const o=await $e(n,{cwd:e,ignore:ft,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),s=await Promise.all(o.map(async n=>{const r=t.join(e,n);try{return{file:n,mtime:(await x.stat(r)).mtimeMs}}catch{return{file:n,mtime:0}}}));return s.sort((e,t)=>t.mtime-e.mtime),{files:s.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof $s)throw e;if(e instanceof Error)throw new $s(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new $s("Unknown error occurred during file search","UNKNOWN_ERROR")}}function formatGlobResults(e){if(0===e.files.length)return"No files found matching pattern";const t=[],n=e.files.length;t.push(`Found ${n} file${1!==n?"s":""}`);for(const n of e.files)t.push(` ${n}`);return t.join("\n")}bt(),vt(),It(),__name(globSearch,"globSearch"),bt(),__name(formatGlobResults,"formatGlobResults");var Fs={name:"glob",description:"Searches for files in a directory tree using glob-style path patterns, enabling fast and flexible discovery of files across codebases of any size.\nThis tool matches file paths against glob patterns such as **/*.js or src/**/*.ts, making it ideal for locating files by name, extension, or directory structure without inspecting file contents. It performs recursive traversal where applicable and efficiently handles large repositories.\nResults are returned as a list of matching file paths, sorted by modification time, allowing you to quickly identify the most recently changed or relevant files.\nFile pattern matching can be refined using inclusive or exclusive glob expressions to narrow down results, improving performance and focus when working with large or complex projects.\nIt should be used when you need to find files based on naming or path patterns, explore the structure of an unfamiliar codebase, locate configuration or entry-point files, or prepare a targeted set of files for further inspection with tools like grep.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files. Supports wildcards: * matches any characters except /, ** matches any characters including / (for recursive search), ? matches single character, [abc] matches character set, {js,ts} matches alternatives. Examples: "**/*.ts" finds all TypeScript files recursively, "src/**/*.{js,jsx}" finds JavaScript files in src directory, "*.json" finds JSON files in current directory, "**/test/**/*.spec.ts" finds test spec files.'},path:{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=Rs.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while finding files`}},"execute")};bt(),bt();var Ns=u.object({command:u.string().min(1,"Command cannot be empty"),args:u.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},u.array(u.string()).optional()),directory:u.string().optional(),timeout:u.preprocess(e=>"string"==typeof e?parseInt(e,10):e,u.number().optional())}),Os=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,a){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=a}};async function executeShellCommand(t){const{command:n,args:r=[],directory:o,timeout:s=3e4}=t,a=Date.now();if(!n.trim())throw new Os("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(e.isAbsolute(o))throw new Os("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=e.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await x.stat(i)).isDirectory())throw new Os(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof Os)throw e;throw new Os(`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((t,o)=>{let i="",c="",l=!1;const d=r.length>0?Fe([n,...r]):n,u=setTimeout(()=>{if(!l){m.kill("SIGTERM");const e=Date.now()-a;o(new Os(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",i,c,e))}},s),m=A(d,[],e);m.stdout?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>xs)return c="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void m.kill("SIGTERM");i+=t}catch(e){c+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,m.kill("SIGTERM")}}),m.stderr?.on("data",e=>{try{const t=e.toString();if(c.length+t.length>Is)return void(c+="\n[Error output truncated: too large]");c+=t}catch(e){c+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),m.on("close",(e,n)=>{l=!0,clearTimeout(u);const r=Date.now()-a;0===e?t({stdout:i.trim(),stderr:c.trim(),exitCode:e,signal:n,duration:r}):o(new Os(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,i.trim(),c.trim(),r))}),m.on("error",e=>{l=!0,clearTimeout(u);const t=Date.now()-a;o(new Os(`Failed to start command: ${e.message}`,"START_FAILED",null,null,i.trim(),c.trim(),t))})})}catch(e){if(e instanceof Os)throw e;throw new Os(`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")}bt(),__name(executeShellCommand,"executeShellCommand"),bt(),__name(formatShellCommandResult,"formatShellCommandResult");var Ls={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=Ns.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${pe.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${pe.cross} Error: ${e.message}`}return`${pe.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}bt(),bt(),__name(think,"think");var _s={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"string"==typeof e.todos?e.todos:JSON.stringify(e.todos)}bt(),bt(),__name(todoWrite,"todoWrite");var Ms={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};async function askUserQuestion(e,t){if(!e.questions||0===e.questions.length)return JSON.stringify({error:"No questions provided"});for(let t=0;t<e.questions.length;t++){const n=e.questions[t];if(!n.question?.trim()||!n.header?.trim()||!n.options)return JSON.stringify({error:`Question ${t+1} is missing required fields (question, header, options)`});if(n.options.length<2||n.options.length>4)return JSON.stringify({error:`Question ${t+1} must have 2-4 options`});for(const e of n.options)if(!e.label?.trim()||!e.description?.trim())return JSON.stringify({error:`Question ${t+1} has an option with missing label or description`});if(n.header.length>12)return JSON.stringify({error:`Question ${t+1} header exceeds maximum length of 12 characters`})}if(!t?.onQuestionRequest)return JSON.stringify({error:"Question request callback not available"});if(t.abortSignal?.aborted)return JSON.stringify({error:"Interrupted by user"});try{const n=await t.onQuestionRequest(e);return t.abortSignal?.aborted?JSON.stringify({error:"Interrupted by user"}):JSON.stringify(n)}catch(e){return e instanceof Error?JSON.stringify({error:e.message}):JSON.stringify({error:"Failed to get user response"})}}function isErrorResponse(e){return"error"in e&&"string"==typeof e.error}function formatOutput6(e){const{result:t,params:n}=e;if(isErrorResponse(t))return`Error: ${t.error}`;if(!t.answers||0===t.answers.length)return"User declined to answer questions";const r=t.answers.filter(e=>e.selectedOptions&&Array.isArray(e.selectedOptions)&&e.selectedOptions.length>0);if(0===r.length)return"User declined to answer questions";const o=[];return r.forEach(e=>{let t=`Question ${e.questionIndex+1}`;n?.questions?.[e.questionIndex]&&(t=n.questions[e.questionIndex].question||t);const r=e.selectedOptions.join(", ");o.push(`${t} → ${r}`)}),o.join("\n")}bt(),bt(),__name(askUserQuestion,"askUserQuestion"),bt(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var Us={name:"ask_user_question",description:'Use this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- Users will always be able to select "Type something" to provide custom text input\n- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label\n- Use multiSelect: true to allow multiple answers to be selected for a question',acceptsCallbacks:!0,input_schema:{type:"object",properties:{questions:{type:"array",description:"Questions to ask the user",items:{type:"object",properties:{question:{type:"string",description:"The complete question to ask the user. Should be clear, specific, and end with a question mark."},header:{type:"string",description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'},options:{type:"array",description:'The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Type something" option, that will be provided automatically.',items:{type:"object",properties:{label:{type:"string",description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."},description:{type:"string",description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}},required:["label","description"]}},multiSelect:{type:"boolean",description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."}},required:["question","header","options"]}}},required:["questions"]},execute:__name(async(e,t)=>{const n=await askUserQuestion(e,{onQuestionRequest:t?.onQuestionRequest,abortSignal:t?.abortSignal});try{return formatOutput6({result:JSON.parse(n),params:e})}catch{return n}},"execute")};bt(),bt();var js=u.object({port:u.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:u.number().int().positive().optional()}).refine(e=>void 0!==e.port&&void 0===e.pid||void 0===e.port&&void 0!==e.pid,{message:"Exactly one of port or pid must be provided"}),Bs=class extends Error{static{__name(this,"KillshellError")}code;pid;port;constructor(e,t,n,r){super(e),this.name="KillshellError",this.code=t,this.pid=n,this.port=r}};function isUnixLike(){const e=process.platform;return"darwin"===e||"linux"===e}function isWindows(){return"win32"===process.platform}async function executeCommand(e,t){return new Promise((n,r)=>{const o=A(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let s="",a="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{a+=e.toString()}),o.on("close",e=>{0===e?n(s.trim()):r(new Error(a.trim()||s.trim()))}),o.on("error",e=>{r(e)})})}async function findPidByPort(e){try{if(isUnixLike()){const t=(await executeCommand("lsof",["-ti",`:${e}`,"-sTCP:LISTEN"])).trim().split("\n")[0];if(!t||!/^\d+$/.test(t))return null;const n=parseInt(t,10);return isNaN(n)?null:n}if(isWindows()){const t=(await executeCommand("netstat",["-ano"])).split("\n");for(const n of t){const t=n.trim();if(!t)continue;const r=t.split(/\s+/);if(r.length<5)continue;if("LISTENING"!==r[3])continue;const o=r[1].match(/:(\d+)$/);if(!o)continue;const s=parseInt(o[1],10);if(isNaN(s)||s!==e)continue;const a=parseInt(r[r.length-1],10);if(!isNaN(a))return a}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new Bs(`No process found listening on port ${e.port}`,"NO_PROCESS_FOUND",void 0,e.port);t=r}else void 0!==e.pid&&(t=e.pid);if(!t)throw new Bs("Unable to determine target process","INVALID_TARGET");const r=await getProcessName(t);try{await killProcess(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new Bs(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}function formatKillshellResult(e){const t=[];return t.push(`${pe.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}bt(),__name(isUnixLike,"isUnixLike"),__name(isWindows,"isWindows"),__name(executeCommand,"executeCommand"),__name(findPidByPort,"findPidByPort"),__name(getProcessName,"getProcessName"),__name(isProcessAlive,"isProcessAlive"),__name(waitForProcessTermination,"waitForProcessTermination"),__name(killProcess,"killProcess"),__name(executeKillshell,"executeKillshell"),bt(),__name(formatKillshellResult,"formatKillshellResult");var zs={name:"kill_shell",description:"Terminates processes by port number or PID, useful for freeing occupied ports or stopping stuck development servers. Attempts graceful termination first (SIGTERM/taskkill), then forces if needed. Use with caution - terminating system processes may cause instability.",acceptsCallbacks:!0,input_schema:{type:"object",properties:{port:{type:"number",description:"Port number (1-65535) to free by terminating the listening process. Automatically finds and kills the process using this port."},pid:{type:"number",description:"Process ID to terminate directly. Use when you know the exact PID to kill."}},required:[]},execute:__name(async(e,t)=>{try{const n=js.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?`${pe.cross} Permission denied: Process termination was not approved`:formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`${pe.cross} Error: ${e.message}`:`${pe.cross} Error: Unknown error occurred while killing process`}},"execute")};bt(),bt(),bt(),bt(),bt(),vt(),bt(),bt();var Ws=["explore","plan","review","general"],Hs=[{name:"explore",description:"Use this for codebase exploration, search, or understanding tasks that require multiple file operations",tools:"glob, grep, read_file, read_directory, read_multiple_files, think",systemPrompt:'You are a codebase explorer. Your prompt will specify depth level and what information is needed.\n\nTOOLS AVAILABLE:\n- glob: Find files by patterns\n- grep: Search code for keywords/patterns\n- read_file: Read specific files\n- read_directory: List directory contents\n- read_multiple_files: Read many files efficiently\n- think: Reason through findings\n\nDEPTH LEVELS:\n- quick: 1-2 files, answer the specific question only\n- medium: 3-5 files, understand the main component and context\n- thorough: 10+ files, comprehensive understanding\n\nINSTRUCTIONS:\n1. Look for "Depth: [level]" in the prompt (usually on line 2)\n2. Identify exactly what information is needed (specified in the prompt)\n3. Use only the file operations needed to get that information\n4. Stop when you have the requested information\n\nIf no depth level specified, default to "quick".\n\nRESPONSE FORMAT:\n- Provide exactly what was requested\n- Include relevant file paths and code sections\n- Match your depth to the specified level\n- Stop when done - don\'t over-explore',location:"personal",filePath:"__builtin__"}];function isReservedAgentName(e){return!!e&&Ws.includes(e.toLowerCase())}function getRootAgentDir(){return t.join(g.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await x.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await x.readFile(o,"utf-8"),{data:a,content:i}=De(s),c=a.name||r.replace(".md","");if(isReservedAgentName(c))return null;let l=a.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:c,description:a.description||"",tools:l,systemPrompt:i.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,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(isReservedAgentName,"isReservedAgentName"),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents"),bt(),vt(),Ut(),kn(),Lt(),bt();var Gs=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)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=1.1*estimateTextTokens(JSON.stringify(n.input)));else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));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.max(0,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 checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?(estimateTokens(e),"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."):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 sleep(e){const{delay:t,signal:n}=e;return new Promise((e,r)=>{if(n?.aborted)return r(new Error("Interrupted by user"));const o=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(o),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(function getOversizedOutputError(e,t){return"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."},"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),bt(),__name(sleep,"sleep"),bt(),fn();var qs=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${pe.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${pe.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${pe.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${pe.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}};function getEnterpriseMemoryPath(){switch(m.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return e.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const t=m.homedir();return e.join(t,".commandcode","AGENTS.md")}function getProjectMemoryPaths(t){return[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:y(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(y(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:y(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return y(e)&&k(e).isFile()?await P.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}async function processImports(t,n,r=0,o=5){if(r>=o)return t;const s=[],a=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(s.push(e),`__CODE_BLOCK_${s.length-1}__`)),i=Array.from(a.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let c=a;for(const t of i){const s=t[1];let a=s;s.startsWith("~/")?a=e.join(m.homedir(),s.slice(2)):e.isAbsolute(s)||(a=e.resolve(e.dirname(n),s));const i=await loadMemoryFile(a);if(i){const e=await processImports(i,a,r+1,o);c=c.replace(t[0],`\n# Imported from ${s}\n${e}\n`)}}return c=c.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>s[parseInt(t)]),c}async function loadAllMemories(t,n){const r=new Map,o=getEnterpriseMemoryPath();if(y(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const s=getUserMemoryPath();if(y(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const a=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of a)if(y(e)){const t=await loadMemoryFile(e);if(t){const n=await processImports(t,e);r.set(e,n)}break}if(n&&n.length>0)for(const o of n){const n=e.isAbsolute(o)?e.dirname(o):e.dirname(e.resolve(t,o));if(n.startsWith(t)&&n!==t){const o=[];let s=n;for(;s.startsWith(t)&&s!==t;)o.push(s),s=e.dirname(s);for(const t of o.reverse()){const n=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of n)if(y(e)&&!r.has(e)){const t=await loadMemoryFile(e);if(t){const n=await processImports(t,e);r.set(e,n)}break}}}}return r}async function openInEditor(t){const n=process.env.EDITOR||process.env.VISUAL||"code",r=e.dirname(t);return y(r)||await P.mkdir(r,{recursive:!0}),y(t)||await P.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const o=A(n,[t],{stdio:"inherit",shell:!0});o.on("exit",t=>{0===t?e():r(new Error(`Editor exited with code ${t}`))}),o.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),r(e)})})}async function initProjectMemory(t){const n=e.join(t,"AGENTS.md");return y(n)||await P.writeFile(n,"# 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"),n}async function getMemoryContent(t){try{const n=process.cwd(),r=await loadAllMemories(n,t);if(0===r.size)return null;const o=[],s=getEnterpriseMemoryPath(),a=getUserMemoryPath(),i=[e.join(n,"AGENTS.md"),e.join(n,".commandcode","AGENTS.md")];r.has(s)&&o.push(`# Memory from: ${s}\n\n${r.get(s)}`),r.has(a)&&o.push(`# Memory from: ${a}\n\n${r.get(a)}`);for(const e of i)if(r.has(e)){o.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===s||e===a||i.includes(e)||o.push(`# Memory from: ${e}\n\n${t}`);return o.join("\n\n---\n\n")}catch(e){return null}}bt(),vt(),__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"),bt(),vt(),ir(),fn();var Vs=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(g.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Oe(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const n=_SessionManager.getCurrentProjectDirName();this.projectPath=t.join(_SessionManager.getProjectsBasePath(),n),this.sessionFilePath=t.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=v("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await x.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"project_init_failed"}),context:{component:Bn.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await x.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{if(0===e.length)return;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 x.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 n=e||this.sessionId,r=t.join(this.projectPath,`${n}.jsonl`);try{const e=(await x.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let n=0;for(const r of e)try{const e=JSON.parse(r);"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){n++,console.error("Error parsing session line:",e)}return{messages:t,corruptedLines:n,totalLines:e.length}}catch(e){return console.error("Error loading messages:",e),{messages:[],corruptedLines:0,totalLines:0}}}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=ss(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=ss(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 n=e||this.sessionId,r=t.join(this.projectPath,`${n}.jsonl`);try{const e=(await x.readFile(r,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);t.push(e)}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading session:",e),[]}}convertToFeedEntries(e){return e.map(e=>{const t={id:e.id,timestamp:new Date(e.timestamp).getTime(),role:e.role,metadata:e.metadata};return"object"==typeof e.content&&null!==e.content&&"input"in e.content?{...t,input:e.content.input,output:e.content.output,...e.content.name?{name:e.content.name}:{},...e.content.command?{command:e.content.command}:{}}:{...t,input:"string"==typeof e.content?e.content:JSON.stringify(e.content)}})}convertToAnthropicMessages(e){return e.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>{let t;if(t="string"==typeof e.content?e.content:e.content&&"object"==typeof e.content?e.content.input||JSON.stringify(e.content):"","user"===e.role&&e.metadata?.fileReferences)try{t=reconstructContent(t,e.metadata.fileReferences)}catch(e){console.error("Failed to reconstruct file content from session:",e)}return{role:e.role,content:t}})}static async isProjectInitialized(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return(await x.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await x.mkdir(r,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),n=t.join(_SessionManager.getProjectsBasePath(),e);try{try{await x.access(n)}catch{return[]}const e=(await x.readdir(n)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),r=[];for(const o of e){const e=o.replace(".jsonl",""),s=t.join(n,o);try{const t=await x.stat(s),o=(await x.readFile(s,"utf-8")).trim().split("\n").filter(e=>e.trim());if(o.length>0){let s="",a="";const i=JSON.parse(o[0]);i.gitBranch&&(a=i.gitBranch);for(const e of o){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)s=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){s=e.text;break}}else t.content?.input&&(s=t.content.input);if(s)break}}const c=await _SessionManager.loadSessionMetaForId(e,n),l=c?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:s||"No messages",title:l||void 0,messageCount:o.length,projectPath:n,gitBranch:a||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return r.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const n=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await x.writeFile(n,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=t.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await x.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await x.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await x.readFile(this.getMetaFilePath(),"utf-8");return JSON.parse(e)}catch(e){return e instanceof SyntaxError&&dlog("Session",`Corrupt session meta file: ${this.getMetaFilePath()}`),null}}async saveSessionMeta(e){try{const t={...await this.loadSessionMeta(),...e};await x.writeFile(this.getMetaFilePath(),JSON.stringify(t,null,2))}catch(e){dlog("Session",`Failed to save session meta: ${e}`)}}async saveSessionTitle(e){await this.saveSessionMeta({title:e})}async loadSessionTitle(){const e=await this.loadSessionMeta();return e?.title||null}static async loadSessionMetaForId(e,n){const r=t.join(n,`${e}.meta.json`);try{const e=await x.readFile(r,"utf-8");return JSON.parse(e)}catch(e){return null}}getCheckpointsFilePath(){return t.join(this.projectPath,`${this.sessionId}.checkpoints.jsonl`)}async saveSnapshot(e){const{snapshot:t,isUpdate:n}=e,r=this.getCheckpointsFilePath();try{await this.initializeProject();const e={type:"file-history-snapshot",messageId:t.messageId,snapshot:t,isSnapshotUpdate:n};if(n){let n=[];try{n=(await x.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const o=n.findIndex(e=>e.messageId===t.messageId);-1!==o?n[o]=e:n.push(e);const s=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await x.writeFile(r,s)}else await x.appendFile(r,JSON.stringify(e)+"\n")}catch(e){console.error("Failed to save checkpoint snapshot:",e)}}async loadSnapshots(){const e=this.getCheckpointsFilePath();try{const t=(await x.readFile(e,"utf-8")).trim().split("\n").filter(e=>e.trim()),n=[];for(const e of t)try{const t=JSON.parse(e);"file-history-snapshot"===t.type&&n.push(t.snapshot)}catch{}return n}catch{return[]}}async deleteSnapshotsAfter(e){const{messageId:t,inclusive:n=!1}=e,r=this.getCheckpointsFilePath();try{const e=(await x.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),o=e.findIndex(e=>e.messageId===t);if(-1===o)return;const s=(n?e.slice(0,o):e.slice(0,o+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await x.writeFile(r,s)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let o="";if("string"==typeof r.message.content)o=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(o+=e.text);return{messageId:r.meta.messageId||crypto.randomUUID(),content:o}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return r.length>0&&await this.saveMessages(r),r}};wn();var Ks=new qs("AgentExecutor");function agentToTool(t,n){const{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}=n;return{name:t.name,description:t.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object"}}},required:["messages"]},execute:__name(async(n,i)=>{let c=null;const l=Date.now();let d=null;try{let u=getAvailableTools(t,{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}),m=Date.now();const g=10,p=[];if(i?.onFeedUpdate){const e=ss(t.name,n);c=Qo({name:t.name,input:e}),i.onFeedUpdate(c)}d=setInterval(()=>{if(i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{...c.metadata,elapsedSeconds:t}},i.onFeedUpdate(c)}},1e3);const h=await getConfiguredProvider(),f=await isOAuthEnforced();let y;h===ut.ANTHROPIC&&(y=await Nt.getValidAccessToken(),validateOAuthToken({token:y,provider:h}));const E=getApiBaseUrl(),w=new ao({baseUrl:E});let b=0;const S=[];let k=n?.messages;if("string"==typeof k)try{k=JSON.parse(k)}catch(e){k=[]}if(Array.isArray(k)&&k.length>0)for(const e of k)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&S.push({role:"user",content:t})}const C={stream:!0,messages:S,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:u,model:`anthropic:${getConfiguredModel()}`},v=await isTasteLearningEnabled(),T={[it.PROJECT_SLUG]:Vs.getCurrentProjectDirName(),[it.TASTE_LEARNING]:v.toString(),[it.INTERNAL_TEAM_FLAG_HEADER]:f.toString()};y&&(T[it.OAUTH_TOKEN]=`Bearer ${y}`);const A=getEnvironmentContext(),P=await getMemoryContent([]),x=crypto.randomUUID();let I="",D=!0;const R=__name(()=>{Ks.debug("[Agent] Abort signal triggered, stopping immediately"),D=!1,d&&(clearInterval(d),d=null)},"abortHandler");i?.abortSignal&&i.abortSignal.addEventListener("abort",R);try{for(;D;){if(i?.abortSignal?.aborted)throw Ks.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:w,body:{mode:"custom-agent",config:A,memory:P,threadId:x,params:{...C,messages:S}},headers:T,abortSignal:i?.abortSignal,onTextDelta:__name(e=>{b+=estimateTokens(e);const t=Date.now();if(i?.onFeedUpdate&&c&&t-m>=g){const e=Math.floor((t-l)/1e3);c={...c,metadata:{...c.metadata,tokensUsed:b,elapsedSeconds:e}},i.onFeedUpdate(c),m=t}},"onTextDelta")});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(b=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if(I=t.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(t,i):t.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===n.length){const e=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);e.length>0&&S.push({role:"assistant",content:e}),D=!1;break}const r=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);r.length>0&&S.push({role:"assistant",content:r});const o=[],s=new Set;let a=!1;for(const t of n){if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{if(["edit_file","write_file","create_file","delete_file","shell_command"].includes(t.name)&&i?.onPermissionRequest){if(d&&(clearInterval(d),d=null),!await i.onPermissionRequest(t.name,n)){Ks.debug(`Permission denied for tool: ${t.name}`),a=!0;break}d=setInterval(()=>{if(i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{...c.metadata,elapsedSeconds:t}},i.onFeedUpdate(c)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let o=!1;const s=["path","file_path","absolutePath","filePath","directory","folder"];for(const t of s)if(t in r&&"string"==typeof r[t]){const n=r[t];if(!e.isAbsolute(n)){const s=e.resolve(process.cwd(),n);r[t]=s,o=!0,Ks.debug(`Converted '${t}': '${n}' -> '${s}'`)}}"paths"in r&&Array.isArray(r.paths)&&(r.paths=r.paths.map(t=>"string"!=typeof t||e.isAbsolute(t)?t:(o=!0,e.resolve(process.cwd(),t)))),o?(n=r,Ks.debug(`Resolved input for ${t.name}: ${ss(t.name,n)}`)):Ks.debug(`No path resolution needed for ${t.name}: ${ss(t.name,n)}`)}if(i?.onFeedUpdate&&c){const e=ss(t.name,n);p.push({name:t.name,input:e}),p.length>3&&p.shift();const r=Date.now(),o=Math.floor((r-l)/1e3);c={...c,metadata:{isAgent:!0,status:"running",startTime:l,tokensUsed:b,elapsedSeconds:o,recentTools:[...p]}},Ks.debug(`Updating agent with recentTools (${p.length} tools): ${JSON.stringify(p)}`),i.onFeedUpdate(c)}const r=await executeTool(t.name,n,{abortSignal:i?.abortSignal});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");const u=checkToolOutputTokensLimit(r,t.name);if(o.push({type:"tool_result",tool_use_id:t.id,content:u}),s.add(t.id),i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{isAgent:!0,status:"running",startTime:l,tokensUsed:b,elapsedSeconds:t,recentTools:[...p]}},i.onFeedUpdate(c)}Ks.debug(`Tool executed successfully: ${t.name}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";o.push({type:"tool_result",tool_use_id:t.id,content:`Error: ${n}`,is_error:!0}),s.add(t.id),Ks.error(`Tool execution failed: ${t.name} - ${n}`)}}if(a){const e=S[S.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?s.has(e.id):"text"===e.type);t.length>0?e.content=t:S.pop()}D=!1;break}const u=[...o];S.push({role:"user",content:u})}}finally{i?.abortSignal&&i.abortSignal.removeEventListener("abort",R)}if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&c){const e=Date.now(),t=(e-l)/1e3;c={...c,output:I||"DONE",metadata:{isAgent:!0,status:"done",startTime:l,endTime:e,tokensUsed:b,elapsedSeconds:t}},i.onFeedUpdate(c)}return I||"DONE"}catch(e){if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&c){const t=Date.now(),n=(t-l)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||i?.abortSignal?.aborted;c={...c,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:l,endTime:t,tokensUsed:c?.metadata?.tokensUsed||0,elapsedSeconds:n}},i.onFeedUpdate(c)}throw e}},"execute")}}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=t;let a=[];if("*"===e.tools)a=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=s[e];if(!t&&o.has(e)&&(t=e),t){const e=o.get(t);if(e)a.push(e);else{const e=r.find(e=>e.name===t);e&&a.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=s[t];if(!e&&o.has(t)&&(e=t),e){const t=o.get(e);if(t)a.push(t);else{const t=r.find(t=>t.name===e);t&&a.push(t)}}}return a}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:s}=e;let a=null;for(let e=0;e<5;e++){if(o?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:ct.ALPHA.GENERATE,signal:o,headers:r}),a=Ne.fromReadableStream(e);s&&a.on("text",s);let i=null;a.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await a.finalMessage();if(i)throw i;return c}catch(t){if(a=t,o?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Ks.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:o})}}throw a||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 Zr&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof eo||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 Zr&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof eo||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="";const r=e.content;for(const e of r)if("text"===e.type)n+=e.text;else if("server_tool_use"===e.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const{message:n,isError:o}=Po({serverToolBlock:e,contentBlocks:r}),s=ss(e.name,e.input),a={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:s,output:o?Xo(n):n};t.onFeedUpdate(a)}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 Js=new Map,Ys=null;function initializeAgentManager(e){Ys=e}async function loadAgentTools(){if(!Ys)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Js.clear();for(const e of Hs){const t=agentToTool(e,Ys);Js.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Ys);Js.set(t.name,t)}}async function getAgentTools(){return 0===Js.size&&await loadAgentTools(),Array.from(Js.values())}async function getAgentTool(e){return 0===Js.size&&await loadAgentTools(),Js.get(e)}function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,o=e.join(r,".commandcode","taste"),s=e.normalize(e.resolve(r,n)),a=e.normalize(o);return s.startsWith(a)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),o=e.normalize(e.join(m.homedir(),".commandcode","taste"));let s=null;if(n.startsWith(r)?s=r:n.startsWith(o)&&(s=o),!s)return{isTaste:!1};if(!n.endsWith("taste.md"))return{isTaste:!1};const a=e.relative(s,n).split(e.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"),bt(),vt(),__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"),ir();var Qs=[is,fs,ws,Ss,As,Ds,Fs,Ls,_s,Ms,Us,zs],Zs=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],Xs=new Map(Qs.map(e=>[e.name,e])),ea=new Set([...Qs.map(e=>e.name),...Zs.map(e=>e.name)]);function isAgentTool(e){return!ea.has(e)}async function executeTool(e,t,n){let r=Xs.get(e);if(r||(r=await getAgentTool(e)),!r){const t=await getAgentTools(),n=[...Array.from(Xs.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: ",""))}const o=trackToolStart({toolName:e});try{let s;return s=(!Xs.has(e)||!0===r.acceptsCallbacks)&&n?await r.execute(t,n):await r.execute(t),o.end({status:"success"}),s}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message){const t=sanitizeErrorForTelemetry({error:e,label:"tool_interrupted"});throw o.end({status:"error",error:t}),e}if(e instanceof Error){const t=sanitizeErrorForTelemetry({error:e,label:"tool_error"});return o.end({status:"error",error:t}),`Error: ${e.message}`}return o.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(){return[...Qs.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})),...Zs]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var ta={};Qs.forEach(e=>{ta[e.name]=toPascalCase(e.name)}),Zs.forEach(e=>{ta[e.name]=toPascalCase(e.name)});var na={};function parseEmbeddedErrorJSON(e){const t=e.indexOf("{");if(-1===t)return null;try{const n=JSON.parse(e.slice(t));if(n?.error?.message){const r=e.slice(0,t).trim();return{status:/^\d+$/.test(r)?Number(r):null,type:n.error.type||null,message:n.error.message}}}catch{}return null}function parseErrorLine(e){try{const t=JSON.parse(e);if("error"===t?.type&&t?.error?.type&&t?.error?.message)return{type:t.error.type,message:t.error.message}}catch{}return null}function interceptStreamErrors(e){const{responseStream:t}=e;let n=null,r="";const o=new TextDecoder,s=new TransformStream({transform(e,t){const s=o.decode(e,{stream:!0});r+=s;const a=r.split("\n");r=a.pop()??"";for(const e of a){const r=e.trim();if(!r){t.enqueue((new TextEncoder).encode(e+"\n"));continue}const o=parseErrorLine(r);if(o)return n=o,void t.error(new Error(`Error: Stream error: ${o.type} - ${o.message}`));t.enqueue((new TextEncoder).encode(e+"\n"))}},flush(e){const t=r.trim();if(t){const o=parseErrorLine(t);if(o)return n=o,void e.error(new Error(`Error: Stream error: ${o.type} - ${o.message}`));e.enqueue((new TextEncoder).encode(r))}}});return{stream:t.pipeThrough(s),getStreamError:__name(()=>n,"getStreamError")}}Object.entries(ta).forEach(([e,t])=>{na[t]=e}),initializeAgentManager({clientTools:Qs,serverTools:Zs,toolsMap:Xs,displayNameToToolName:na}),bt(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors"),ir(),vt(),Lt(),wn(),kn(),bt(),vt(),Ut(),fn(),bt();var ra=new class extends Le{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;get observerHasRun(){return this._observerHasRun}markObserverRun(){this._observerHasRun=!0}get importHasStarted(){return this._importHasStarted}markImportStarted(){this._importHasStarted=!0}get learningComplete(){return this._learningComplete}markLearningComplete(){this._learningComplete=!0,this.emit("learning-complete")}addEvent(e){const{type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d}=e,u={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d};this.events.unshift(u),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",u)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}};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}),s=new Map(r.map(e=>[e.text,e.confidence])),a=[],i=[],c=[];return o.forEach(e=>{const t=s.get(e.text);void 0===t?a.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:a,upgraded:i,downgraded:c}}bt(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings"),wn(),kn(),ir();var oa=new qs("LearningAgent"),sa=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=3;request;projectRoot;tasteDir;sessionId;abortSignal;constructor(t){this.request=t.request,this.sessionId=t.sessionId,this.projectRoot=t.projectRoot,this.tasteDir=e.join(t.projectRoot,".commandcode","taste")}updateRequest(e){this.request=e}setAbortSignal(e){this.abortSignal=e}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)return this.pendingMessages=t,{success:!0};if(0===t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length)return{success:!0};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)}return{success:!0}}catch(e){const n=e instanceof Error?e.message:String(e);return dlog(`[LearningAgent] ERROR: ${n}`),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learning_pass_failed"}),context:{component:Bn.LEARNING_AGENT,heading:"Learning pass failed"}}),ra.addEvent({type:"error",message:"learning pass failed",details:n}),this.lastProcessedMessageIndex=t.length-1,{success:!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)];ra.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),s=t.length-this.lastProcessedMessageIndex-1,a=Math.max(20,s),i=Math.max(0,t.length-a),c=t.slice(i);let l=0,d=!1;dlog(`[LearningAgent] analyzing ${s} new messages for patterns`);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){const e=await this.callLearningAPI({conversation:u}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.name).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&oa.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||ra.addEvent({type:"no_learnings",message:"no changes to taste"}),ra.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{this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",s="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(s=String(e.filePath||e.file_path||""),s)try{o=await h.promises.readFile(s,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const a=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&s)try{i=await h.promises.readFile(s,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=s.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:o,newText:i});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{ra.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{ra.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{ra.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:a})}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(t){const{toolName:n,input:r}=t,o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(!o||!r[o])return;const s=String(r[o]);if(e.isAbsolute(s))throw new Error(`Security: ${n} received absolute path. Only taste-relative paths are allowed (e.g., ".commandcode/taste/cli/taste.md" or ".commandcode/taste/taste.md"). Attempted: ${s}`);const a=e.normalize(s);if(a.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${s}`);const i=e.join(this.tasteDir,a);if(!e.normalize(i).startsWith(this.tasteDir))throw new Error(`Security: ${n} can only access files within .commandcode/taste/. Attempted: ${s}`)}adjustPathsForTaste(t){const{toolName:n,input:r}=t,o={...r},s={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(s&&o[s]){const t=String(o[s]);let r;const a="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)&&t.startsWith(this.tasteDir))if(a){if(!this.isValidTasteFilePath(t))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${t}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);r=t}else r=t;else{if(e.isAbsolute(t))throw new Error(`Invalid path: Absolute path outside taste directory: ${t}`);const n=e.normalize(t);if(n.startsWith(".."))throw new Error(`Security: Path traversal attempt detected: ${t}`);if(r=n.startsWith(".commandcode/taste")||n.startsWith(".commandcode"+e.sep+"taste")?n.replace(/^\.commandcode[/\\]taste/,this.tasteDir):e.join(this.tasteDir,n),r=e.normalize(r),!r.startsWith(this.tasteDir))throw new Error(`Security: Resolved path escapes taste directory: ${t} -> ${r}`);if(a&&!this.isValidTasteFilePath(r))throw new Error(`Invalid adjusted path: ${r}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}o[s]=r}return o}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 t=e.join(this.tasteDir,"taste.md");h.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!h.existsSync(t))return!1;const n=h.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let o=n;for(const t of r){const n=t.name.toLowerCase().replace(/\s+/g,"-"),r=e.join(this.tasteDir,n),s=e.join(r,"taste.md");h.mkdirSync(r,{recursive:!0}),ra.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const a=`# ${t.name}\n${t.learnings.join("\n")}\n`;h.writeFileSync(s,a,"utf-8");const i=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;o=o.replace(t.fullSection,i)}return h.writeFileSync(t,o,"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(t){const{dir:n,prefix:r}=t,o=h.readdirSync(n,{withFileTypes:!0});let s="";for(let t=0;t<o.length;t++){const a=o[t],i=t===o.length-1,c=i?"└── ":"├── ";if(a.isDirectory()){s+=`${r}${c}${a.name}/\n`;const t=r+(i?" ":"│ ");s+=await this.buildTree({dir:e.join(n,a.name),prefix:t})}else if("taste.md"===a.name){const t=(h.readFileSync(e.join(n,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;s+=`${r}${c}${a.name} (${t} learnings)\n`}else s+=`${r}${c}${a.name}\n`}return s}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===ut.ANTHROPIC&&(o=await Nt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[it.PROJECT_SLUG]:Vs.getCurrentProjectDirName(),[it.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[it.OAUTH_TOKEN]=`Bearer ${o}`);const a=await this.getTasteTools(),i=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${i})`);const c={conversation:t,tools:a,model:i,threadId:this.sessionId};let l=0,d=null;for(;l<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:ct.ALPHA.TASTE.LEARN,body:c,headers:s,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),l++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${d.message}`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_client_error"}),context:{component:Bn.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(l>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:Bn.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":l}}),d;const n=1e3*Math.pow(2,l);dlog(`[LearningAgent] retrying API call (${l}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw d||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return h.existsSync(r)}};bt(),vt(),Ut(),Lt(),wn(),kn(),fn();var aa="claude-haiku-4-5-20251001",ia=class{static{__name(this,"CompactAgent")}request;sessionId;maxApiRetries=3;constructor(e){this.request=e.request,this.sessionId=e.sessionId}updateRequest(e){this.request=e}async compactMessages(e){const{messages:t}=e;dlog(`[CompactAgent] compacting ${t.length} messages`);try{const e=await this.callCompactAPI({messages:t});return dlog(`[CompactAgent] compaction complete: ${e.summary.length} chars`),e}catch(e){throw dlog(`[CompactAgent] ERROR: ${e instanceof Error?e.message:String(e)}`),e}}async callCompactAPI(e){const{messages:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===ut.ANTHROPIC&&(o=await Nt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[it.PROJECT_SLUG]:Vs.getCurrentProjectDirName(),[it.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[it.OAUTH_TOKEN]=`Bearer ${o}`);const a=t.map(e=>{const t=e.role;let n="";return"string"==typeof e.content?n=e.content:Array.isArray(e.content)&&(n=e.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("\n")),`[${t}]: ${n}`}).join("\n\n"),i={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],system:"Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\nThis summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.\n\nBefore providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:\n\n1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:\n - The user's explicit requests and intents\n - Your approach to addressing the user's requests\n - Key decisions, technical concepts and code patterns\n - Specific details like:\n - file names\n - full code snippets\n - function signatures\n - file edits\n - Errors that you ran into and how you fixed them\n - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.\n\nYour summary should include the following sections:\n\n1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail\n2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.\n3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.\n4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.\n6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.\n7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.\n8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.\n9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.\n If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.\n\nHere's an example of how your output should be structured:\n\n<example>\n<analysis>\n[Your thought process, ensuring all points are covered thoroughly and accurately]\n</analysis>\n\n<summary>\n1. Primary Request and Intent:\n [Detailed description]\n\n2. Key Technical Concepts:\n - [Concept 1]\n - [Concept 2]\n - [...]\n\n3. Files and Code Sections:\n - [File Name 1]\n - [Summary of why this file is important]\n - [Summary of the changes made to this file, if any]\n - [Important Code Snippet]\n - [File Name 2]\n - [Important Code Snippet]\n - [...]\n\n4. Errors and fixes:\n - [Detailed description of error 1]:\n - [How you fixed the error]\n - [User feedback on the error if any]\n - [...]\n\n5. Problem Solving:\n [Description of solved problems and ongoing troubleshooting]\n\n6. All user messages:\n - [Detailed non tool use user message]\n - [...]\n\n7. Pending Tasks:\n - [Task 1]\n - [Task 2]\n - [...]\n\n8. Current Work:\n [Precise description of current work]\n\n9. Optional Next Step:\n [Optional Next step to take]\n\n</summary>\n</example>\n\nPlease provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.\n\nThere may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:\n<example>\n## Compact Instructions\nWhen summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.\n</example>\n\n<example>\n# Summary instructions\nWhen you are using compact - please focus on test output and code changes. Include file reads verbatim.\n</example>",messages:[{role:"user",content:`Please summarize the following conversation.\n\n${a}`}],model:`anthropic:${aa}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let c=0,l=null;for(;c<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${ct.ALPHA.GENERATE} with model: ${aa}`);const e=await this.request.post({endpoint:ct.ALPHA.GENERATE,body:i,headers:s,stream:!0});if(!e)throw new Error("No response stream received");const t=Ne.fromReadableStream(e);let n="",r=null;t.on("text",e=>{n+=e}),t.on("error",e=>{r=e});const o=await t.finalMessage();if(r)throw r;return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:o.usage.input_tokens,output:o.usage.output_tokens}}}catch(e){l=e instanceof Error?e:new Error(String(e)),c++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${l.message}`),l;if(c>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),l;const n=1e3*Math.pow(2,c);dlog(`[CompactAgent] retrying API call (${c}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}throw l||new Error("Compact API call failed")}};async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!y(n))return null;const r=await P.readFile(n,"utf-8"),o=r.trim();return o&&"# Taste (Continuously Learned by CommandCode.ai)"!==o&&"# Taste (Continuously Learned by CommandCode)"!==o?r:null}catch(e){return null}}function extractMessageText(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t="";for(const n of e)"text"===n.type&&(t+=n.text);return t}async function buildAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced(),n={[it.PROJECT_SLUG]:Vs.getCurrentProjectDirName(),[it.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};if(e===ut.ANTHROPIC){const e=await Nt.getValidAccessToken();e&&(n[it.OAUTH_TOKEN]=`Bearer ${e}`)}return n}function hasUserAndAssistantMessage(e){let t=!1,n=!1;for(const r of e)if("user"===r.message.role&&(t=!0),"assistant"===r.message.role&&(n=!0),t&&n)return!0;return!1}async function generateSessionTitle(e){const{messages:t,sessionManager:n,request:r}=e;if(!hasUserAndAssistantMessage(t))return;if(await n.loadSessionTitle())return;let o="",s="";for(const e of t)if(o||"user"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,1e3)),s||"assistant"!==e.message.role||(s=extractMessageText(e.message.content).slice(0,1e3)),o&&s)break;if(!o||!s)return;const a=`You are generating a succinct session title for a coding session based on the provided description.\n\nThe title should be:\n- Clear, concise, and accurately reflect the task\n- No more than 6 words\n- Easy to understand by a general audience\n- Free of unnecessary jargon (use technical terms only if essential)\n- Written in sentence case (capitalize only the first word and proper nouns)\n\nReturn only the title as a plain string, not JSON.\n\nExample titles:\nAdd retry logic to API\nSimplify error handling flow\nClean up unused components\n\nSession description:\n<description>User: ${o}\n\n---\n\nAssistant: ${s}</description>\n\nGenerate the session title now.`,i={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:a}],model:mt,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},c=await buildAuthHeaders(),l=await r.post({endpoint:ct.ALPHA.GENERATE,body:i,headers:c,stream:!0}),d=Ne.fromReadableStream(l);let u="";d.on("text",e=>{u+=e}),await d.finalMessage(),u=u.trim(),u&&(await n.saveSessionTitle(u),dlog("Session",`Title generated: ${u}`))}bt(),vt(),__name(getTasteContent,"getTasteContent"),fn(),bt(),Ut(),Lt(),wn(),kn(),fn(),vt(),__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle");var ca=new qs("ContextEngine"),la=200,da=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;requestInterrupted=!1;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();lastFileContexts=[];titleGenerationInFlight=!1;learningAgent;compactAgent;checkpointManager;constructor(e,t){const n=getApiBaseUrl();this.request=new ao({baseUrl:n}),this.callbacks=e,this.sessionManager=new Vs(t),this.learningAgent=new sa({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new ia({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new ao({baseUrl:e}),this.learningAgent.updateRequest(this.request),this.compactAgent.updateRequest(this.request)}createSessionStoreAdapter(){return{saveSnapshot:__name(async e=>{await this.sessionManager.saveSnapshot(e)},"saveSnapshot"),loadSnapshots:__name(async()=>this.sessionManager.loadSnapshots(),"loadSnapshots"),deleteSnapshotsAfter:__name(async e=>{await this.sessionManager.deleteSnapshotsAfter(e)},"deleteSnapshotsAfter"),getMessageAtIndex:__name(e=>this.sessionManager.getMessageAtIndex({index:e.index,messages:this.messages}),"getMessageAtIndex"),getMessageIndexById:__name(e=>this.sessionManager.getMessageIndexById({messageId:e.messageId,messages:this.messages}),"getMessageIndexById"),truncateMessagesAtIndex:__name(async e=>{const t=await this.sessionManager.truncateMessagesAtIndex({index:e.index,messages:this.messages});this.messages=t},"truncateMessagesAtIndex"),getMessageCount:__name(()=>this.sessionManager.getMessageCount({messages:this.messages}),"getMessageCount")}}setupCheckpointSessionStore(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),this.checkpointManager.runCleanup().catch(()=>{})}async interrupt(e=!1){if(this.requestInterrupted=!0,this.abortController){this.abortController.abort(),this.abortController=null,ca.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)){const n=t.message.content.filter(e=>"tool_use"===e.type),r=[];if(n.length>0){const e=n.map(e=>({type:"tool_result",tool_use_id:e.id,content:"Interrupted by user",is_error:!0}));r.push(...e),ca.debug(`Added tool_result blocks for ${e.length} interrupted tool calls`)}e&&r.push({type:"text",text:"Interrupted by user"}),r.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:r}))}if(e){const e=Bo("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>ca.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n){let r=e,o=[];try{const t=await processFileReferences(e);if(r=t.processedContent,o=t.fileReferences,o.length>0){const e=o.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(r=`${n}\n\n${r}`);const s=Bo(e);t&&t.length>0&&(s.metadata={...s.metadata,images:t}),o&&o.length>0&&(s.metadata={...s.metadata,fileReferences:o}),this.callbacks.onFeedUpdate(s);const a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),r.trim()&&a.push({type:"text",text:r});const i={role:"user",content:a},c=crypto.randomUUID(),l=this.createMessageWithMeta(i,{messageId:c});this.addMessageAndSync(l),this.checkpointManager.createSnapshot({messageId:c}).catch(e=>ca.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,s).catch(e=>ca.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const d=await this.processMessages();return this.triggerTitleGeneration(),d}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){ca.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}triggerTitleGeneration(){this.titleGenerationInFlight||(this.titleGenerationInFlight=!0,generateSessionTitle({messages:this.messages,sessionManager:this.sessionManager,request:this.request}).catch(e=>{dlog("Session",`Title generation failed: ${e instanceof Error?e.message:String(e)}`)}).finally(()=>{this.titleGenerationInFlight=!1}))}async processMessages(){let e="";this.requestInterrupted=!1,this.abortController=new AbortController,this.learningAgent.setAbortSignal(this.abortController.signal);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.checkIfInterrupted(),this.updateContextUsage(o),await this.checkAndCompactIfNeeded();const s=o.content.filter(e=>"tool_use"===e.type),a=o.content.filter(e=>"server_tool_use"===e.type);if(e=a.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===s.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===a.length){const t=Wo(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>ca.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>ca.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=Bo(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>ca.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=Wo(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:s}),{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=Bo(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>ca.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&ca.debug("Request interrupted or insufficient credits"),e}return this.abortController=null,e}getHistory(){return[...this.messages]}async loadSession(e){const{messages:t,corruptedLines:n,totalLines:r}=await this.sessionManager.loadMessages(e);this.messages=t,this.triggerTitleGeneration();try{await this.loadCheckpoints()}catch(t){ca.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return ca.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}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 manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};ca.debug(`Manual compact: ${this.messages.length} messages`);const e=this.contextTokensUsed;return await this.summarizeAndCompact(),{tokensSaved:Math.max(0,e-this.contextTokensUsed),didCompact:!0}}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}}}let o=0;const s=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],a=n.message.role;if(e&&t>=r&&-1!==r)s.push(n);else{if("user"===a){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){o+=estimateTokens(n.message);continue}s.push(n)}else s.push(n)}else if("assistant"===a){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)o+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?s.push({...n,message:{...n.message,content:r}}):o+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&s.push(n)}"user"!==a&&"assistant"!==a&&(o+=estimateTokens(n.message))}}this.messages=s,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,n-o);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:Gs}),{messagesRemoved:t-s.length,tokensSaved:o}}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=Jr.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:ct.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.requestInterrupted||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===ut.ANTHROPIC&&(r=await Nt.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o={tools:e,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},s={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:o,threadId:this.sessionManager.getSessionId()};ca.debug(`calling API (${o.model}, ${this.messages.length} msgs, ${e.length} tools)`);const a=await isTasteLearningEnabled(),i={[it.PROJECT_SLUG]:Vs.getCurrentProjectDirName(),[it.TASTE_LEARNING]:a.toString(),[it.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(i[it.OAUTH_TOKEN]=`Bearer ${r}`),{body:s,headers:i}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++){let r;try{const t=interceptStreamErrors({responseStream:await this.request.post({body:e.body,stream:!0,endpoint:ct.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const o=Ne.fromReadableStream(n);o.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let s=null;o.on("error",e=>{s="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const a=await o.finalMessage();if(s)throw s;return this.callbacks.onRetryUpdate?.(null),a}catch(e){const o=r?.(),s=o?Object.assign(new Error(o.message),{type:o.type,error:{type:o.type,message:o.message}}):e;if(t=s,this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(s))throw trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"non_retryable_api_error"}),context:{component:Bn.CONTEXT_ENGINE,heading:"Non-retryable API error",code:s?.status||s?.statusCode}}),this.formatAPIError(s);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:Bn.CONTEXT_ENGINE,code:s?.status||s?.statusCode,"retry.attempts":10}}),this.formatAPIError(s);trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"generate_retry_attempt"}),context:{heading:"Generate API retry",component:Bn.CONTEXT_ENGINE,code:s?.status||s?.statusCode,"retry.attempt":n+1,"retry.max":10}});const a=Math.min(n,10),i=100*Math.pow(2,a),c=Math.max(i,1e3),l=Math.min(c,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:l,signal:this.abortController?.signal})}}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){const{message:t}=this.extractErrorMessage(e),n=t?.toLowerCase()||"",r="Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")||this.requestInterrupted||this.abortController?.signal.aborted,o="Insufficient credits"===t||n.includes("insufficient credits"),s=e instanceof Xr||401===e?.status||e instanceof eo||403===e?.status,a=e?.type||e?.error?.type,i="rate_limit_error"===a||429===e?.status||n.includes("rate limit"),c="overloaded_error"===a||529===e?.status||n.includes("overloaded");return r||o||s||i||c}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.error?.message){const n=parseEmbeddedErrorJSON(e.error.message);return n?{...n,status:n.status||t}:{status:t,type:e.error.type||null,message:e.error.message}}const n=e?.message;if("string"==typeof n){const e=parseEmbeddedErrorJSON(n);if(e)return{...e,status:e.status||t}}return{status:t,type:e?.type||null,message:e?.message||null}}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.requestInterrupted||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=this.extractErrorMessage(e),n=t.status,r=t.type,o=t.message;dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",o);const s=o?.toLowerCase().includes("insufficient credits");if(s)return new Error("Insufficient credits");const a=o?.toLowerCase().includes("oauth authentication required");if(a)return e;if(e instanceof eo||403===e?.status)return e;if(e instanceof Xr||401===e?.status)return new Error('Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.');const i=getSupportId();let c="";if(o)if(o.includes("Invalid 'Authorization' header"))c='Error: Authentication failed. Run "cmd login" to sign in again.';else{let e=o;for(;e.startsWith("Error: ");)e=e.substring(7);e.includes("Unexpected event order")&&(e="The API returned an error. This may be due to high traffic or a temporary issue.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>la&&(t=t.substring(0,la)+"..."),c=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const s=o.toLowerCase(),a="overloaded_error"===r||s.includes("overloaded"),l="rate_limit_error"===r||s.includes("rate limit");c+=a?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":l?'\n\nYou can wait a moment and try again, or type "continue" to retry.':'\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==i&&(c+=`\nRequest ID: ${i}`)}else if(e.toString){const t=e.toString();c=t.length>la?t.substring(0,la)+"...":t}else c="Error: Unknown error occurred";return new Error(c)}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 s=await this.executeSingleTool(o);t.push({type:"tool_result",tool_use_id:o.id,content:s}),n.add(o.id),isAgentTool(o.name)||this.showToolSuccess(o,s)}catch(e){const r=e instanceof Error?e.message:"Unknown error";"Interrupted by user"===r&&isAgentTool(o.name)?n.add(o.id):(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,onQuestionRequest:this.callbacks.onQuestionRequest,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=ss(e.name,e.input),n={..."edit_file"===e.name?e.input:{},permissionDenied:!0},r=Ho(e.name,t,n),o=Zo(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=ss(e.name,r),s=Ho(e.name,o,n),a=Zo(s,t);this.callbacks.onFeedUpdate(a)}showToolError(e,t){const n=ss(e.name,e.input),r="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,o=Ho(e.name,n,r),s=Zo(o,Xo(t));this.callbacks.onFeedUpdate(s)}processServerToolBlocks(e){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let t="";const n=e.content;for(const e of n)if("text"===e.type)t+=e.text;else if("server_tool_use"===e.type){if(t.trim()){const e=Wo(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:o}=Po({serverToolBlock:e,contentBlocks:n}),s=ss(e.name,e.input),a=Ho(e.name,s),i=Zo(a,o?Xo(r):r);this.callbacks.onFeedUpdate(i)}if(t.trim()){const e=Wo(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:Gs})}async checkAndCompactIfNeeded(){const e=Math.floor(Gs*yt.TIER_1_THRESHOLD),t=Math.floor(Gs*yt.TIER_2_THRESHOLD),n=Math.floor(Gs*yt.TIER_3_THRESHOLD);try{if(this.contextTokensUsed>n){ca.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 3 threshold (${n}), triggering summarization`),this.callbacks.onStatusUpdate?.("Context limit reached. Auto-compacting the conversation...");const e=this.contextTokensUsed;await this.summarizeAndCompact();const t=Math.max(0,e-this.contextTokensUsed);return void(t>0&&this.callbacks.onFeedUpdate(zo(`Auto-compacted conversation, saved ~${t.toLocaleString()} tokens.`)))}if(this.contextTokensUsed>t){ca.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${yt.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(yt.TIER_2_KEEP_COUNT);return ca.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void(e.tokensSaved>0&&this.callbacks.onFeedUpdate(zo(`Auto-compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`)))}if(this.contextTokensUsed>e){const t=this.countToolCalls(),n=yt.TIER_1_KEEP_COUNT;if(t>n){ca.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);ca.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),t.tokensSaved>0&&this.callbacks.onFeedUpdate(zo(`Auto-compacted conversation, saved ~${t.tokensSaved.toLocaleString()} tokens.`))}}}catch(e){ca.debug(`Failed to automatically compact conversation: ${e}`)}}countToolCalls(){let e=0;for(const t of this.messages){const n=t.message.content;if(Array.isArray(n))for(const t of n)"tool_use"===t.type&&e++}return e}async removeToolCallsExceptLast(e){const t=this.contextTokensUsed;let n=0;const r=[];for(let e=0;e<this.messages.length;e++){const t=this.messages[e].message.content;if(Array.isArray(t))for(let n=0;n<t.length;n++)"tool_use"===t[n].type&&r.push({id:t[n].id,msgIndex:e,blockIndex:n})}const o=new Set(r.slice(-e).map(e=>e.id)),s=new Set(r.filter(e=>!o.has(e.id)).map(e=>e.id)),a=[];for(const e of this.messages){const t=e.message.role,r=e.message.content;if("user"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_result"!==e.type||!s.has(e.tool_use_id)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;a.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_use"!==e.type||!s.has(e.id)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;a.push({...e,message:{...e.message,content:t}});continue}a.push(e)}this.messages=a,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,t-n);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:Gs}),{toolsRemoved:s.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return ca.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(yt.TIER_2_KEEP_COUNT);ca.debug(`Summarizing ${e.length} older messages, keeping ${t.length} recent messages`);const n=e.map(e=>e.message),r=await this.compactAgent.compactMessages({messages:n});ca.debug(`Summarization complete: ${r.summary.length} chars, used ${r.tokensUsed.input}/${r.tokensUsed.output} tokens`);const o=this.createMessageWithMeta({role:"user",content:[{type:"text",text:`This is an auto-compacted summary of the earlier conversation that ran out of context.\n\n${r.summary}`}]},{isSummary:!0}),s=this.contextTokensUsed,a=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[o,...t],await this.sessionManager.saveMessages(this.messages);const i=estimateTokens(o.message),c=Math.max(0,s-a+i);this.contextTokensUsed=c,this.callbacks.onContextUsageUpdate?.({current:c,limit:Gs}),ca.debug(`Tier 3 summarization complete: reduced from ${s} to ~${c} tokens`)}catch(e){ca.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(yt.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=yt.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const o=this.messages[r],s=estimateTokens(o.message);if(t+s>e){n=r+1;break}t+=s;const a=o.message.content;Array.isArray(a)&&a.some(e=>"tool_result"===e.type)}n=Math.min(n,this.messages.length-3),n=Math.max(0,n);let r=0;this.messages[0]?.meta?.isSummary&&(r=1);for(let e=r;e<n;e++){const t=this.messages[e].message.content;if(Array.isArray(t)&&t.some(e=>"image"===e.type)){n=e;break}}for(;n>r&&"user"===this.messages[n].message.role;)n--;return{messagesToSummarize:this.messages.slice(r,n),messagesToKeep:this.messages.slice(n),keepStartIndex:n}}getCheckpointManager(){return this.checkpointManager}listCheckpoints(){return this.checkpointManager.listCheckpoints()}hasCheckpoints(){return this.checkpointManager.hasCheckpoints()}async restoreToCheckpoint(e){const{messageId:t,mode:n}=e;this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()});const r=this.sessionManager.getMessageIndexById({messageId:t,messages:this.messages});let o=0;if(-1!==r&&("conversation"===n||"both"===n))for(let e=r;e<this.messages.length;e++)o+=estimateTokens(this.messages[e].message);const s=await this.checkpointManager.restore({messageId:t,mode:n});return!s.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-o),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:Gs})),s}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}};function getShellPathAndName(){const e=process.env.SHELL||"/bin/bash",t=e.split("/").pop()?.toLowerCase()||"bash";return{path:e,name:t}}function getShellType(e){return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":"unknown"}function detectUserShell(){const{path:e,name:t}=getShellPathAndName();return"win32"===process.platform?{type:"unknown",path:e}:{type:getShellType(t),path:e}}bt(),bt(),bt(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var ua=["no job control","cannot set terminal process group"],ma=null;function getShellInfo(){return ma||(ma=detectUserShell()),ma}__name(getShellInfo,"getShellInfo");var ga=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{let s=!1;const a=__name(e=>{s||(s=!0,t(e))},"doResolve"),i=getShellInfo(),c="bash"===i.type||"zsh"===i.type,l=c?i.path:"/bin/bash",d=A(l,c?["-i","-c",e]:["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let u="",m="",g=null;n>0&&(g=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),a({stdout:u,stderr:m+(m?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(u.length+n.length>xs){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void a({stdout:u,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}u+=n}catch(e){m+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,d.kill("SIGTERM")}}),d.stderr?.on("data",e=>{try{const t=e.toString();if(m.length+t.length>Is)return void(m+="\n[Error output truncated: too large]");m+=t}catch(e){m+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{g&&clearTimeout(g);const n=c?m.split("\n").filter(e=>!ua.some(t=>e.includes(t))).join("\n"):m;a({stdout:u.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{g&&clearTimeout(g),a({stdout:u,stderr:m+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),pa=__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"),ha=__name(()=>{const[e,t]=_({isExecuting:!1,currentCommand:null});return{executeBash:j(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await ga(e,{timeout:3e4,cwd:process.cwd()}),o=pa(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]=Zo(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]=Zo(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");bt(),bt(),vt();var fa=class extends Le{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,n){super(),this.projectRoot=e,this.configPath=n||t.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 x.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 n=t.relative(this.projectRoot,e.filePath);return`${e.action}:${n}`}isTrustedPath(e){const n=t.relative(this.projectRoot,e);return this.config.trustedPaths.some(t=>n.startsWith(t)||e.startsWith(t))}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=t.join(this.projectRoot,".commandcode"),n=t.join(e,"settings.local.json");try{await x.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await x.readFile(n,"utf-8"),r=JSON.parse(e);r.permissions&&r.permissions.allow&&(t.permissions.allow=[...new Set([...r.permissions.allow,...t.permissions.allow])]),r.permissions&&r.permissions.deny&&(t.permissions.deny=r.permissions.deny)}catch(e){}await x.writeFile(n,JSON.stringify(t,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const n=t.join(this.projectRoot,".commandcode"),r=t.join(n,"settings.local.json"),o=`Bash(${e.split(" ")[0]}:*)`;try{let e;await x.mkdir(n,{recursive:!0});try{const t=await x.readFile(r,"utf-8");e=JSON.parse(t)}catch(t){e={permissions:{allow:[],deny:[],defaultMode:"ask"}}}e.permissions||(e.permissions={allow:[],deny:[],defaultMode:"ask"}),e.permissions.allow||(e.permissions.allow=[]),e.permissions.allow.includes(o)||e.permissions.allow.push(o),await x.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},ya=__name((e={})=>{const[t,n]=_(null),[r,o]=_(null),[s,a]=_(!1);return U(()=>{const t=e.projectRoot||process.cwd(),r=new fa(t);return r.on("permission-request",(t,n)=>{o(t),a(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),a(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:j(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:j(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:j(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),a(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),a(!1)}},[t]),clearSessionPermissions:j(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:j(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:j((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:j(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r=["create","edit","delete","execute","shellCommands"];for(const e of r)n.setAutoApprove(e,t)}bt(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),bt();var Ea=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole");function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",o=!1,s="";for(let e=0;e<t.length;e++){const a=t[e];'"'!==a&&"'"!==a||o?a===s&&o?(o=!1,s=""):" "!==a||o?r+=a:(r.trim()&&n.push(r.trim()),r=""):(o=!0,s=a)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const o=n.substring(0,r),s=n.substring(r+1).trim();return{commandName:o,rawArguments:s,positionalArgs:parsePositionalArguments({input:s})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let o=t;return o=o.replace(/\$ARGUMENTS/g,n),o=o.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:o}}function loadCustomCommands(){const e=[],n=t.join(process.cwd(),".commandcode","commands"),r=t.join(g.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,o=""){if(f.existsSync(n))try{const s=f.readdirSync(n,{withFileTypes:!0});for(const a of s){const s=t.join(n,a.name);if(a.isDirectory())loadCommandsFromDirectory(s,r,o?`${o}/${a.name}`:a.name);else if(a.isFile()&&a.name.endsWith(".md")){const n=t.basename(a.name,".md"),i=f.readFileSync(s,"utf-8").trim();e.push({name:n,source:r,content:i,subdirectory:o})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(r,"user"),loadCommandsFromDirectory(n,"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.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim()} ${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}function isDirectoryEmpty(){try{return 0===S(process.cwd()).length}catch{return!1}}async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new ao({baseUrl:e});return await t.get({endpoint:ct.ALPHA.WHOAMI})}bt(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),Mt(),bt(),vt(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),bt(),__name(isDirectoryEmpty,"isDirectoryEmpty"),bt(),vt(),__name(getAuthenticatedEntity,"getAuthenticatedEntity"),Sn(),bt();var wa=["Code","Code - Insiders","VSCodium","Cursor"],ba="Code",Sa={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},ka=__name(e=>l(e).href,"formatPathForTerminal"),Ca=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),va=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),Ta=__name(({home:t,configSegments:n,variants:r})=>{for(const o of r){const r=va({home:t,configSegments:n,variant:o});if(h.existsSync(e.dirname(r)))return o}return null},"findExistingVariant"),Aa=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Pa(t.when)},"isTerminalShiftEnterBinding"),Pa=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),xa=__name(e=>{const t=_e(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),Ia=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),Da=__name(({error:e,content:t})=>{const n=e.message;return Ia(t)&&(n.includes("Expected double-quoted property name")||n.includes("Unexpected token")||n.includes("is not valid JSON"))?"Invalid JSON: trailing comma detected. Remove the comma before the closing bracket.":n.includes("Expected")&&n.includes(",")&&n.includes("or")?"Invalid JSON: missing comma between elements.":n.includes("Unterminated string")||n.includes("Bad string")?"Invalid JSON: unterminated string. Check for missing closing quotes.":"Invalid JSON syntax. Please check the file format."},"formatJsonParseError"),Ra=__name(e=>{let t="",n=!1,r=!1;for(let o=0;o<e.length;o++){const s=e[o];if(n)t+=s,r?r=!1:"\\"===s?r=!0:'"'===s&&(n=!1);else if('"'!==s){if(","===s){let t=o+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=s}else n=!0,t+=s}return t},"removeTrailingCommas"),$a=__name(e=>{try{const t=_e(e),n=Ra(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:Da({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),Fa=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:ka(t)}),"createSuccessResult"),Na=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:ka(t)}),"createErrorResult"),Oa=__name(()=>{const t=m.homedir(),n=m.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=Ca(n);if(!r)return va({home:t,configSegments:[".config"],variant:ba});const o=Ta({home:t,configSegments:r,variants:wa});return va({home:t,configSegments:r,variant:o??ba})},"getVSCodeKeybindingsPath"),La=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)Aa(n)&&(n.command===Sa.command&&n.args?.text===Sa.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),_a=__name(t=>{try{if(!h.existsSync(t)){const n=e.dirname(t);return h.existsSync(n)||h.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=h.readFileSync(t,"utf-8");if(xa(n))return{rawContent:n,keybindings:[]};const r=$a(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:Na({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):Na({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return Na({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),Ma=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(Sa,null,2);if(xa(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return Na({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?Na({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,o+1)+",\n"+n+e.substring(o+1)},"generateNewContent");function setupVSCodeTerminal(){const e=Oa();try{const t=_a(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=La(r);if(o.hasConflicting)return Na({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return Fa({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=Ma({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(h.writeFileSync(e,s,"utf-8"),Fa({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return Na({message:`Failed to configure VSCode key binding: ${t instanceof Error?t.message:"Unknown error"}`,keybindingsPath:e})}}function isVSCodeTerminal(){return"vscode"===process.env.TERM_PROGRAM}__name(setupVSCodeTerminal,"setupVSCodeTerminal"),__name(isVSCodeTerminal,"isVSCodeTerminal"),bt(),vt(),fn(),bt();var Ua={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return Ua[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Oe(t);return e.join(g.homedir(),".commandcode","projects",n)}function getGlobalProjectSettingsPath(t=process.cwd()){return e.join(getGlobalProjectSettingsDir(t),"settings.json")}async function loadGlobalProjectSettings(e=process.cwd()){try{const t=getGlobalProjectSettingsPath(e),n=await P.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(t,n=process.cwd()){try{const r=getGlobalProjectSettingsPath(n),o=e.dirname(r);await P.mkdir(o,{recursive:!0}),await P.writeFile(r,JSON.stringify(t,null,2))}catch(e){const t=e instanceof Error?e.message:String(e);dlog("Error saving global project settings:",e),ra.addEvent({type:"error",message:`Failed to save global project settings: ${t}`})}}async function loadLocalProjectSettings(t=process.cwd()){try{const n=e.join(t,".commandcode","settings.local.json"),r=await P.readFile(n,"utf-8");return JSON.parse(r)}catch{return{}}}async function loadMergedProjectSettings(e=process.cwd()){try{const t=mergeSettings(await loadGlobalProjectSettings(e),await loadLocalProjectSettings(e)),n=t.tasteOnboarding,r=n?.learnedSessions?.["claude-code"]?.length||0;return dlog(`[Config] project settings loaded (taste: ${n?.completed?"complete":n?.skipped?"skipped":"pending"}, learned: ${r} sessions)`),t}catch(e){return dlog("[Settings] error loading",e),{}}}function mergeSettings(e,t){const n={...e};return t.tasteOnboarding&&(n.tasteOnboarding={...e.tasteOnboarding,...t.tasteOnboarding},(e.tasteOnboarding?.learnedSessions||t.tasteOnboarding?.learnedSessions)&&(n.tasteOnboarding.learnedSessions={...e.tasteOnboarding?.learnedSessions,...t.tasteOnboarding?.learnedSessions})),n}__name(getAgentDisplayName,"getAgentDisplayName"),__name(getProjectDirName,"getProjectDirName"),bt(),fn(),vt(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),bt(),fn();var ja=e.join(m.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=C(e,{encoding:"utf8"}),n=Me.createInterface({input:t,crlfDelay:1/0});for await(const e of n)if(e.trim()){try{const r=JSON.parse(e);if("session_meta"===r.type&&r.payload?.cwd)return n.close(),t.destroy(),{cwd:r.payload.cwd,id:r.payload.id,timestamp:r.payload.timestamp}}catch{}break}return n.close(),t.destroy(),null}catch{return null}}async function findAllSessionFiles(t,n){const r=[];try{await P.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const o=await P.readdir(t);for(const s of o){if(!/^\d{4}$/.test(s))continue;const o=e.join(t,s);if(!(await P.stat(o)).isDirectory())continue;const a=await P.readdir(o);for(const t of a){if(!/^\d{2}$/.test(t))continue;const a=e.join(o,t);if(!(await P.stat(a)).isDirectory())continue;const i=await P.readdir(a);for(const o of i){if(!/^\d{2}$/.test(o))continue;const i=e.join(a,o);if(!(await P.stat(i)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${s}/${t}/${o}`});const c=(await P.readdir(i)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(i,t));r.push(...c)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const o=[];for(let s=0;s<e.length;s+=n){const a=e.slice(s,s+n),i=await Promise.all(a.map(t));for(const e of i)null!==e&&o.push(e);r?.(Math.min(s+n,e.length),e.length)}return o}async function findCodexSessions(t,n,r=0){const o=t||process.cwd(),s=[];dlog(`[Codex] scanning for project: ${o}`);const a=await findAllSessionFiles(ja,n);if(0===a.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${a.length} session files to scan`),n?.({phase:"reading",totalFiles:a.length,processedFiles:0,matchedSessions:0});let i=0;const c=await processFilesInBatches(a,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===o)try{const r=await P.stat(t),o=e.basename(t,".jsonl");return{id:n.id||o,filePath:t,createdAt:new Date(n.timestamp||r.birthtime),lastModified:r.mtime,messageCount:0,agent:"codex",projectDir:n.cwd}}catch{return null}return null},10,(e,t)=>{i=s.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:i})});s.push(...c);const l=r>0?s.slice(0,r):s;return dlog(`[Codex] matched ${l.length} sessions for project`),n?.({phase:"complete",totalFiles:a.length,processedFiles:a.length,matchedSessions:l.length}),l.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await P.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("event_msg"===n.type&&"user_message"===n.payload?.type&&n.payload?.message){const e=n.payload.message;"string"==typeof e&&e.trim()&&t.push(e.trim())}}catch{continue}t.length>0&&dlog(`[Codex] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Codex] failed to extract prompts: ${e}`,t)}return t}async function loadProjectSettings(){return loadMergedProjectSettings()}async function saveProjectSettings(e){await saveGlobalProjectSettings(e)}function isOnboardingDone(e){return!0===e?.skipped||!0===e?.completed}function buildAgentSessionsList(e){return Object.entries(e).filter(([e,t])=>t&&t.length>0).map(([e,t])=>({agent:e,sessionIds:t,displayName:getAgentDisplayName(e)}))}async function checkOnboardingConditions(){try{const e=(await loadProjectSettings()).tasteOnboarding,t=!0===e?.demoShown;if(isOnboardingDone(e))return dlog("[Onboarding] "+(e?.skipped?"user skipped":"already completed")),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!0,agentSessions:[],demoShown:t};const n=await findNewSessions(e?.learnedSessions||{}),r=(n["claude-code"]?.length||0)+(n.codex?.length||0);return r>0?(dlog(`[Onboarding] found ${r} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:r,hasTasteContent:!0,agentSessions:buildAgentSessionsList(n),demoShown:t}):t?(dlog("[Onboarding] no new sessions to learn from"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t}):(dlog("[Onboarding] first time user, will show demo"),{shouldTrigger:!0,reason:"no_sessions",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:!1}}}async function getSessionFilesFromDir(e){try{return(await P.readdir(e)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints")).map(e=>e.replace(".jsonl",""))}catch{return[]}}async function findNewSessions(t){const n={},r=t["claude-code"]||[],o=t.codex||[];try{const t=e.join(m.homedir(),".claude","projects");await P.access(t);const o=getProjectDirName(process.cwd()),s=(await P.readdir(t)).filter(e=>e===o);for(const o of s){const s=e.join(t,o);if((await P.stat(s)).isDirectory()){const e=await getSessionFilesFromDir(s);e.length>0&&(n["claude-code"]=e.filter(e=>!r.includes(e)))}}dlog(`[Sessions] claude-code: ${n["claude-code"]?.length||0} new, ${r.length} learned`)}catch{dlog("[Sessions] claude projects dir not found")}try{const e=await findCodexSessionIds();e.length>0&&(n.codex=e.filter(e=>!o.includes(e)));dlog(`[Sessions] codex: ${n.codex?.length||0} new, ${o.length} learned`)}catch{dlog("[Sessions] codex sessions not found")}return n}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0,await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function markDemoShown(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.demoShown=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:o}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions();e.shouldTrigger?(dlog(`[Onboarding] starting taste learning (${e.reason})`),o(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),__name(loadProjectSettings,"loadProjectSettings"),__name(saveProjectSettings,"saveProjectSettings"),__name(isOnboardingDone,"isOnboardingDone"),__name(buildAgentSessionsList,"buildAgentSessionsList"),__name(checkOnboardingConditions,"checkOnboardingConditions"),__name(getSessionFilesFromDir,"getSessionFilesFromDir"),__name(findNewSessions,"findNewSessions"),__name(markSessionsAsLearned,"markSessionsAsLearned"),__name(markOnboardingSkipped,"markOnboardingSkipped"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markDemoShown,"markDemoShown"),__name(triggerTasteOnboarding,"triggerTasteOnboarding"),bt(),vt(),bt();var Ba="# Taste (Continuously Learned by CommandCode.ai)",za=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return za.test(t)?t.replace(za,`$1${Ba}`):t}__name(migrateHeader,"migrateHeader");var Wa=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await P.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await P.access(r);const e=await P.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await P.writeFile(r,t,"utf-8")}catch{await P.writeFile(r,Ba+"\n\n")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await P.access(n),!0}catch{return!1}}};wn(),kn(),Zt(),bt(),bt(),vt(),bt(),bt(),vt();var Ha=__name(()=>t.join(g.homedir(),".commandcode","agents"),"getRootAgentDir"),Ga=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),qa=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=_("idle"),[a,i]=_(""),c=[...Qs.map(e=>e.name),...Zs.map(e=>e.name)],l=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void i("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?Ha():Ga();await x.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),a=Array.from(e.selectedTools).map(e=>ta[e]||e).join(", "),i=0===e.selectedTools.size?"none":e.selectedTools.size===c.length?'"*"':JSON.stringify(a),l=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${i}\n---\n\n${e.sysPrompt}\n`;await x.writeFile(s,l,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),i(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");V((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||l()});const d=Array.from(e.selectedTools).map(e=>ta[e]||e).join(", "),u="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return L.createElement(z,{flexDirection:"column",gap:1},L.createElement(z,{flexDirection:"column"},L.createElement(z,{gap:1},L.createElement(W,{color:"white",bold:!0},"Name:"),L.createElement(W,{color:"gray"},e.agentType)),L.createElement(z,{gap:1},L.createElement(W,{color:"white",bold:!0},"Location:"),L.createElement(W,{color:"gray"},u)),L.createElement(z,{gap:1},L.createElement(W,{color:"white",bold:!0},"Tools:"),L.createElement(W,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===c.length?"*":d))),L.createElement(z,{gap:1},L.createElement(W,{color:"white",bold:!0},"Description"),L.createElement(W,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),L.createElement(W,{color:"gray"},e.ccToolDefinition),L.createElement(z,{gap:1},L.createElement(W,{color:"white",bold:!0},"System Prompt:")),L.createElement(W,{color:"gray"},e.sysPrompt),!r&&L.createElement(z,{marginTop:1},"idle"===o&&L.createElement(z,{gap:1},L.createElement(W,{color:"green",dimColor:!0},"Press"),L.createElement(W,{color:"green",bold:!0},"Enter"),L.createElement(W,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===o&&L.createElement(W,{color:"yellow"},"Saving agent..."),"saved"===o&&L.createElement(W,{color:"green"},"✓ ",a),"error"===o&&L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"red"},"✗ Error: ",a),L.createElement(W,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),Va=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=_("menu"),a=[...Qs.map(e=>e.name),...Zs.map(e=>e.name)];let i=new Set;if("*"===e.tools||'"*"'===e.tools)i=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>na[e]||e);i=new Set(t)}const c={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(V((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return L.createElement(z,{flexDirection:"column"},L.createElement(qa,{config:c,onSaveComplete:()=>s("menu"),viewOnly:!0}),L.createElement(z,{marginTop:1},L.createElement(W,{color:"gray"},"Press Enter to go back")));if("edit"===o)return L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"yellow"},"Edit functionality coming soon..."),L.createElement(W,{color:"gray"},"Press Esc to go back"));if("delete"===o){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],o=__name(async r=>{if("confirm-delete"===r.value)try{await x.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return L.createElement(z,{flexDirection:"column",gap:1},L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"red"},"Delete agent"),L.createElement(W,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),L.createElement(z,null,L.createElement(Ue,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>L.createElement(W,{color:e?"white":"gray"},` ${t}`)})))}return L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"white",bold:!0},e.name),L.createElement(z,{marginTop:1},L.createElement(Ue,{items:l,onSelect:d,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>L.createElement(W,{color:e?"white":"gray"},` ${t}`)})),L.createElement(z,{marginTop:1},L.createElement(W,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Ka=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=_([]),[s,a]=_([]),[i,c]=_([]),[l,d]=_(!0),[u,m]=_(!1),[p,h]=_(null),[f,y]=_(!1),E=__name(()=>t.join(g.homedir(),".commandcode","agents"),"getRootAgentDir"),w=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),b=__name(async(e,n)=>{try{m(!1);const r=(await x.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await x.readFile(o,"utf-8"),{data:a,content:i}=De(s);let c=a.tools||"";return"*"!==c&&'"*"'!==c||(c="*"),{name:a.name||r.replace(".md",""),description:a.description||"",tools:c,sysPrompt:i.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");U(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([b(E(),"personal"),b(w(),"project")]),n=Hs.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));o(e),a(t),c(n),d(!1)},"loadAgents")()},[u]);const S=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{S.push({label:e.name,value:e.filePath})}),s.forEach(e=>{S.push({label:e.name,value:e.filePath})});const k=r.length+s.length,C=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(h(e),y(!0))}},"handleAgentSelect");if(l)return L.createElement(W,{color:"gray"},"Loading agents...");if(f&&p){const e=p.filePath.startsWith("__builtin__:");return L.createElement(Va,{agent:p,onBack:()=>{y(!1),h(null)},setRevalidateAgent:m,isReadOnly:e})}const v=__name(({isSelected:e,label:t})=>{const n=S.find(e=>e.label===t),o=n?.value||"",a=r[0]?.filePath===o,i=s[0]?.filePath===o;return L.createElement(z,{flexDirection:"column"},a&&r.length>0&&L.createElement(z,{marginTop:1},L.createElement(W,{color:"gray",bold:!0},"User agents")),i&&s.length>0&&L.createElement(z,{marginTop:1},L.createElement(W,{color:"gray",bold:!0},"Project agents")),L.createElement(z,null,L.createElement(W,{color:"white"},e?">":" "),L.createElement(W,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return L.createElement(z,{flexDirection:"column"},L.createElement(z,{marginBottom:1},L.createElement(W,{color:"white",bold:!0},"Agents"),k>0?L.createElement(W,{color:"gray"}," ","(",k," agent",k>1?"s":"",")"):L.createElement(W,{color:"gray"}," (No custom agents)")),n&&L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(W,{color:"green",dimColor:!0},"Created agent: ",n)),L.createElement(Ue,{items:S,onSelect:C,indicatorComponent:()=>null,itemComponent:v}),i.length>0&&L.createElement(z,{flexDirection:"column",marginTop:1},L.createElement(W,{color:"gray",bold:!0},"Default agents"),i.map(e=>L.createElement(W,{key:e.filePath,color:"gray"}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),L.createElement(z,{flexDirection:"column",marginTop:1},L.createElement(W,{color:"gray"},"Create specialized subagents that Command Code can delegate to."),L.createElement(W,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");bt(),vt(),bt(),bt(),vt();var Ja=__name(({onSelect:e})=>L.createElement(Ue,{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})=>L.createElement(W,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>L.createElement(W,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector");bt(),an(),vt(),ln(),pn();var Ya=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=_(!1),[m,g]=_(!1),p=j(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?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),h=j(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?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[m,a]);return"agentType"===e?L.createElement(L.Fragment,null,L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(ta).some(e=>Oe(e)===Oe(t))||Object.keys(ta).some(e=>Oe(e)===Oe(t)))&&L.createElement(W,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Oe(t))&&L.createElement(W,{color:"red"},"⚠ This name is reserved. Reserved names:"," ",Ws.join(", "))),L.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Oe(t);Object.values(ta).some(t=>Oe(t)===e)||Object.keys(ta).some(t=>Oe(t)===e)||isReservedAgentName(e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?L.createElement(L.Fragment,null,L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"white"},"Enter the system prompt for your agent:"),L.createElement(W,{color:"gray"},"Be comprehensive for best results.")),L.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?L.createElement(L.Fragment,null,L.createElement(W,{color:"white"},"When should ","Command Code"," use this agent?"),L.createElement(TextInput,{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");bt();var Qa=__name(({onSelect:e})=>L.createElement(Ue,{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})=>L.createElement(W,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>L.createElement(W,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector");bt(),an(),bt();var Za=["·","○","◇","☆","✧","☆","◇","○","⌘"],Xa=[8,5,4,4,4,4,4,5,20],ei=[5,4,4,4,4,4,5],ti=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Xa.length;e++)if(n+=Xa[e],t<n)return Za[e];const r=t-58;n=0;for(let e=0;e<ei.length;e++)if(n+=ei[e],r<n)return Za[7-e];return Za[0]},"getWaveSymbol"),ni=["#8A6BA3","#B799E6","#E4CCFF","#FFFFFF","#E4CCFF","#B799E6","#8A6BA3"];function ShimmerText({text:e}){const[t,n]=_(0);U(()=>{const t=setInterval(()=>{n(t=>(t+1)%(e.length+10))},50);return()=>clearInterval(t)},[e.length]);const r=__name(e=>{const n=e-(t-5);return n>=0&&n<ni.length?ni[n]:"#B799E6"},"getCharColor");return L.createElement(W,null,e.split("").map((e,t)=>L.createElement(W,{key:t,color:r(t)},e)))}function CMDIcon(){const[e,t]=_(0);return U(()=>{const e=setInterval(()=>{t(e=>(e+1)%88)},15);return()=>clearInterval(e)},[]),L.createElement(W,{color:"#E4CCFF",bold:!0},ti(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var ri=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=_(0),s=getTerminalWidth();function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}U(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),s=e>0?t:-t,a=setInterval(()=>{o(e=>{const t=e+s;return s>0&&t>=n||s<0&&t<=n?n:t})},30);return()=>clearInterval(a)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");const a=s>70,i=s>40&&s<=70;return L.createElement(z,{width:s,height:1,paddingLeft:0,marginLeft:0},L.createElement(CMDIcon,null),L.createElement(z,{marginRight:1},L.createElement(ShimmerText,{text:e})),a?L.createElement(L.Fragment,null,L.createElement(z,{columnGap:1},L.createElement(W,{dimColor:!0},`(${formatTime3(t)}`),L.createElement(W,{dimColor:!0},"•"),L.createElement(W,{color:"gray"},pe.arrowDown),L.createElement(W,{dimColor:!0},`${formatToken(Math.round(r))}`),L.createElement(W,{dimColor:!0},"•"),L.createElement(z,{columnGap:1},L.createElement(W,{bold:!0,color:"gray"},"esc"),L.createElement(W,{dimColor:!0},"to interrupt)")))):i?L.createElement(z,{columnGap:1},L.createElement(W,{dimColor:!0},`(${formatToken(Math.round(r))})`)):L.createElement(L.Fragment,null))},"Status");pn(),ln();var oi=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,a]=_(!1),[i,c]=_(0),l=j(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(a(!0),n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}},[s,t]);return L.createElement(z,{flexDirection:"column"},r?L.createElement(z,null,L.createElement(CMDIcon,null),L.createElement(W,{color:"white"},"Generating agent from description...")):L.createElement(TextInput,{key:i,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:l,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&L.createElement(z,{marginTop:1},L.createElement(W,{color:"red"},`${he.warning} ${o}`)))},"RecommendedFlow");bt();var si=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=_(!1),[a,i]=_(0),c=B(()=>[...Qs.map(e=>e.name),...Zs.map(e=>e.name)],[]),l=B(()=>[{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=B(()=>{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]":"[ ]"} ${ta[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 V((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[a];if(e){const a=d[e.value];if(!a)return;"continue"===a.type?r():"toggle"===a.type?(s(!o),i(0)):"category"===a.type?n(a.value):"tool"===a.type&&t(a.value)}}}),L.createElement(z,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===a;if("divider"===e.type)return L.createElement(z,{key:`divider-${t}`},L.createElement(W,{color:"gray"}," ",e.label));if("spacer"===e.type)return L.createElement(z,{key:`spacer-${t}`,height:1});if("label"===e.type)return L.createElement(z,{key:`label-${t}`},L.createElement(W,{color:"gray"}," ",e.label));const o="continue"===e.type;return L.createElement(z,{key:`item-${t}`},L.createElement(W,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),L.createElement(z,{marginTop:1},e.size===c.length&&L.createElement(W,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&L.createElement(W,{color:"gray"},e.size," tools selected"),0===e.size&&L.createElement(W,{color:"gray"},"No tools selected")))},"ToolsSelector");kn(),Ut(),Mt(),wn();var ai=__name(({onComplete:e})=>{const[t,n]=_("location"),[r,o]=_(!1),[s,a]=_(null),[i,c]=_("agentType"),l=B(()=>[...Qs.map(e=>e.name),...Zs.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=_(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{a(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===ut.ANTHROPIC&&(r=await Nt.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const s={[it.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(s[it.OAUTH_TOKEN]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new ao({baseUrl:i}),l=await c.post({headers:s,endpoint:ct.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});m({...u,agentType:Oe(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof Zr&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?a(Rt):a("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{m({...u,agentType:Oe(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),w=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),b=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),S=__name(()=>{n("summary")},"handleToolsComplete"),k=__name(e=>{const t=new Set(u.selectedTools);t.has(e)?t.delete(e):t.add(e),m({...u,selectedTools:t})},"handleToggleTool"),C=__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 L.createElement(z,{flexDirection:"column",gap:1},L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"white",bold:!0},"Create new agent"),L.createElement(W,{color:"gray"},p())),L.createElement(z,null,"location"===t&&L.createElement(Ja,{onSelect:h}),"method"===t&&L.createElement(Qa,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&L.createElement(oi,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:y}),"configuration"===t&&"manual"===u.method&&L.createElement(z,{flexDirection:"column",gap:1},L.createElement(Ya,{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:E,onSysPromptSubmit:w,onCCToolDefinitionSubmit:b})),"tools"===t&&L.createElement(si,{selectedTools:u.selectedTools,onToggleTool:k,onToggleCategory:C,onComplete:S}),"summary"===t&&L.createElement(qa,{config:u,onSaveComplete:g})))},"AgentNew"),ii=__name(({onCancel:e})=>{const[t,n]=_(null),[r,o]=_(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return V((t,n)=>{n.escape&&e()}),L.createElement(z,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"single",flexDirection:"column"},null===t&&L.createElement(Ka,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&L.createElement(ai,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");bt(),bt();var ci=__name(({messages:e})=>0===e.length?null:L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(z,{marginBottom:0},L.createElement(W,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>L.createElement(z,{key:t},L.createElement(W,{dimColor:!0},he.pointerSmall," "),L.createElement(W,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages");function accumulateDelta(e,t,n){const r=n+t;return e===t||e===r?t:r&&e.startsWith(r)?t+e.slice(r.length):t&&e.startsWith(t)?t+e.slice(t.length):t+e}function useBracketedPaste(e){const{input:t,detectedImages:n,detectedContent:r,setInput:o,setDetectedImages:s,setDetectedContent:a,incrementInputKey:i}=e,c=M(!1),l=M(""),d=M(null),u=M(""),m=j(async(e,t)=>{let c=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectClipboardImage();if(l){const e=`[Image#${n.length+1}]`;return s(e=>[...e,l]),o(t+e),void i()}let d=c;if(!d.trim()){const e=await detectClipboardText();d=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(d){if(d.length>300){const e=`[Text#${r.length+1}]`;a(e=>[...e,d]),o(t+e)}else o(t+d);i()}},[n.length,r.length,s,a,o,i]),g=j(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(c.current){const e=l.current,t=u.current;l.current="",u.current="",c.current=!1,d.current=null,e&&await m(e,t)}},500)},[m]);return{handlePaste:j(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return c.current&&(c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)),await m(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!c.current)return c.current=!0,u.current=n.textBeforePaste??t,l.current=n.pastedContent??n.cleanedContent,g(),!0;if(c.current&&!n.isPasteEnd)return void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current)),g(),!0;if(c.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current));const e=l.current,t=u.current;return l.current="",u.current="",c.current=!1,await m(e,t),!0}return!(!n.isPasteEnd||n.isPasteStart||c.current)},[t,m,g]),resetPasteState:j(()=>{c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:j(()=>c.current,[])}}bt(),an(),vt(),ln(),Zt(),kn(),bt(),pn(),ln(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),bt(),bt();var li=["code --wait","cursor --wait","nano"],di=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return di.some(e=>n===e||n.endsWith(`/${e}`))?t.some(e=>"--wait"===e||"-w"===e)?e:`${n} --wait ${t.slice(1).join(" ")}`.trim():e}function isCommandAvailable(e){try{const t=e.split(" ")[0],n="win32"===process.platform?"where":"command -v";return v(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of li)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var ui=class extends Error{static{__name(this,"NoEditorError")}constructor(){super("No editor configured"),this.name="NoEditorError"}};async function openInEditor2(e){let t=process.env.EDITOR||process.env.VISUAL||null;if(!t&&("true"===process.env.COMMAND_CODE_DISABLE_EDITOR_FALLBACK||(t=findFallbackEditor()),!t))throw new ui;t=ensureWaitFlag(t);const n=o(p(),`commandcode-${Date.now()}.md`);return await D(n,e),new Promise((e,r)=>{const o=t.split(" ").filter(e=>e.length>0),s=o[0],a=o.slice(1),i=A(s,[...a,n],{stdio:"inherit"});i.on("close",async()=>{try{const t=await R(n,"utf-8");await $(n),e(t.trimEnd())}catch(e){r(e)}}),i.on("error",async e=>{try{await $(n)}catch{}r(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[o,s]=_(!1),[a,i]=_(null),c=j(async()=>{if(!o){s(!0),i(null);try{const n=e.replace(/\n+$/,""),o=await openInEditor2(n);t(o),r?.()}catch(e){i(e instanceof ui?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{s(!1)}}},[e,t,r,o]),l=j(()=>{i(null)},[]);return{isEditorOpen:o,editorError:a,handleOpenInEditor:c,clearEditorError:l}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),bt(),vt(),Sn();var mi=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear (reset, new)",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.COMPACT="/compact",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.FEEDBACK="/feedback",e.TERMINAL_SETUP="/terminal-setup",e.IDE_SETUP="/ide",e.ADD_DIR="/add-dir",e))(mi||{}),gi=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{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:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/agents",description:"Manage agent configurations"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/model",description:"Switch between Command Code models"},{command:"/compact",description:"Compact the conversation history"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/add-dir",description:"Add directory to workspace context"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/ide",description:"Install extension to fetch IDE context"},{command:"/help",description:"Show available shortcuts"},{command:"/exit",description:"Exit the REPL"}];function truncateText(e){const{text:t,maxWidth:n}=e;return t.length<=n?t:n<=3?t.substring(0,n):t.substring(0,n-3)+"..."}__name(truncateText,"truncateText");var pi=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=_(0),[s,a]=_(0),{stdout:i}=q(),c=i?.columns??80,l=Math.max(20,c-22-2-1-2),d=B(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...gi.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];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]),u=B(()=>{const e=s,t=Math.min(e+8,d.length);return d.slice(e,t)},[d,s]);return U(()=>{o(0),a(0)},[n]),V((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>{const t=Math.max(0,e-1);return t<s&&a(t),t});else if(i.downArrow)o(e=>{const t=Math.min(d.length-1,e+1);return t>=s+8&&a(Math.max(0,t-8+1)),t});else if(i.return){const t=d[r];return void(t&&e(t.command))}}),0===d.length?L.createElement(z,{flexDirection:"column",paddingLeft:2},L.createElement(W,{color:"dim"},"No commands found")):(d.length,L.createElement(z,{flexDirection:"column",paddingLeft:1},L.createElement(z,{columnGap:2},L.createElement(z,{flexDirection:"column",width:22},u.map((e,t)=>{const n=s+t;return L.createElement(W,{key:n,color:r===n?"white":"dim",wrap:"truncate"},e.command)})),L.createElement(z,{flexDirection:"column"},u.map((e,t)=>{const n=s+t;return L.createElement(W,{key:n,color:r===n?"white":"dim",wrap:"truncate"},truncateText({text:e.description,maxWidth:l}))})))))},"CommandMenu");function loadGitignore(e){const t=je(),n=o(e,".gitignore");if(y(n))try{const e=E(n,"utf8");t.add(e)}catch{}return t.add(".git"),t}bt(),__name(loadGitignore,"loadGitignore");var hi=__name(({onSelectFile:e,onClose:t,searchQuery:s=""})=>{const[i,c]=_(process.cwd()),[l,d]=_([]),[u,m]=_(0),[g,p]=_(0),h=s.trim()?15:10,f=j((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const s=o(t,e);try{const e=S(s),a=[];return e.forEach(e=>{const i=o(s,e);try{const e=k(i),o=n(t,i);if(r.ignores(o))return;a.push({name:o,path:i,isDirectory:e.isDirectory()})}catch{}}),a.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),a.slice(0,50)}catch{}}if(e.includes("/")){const s=e.split("/"),a=s.pop()||"",i=o(t,s.join("/"));try{const e=S(i),s=[],c=a.toLowerCase();return e.forEach(e=>{const l=e.toLowerCase();if(!a||l.includes(c)){const a=o(i,e);try{const e=k(a),o=n(t,a);if(r.ignores(o))return;s.push({name:o,path:a,isDirectory:e.isDirectory()})}catch{}}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),s.slice(0,50)}catch{}}const s=[],a=e.toLowerCase(),i=__name((e,c=0)=>{if(!(c>8))try{S(e).forEach(l=>{const d=o(e,l);try{const e=k(d),o=n(t,d);if(r.ignores(o))return;const u=o.toLowerCase();(l.toLowerCase().includes(a)||u.includes(a))&&s.push({name:o,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==l&&i(d,c+1)}catch(e){}})}catch(e){}},"searchRecursively");return i(t),s.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),o=n===a,s=r===a;if(o&&!s)return-1;if(!o&&s)return 1;const i=n.split("/").pop()||"",c=r.split("/").pop()||"",l=i.includes(a),d=c.includes(a);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)}),s.slice(0,50)},[]),y=j(e=>{try{const t=S(e),s=[],a=process.cwd(),i=loadGitignore(a);"/"!==e&&s.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=o(e,t);try{const e=k(r),o=n(a,r);if(i.ignores(o))return;s.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(s),m(0),p(0)}catch{}},[]);U(()=>{if(s.trim()){const e=f(s);d(e),m(0),p(0)}else y(i)},[i,y,s,f]),V((n,r)=>{if(r.escape)t();else if(r.upArrow)m(e=>{const t=Math.max(0,e-1);return t<g&&p(t),t});else if(r.downArrow)m(e=>{const t=Math.min(l.length-1,e+1);return t>=g+h&&p(t-h+1),t});else{if(r.rightArrow){const e=l[u];if(!e)return;return void(e.isDirectory&&!s.trim()&&c(a(e.path)))}if(r.return){const t=l[u];if(!t)return;return void e(t.path)}}});const E=l.slice(g,g+h);return L.createElement(z,{flexDirection:"column",paddingLeft:1},L.createElement(z,{marginBottom:1,flexDirection:"column"},L.createElement(W,{color:"dim"},s.trim()?`Searching for: "${s}"`:`Files: ${i}`),L.createElement(W,{color:"dim"},s.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===E.length?L.createElement(W,{color:"dim"},s.trim()?`No files found matching "${s}"`:"No files found in this directory"):E.map((e,t)=>{const n=g+t,r=e.name,o=n===u;return L.createElement(W,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList");bt(),vt(),Sn(),bt();var fi=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20)return null;const r=__name(e=>e>=90?"red":e>=70?"yellow":"dim","getColor"),o=`context: ${n}% left before auto-compact`;return L.createElement(z,{paddingRight:1},L.createElement(W,{color:r(t)},o))},"ContextUsage");bt();var yi=__name(()=>{const[e,t]=_("continuous learning"),n=M([]),r=M(0),o=M(null),s=M(!1);U(()=>{const e=__name(e=>"analyzing"===e.type?(s.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):s.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(s.current=!1,void(n.current.length>0?(r.current=0,a()):t("continuous learning"))):void 0,"handleNewEvent"),a=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const s="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,a()},s)},"cycleThroughNextEvent");return ra.on("new-event",e),()=>{ra.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const a=9+e.length+9>100;let i=e;if(a){const t=100;e.length>t&&(i=e.substring(0,t-3)+"...")}else{const t=82;e.length>t&&(i=e.substring(0,t-3)+"...")}return L.createElement(z,null,!a&&L.createElement(W,{color:"green"},"● taste: "),L.createElement(W,null,i),!a&&L.createElement(W,{dimColor:!0}," (ctrl+t)"))},"LearningFeedMini"),Ei=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?L.createElement(L.Fragment,null,t&&L.createElement(W,{dimColor:!0}," · "),L.createElement(W,{color:"connected"===e.type?"green":"yellow"},e.message)):null,"ConnectionIndicatorBadge"),wi=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,autoAcceptMode:r,tasteLearning:o,contextUsage:s,connectionIndicator:a,pendingExitKey:i,updateStatus:c,updateFailedInfo:l,currentProvider:d,showProviderInfo:u,isBashMode:m,shareInfo:g,showShareNotification:p,unshareNotificationMessage:h,tasteNotificationMessage:f})=>{const y=e>=60;return L.createElement(L.Fragment,null,L.createElement(z,{flexDirection:"column",paddingLeft:1},r&&!i?L.createElement(L.Fragment,null,L.createElement(z,{flexDirection:"row",justifyContent:"space-between",width:e-1},L.createElement(z,{flexDirection:"row",columnGap:0},L.createElement(W,{color:"#E4CCFF"},"»» accept edits on "),L.createElement(W,{dimColor:!0},"(shift+tab to cycle)")),y&&o&&L.createElement(yi,null)),L.createElement(z,{flexDirection:"row",justifyContent:"space-between",width:e-1},L.createElement(z,{flexDirection:"row",columnGap:0},L.createElement(W,{color:n?"#5FAFAF":void 0,dimColor:!n},t),L.createElement(Ei,{indicator:a})),y&&s&&L.createElement(fi,{usage:s}))):L.createElement(z,{flexDirection:"row",justifyContent:"space-between",width:e-1},L.createElement(z,{flexDirection:"row",columnGap:0},i?L.createElement(W,{dimColor:!0},"Press Ctrl+C again to exit"):L.createElement(W,{color:n?"#5FAFAF":void 0,dimColor:!n},t),!i&&L.createElement(Ei,{indicator:a})),y&&L.createElement(z,{flexDirection:"column",alignItems:"flex-end"},o&&L.createElement(yi,null),s&&L.createElement(fi,{usage:s}))),(c||l||u&&d)&&L.createElement(z,{flexDirection:"row",columnGap:1},c&&L.createElement(W,null,he.tick," ","Command Code"," updated:"," ",L.createElement(W,{dimColor:!0},"v",c.updatedFrom),L.createElement(W,{dimColor:!0}," ",he.arrowRight," "),L.createElement(W,null,"v",c.updatedTo)),!c&&l&&L.createElement(W,{color:"yellow",dimColor:!0},he.info," Update available:"," ",l.currentVersion," ",he.arrowRight," ",l.latestVersion),u&&d&&L.createElement(W,{color:"green",dimColor:!0},he.bullet," Provider:"," ",getProviderDisplayName(d)))),m&&L.createElement(z,{paddingLeft:1},L.createElement(W,{color:"green"},"! for bash mode")),p&&g&&L.createElement(z,{paddingLeft:1},L.createElement(W,{color:"#E4CCFF"},"SHARED: ",g.url," (copied to clipboard)")),h&&L.createElement(z,{paddingLeft:1},L.createElement(W,{color:h.includes("NOT SHARED")?"red":"#E4CCFF"},h)),f&&L.createElement(z,{paddingLeft:1},L.createElement(W,{color:"#E4CCFF"},f)))},"BottomIndicator");bt();var bi=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=_([]),[o,s]=_(0),[a,i]=_(!0);U(()=>{c()},[]);const c=__name(async()=>{i(!0);const e=await Vs.listSessions();r(e.slice(0,30)),i(!1)},"loadSessions");if(V((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)}),a)return L.createElement(z,{flexDirection:"column",paddingLeft:2},L.createElement(W,{color:"gray"},"Loading sessions..."));if(0===n.length)return L.createElement(z,{flexDirection:"column",paddingLeft:2},L.createElement(W,{color:"gray"},"No previous sessions found"),L.createElement(W,{color:"dim",dimColor:!0},"Press ESC to go back"));const l=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),d=__name((e,t=50)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage"),u=__name(e=>e.title?e.title:d(e.firstMessage),"getSessionSummary");return L.createElement(z,{flexDirection:"column",paddingLeft:1,width:"100%"},L.createElement(W,{color:"cyan",bold:!0},"Resume Session"),L.createElement(W,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),L.createElement(z,{marginTop:1}),L.createElement(z,{columnGap:2,marginBottom:1},L.createElement(z,{width:5},L.createElement(W,{color:"gray"}," ")),L.createElement(z,{width:13},L.createElement(W,{color:"gray"},"Modified")),L.createElement(z,{width:20},L.createElement(W,{color:"gray"},"Git Branch")),L.createElement(z,{width:11},L.createElement(W,{color:"gray"},"# Messages")),L.createElement(z,null,L.createElement(W,{color:"gray"},"Summary"))),L.createElement(z,{columnGap:2},L.createElement(z,{flexDirection:"column",width:5},n.map((e,t)=>L.createElement(W,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${he.pointer} ${t+1}.`:` ${t+1}.`))),L.createElement(z,{flexDirection:"column",width:13},n.map((e,t)=>L.createElement(W,{key:`mod-${e.id}`,color:o===t?"white":"gray"},l(e.lastModified)))),L.createElement(z,{flexDirection:"column",width:20},n.map((e,t)=>L.createElement(W,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),L.createElement(z,{flexDirection:"column",width:11},n.map((e,t)=>L.createElement(W,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),L.createElement(z,{flexDirection:"column"},n.map((e,t)=>L.createElement(W,{key:`summary-${e.id}`,color:o===t?"white":"gray"},u(e))))))},"SessionsResumeTable");bt(),cr();var Si=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=_(null),[s,a]=_(!1),i=M(!1),c=M(null),[l,d]=_(!1),[u,m]=_("connected"),g=M(null),p=M(null),h=j((e,t)=>{p.current&&(clearTimeout(p.current),p.current=null),m(e),d(!0),void 0!==t&&(p.current=setTimeout(()=>{d(!1)},t))},[]),f=j(()=>{p.current&&(clearTimeout(p.current),p.current=null)},[]),y=j(async(e=!1)=>{if(!i.current){i.current=!0;try{let t=c.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new rr,c.current=t;const r=e?200:500;n=await t.connect(r)}const r=g.current;if(null===r?n?h("connected",3e3):h("disconnected",5e3):r!==n&&(n?h("connected",2e3):h("disconnected",5e3)),g.current=n,a(n),n){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),c.current=null),o(r)}else o(null)}catch{!0===g.current&&h("disconnected",5e3),g.current=!1,a(!1),o(null),c.current?.disconnect(),c.current=null}finally{i.current=!1}}},[h]);return U(()=>{if(!t||n)return;y(!0);const e=setInterval(()=>y(!1),500);return()=>{clearInterval(e),f(),c.current?.disconnect(),c.current=null}},[t,n,y,f]),{context:r,connected:s,refresh:y,connectionIndicator:{visible:l,message:"connected"===u?"IDE ✓":"IDE disconnected",type:u}}},"useVSCodeContext");bt();var ki=__name(e=>{const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:o}=e.activeFile;t.push(`File: ${n} (${r}, line ${o.line})`)}if(e.selection){const{text:n,startLine:r,endLine:o}=e.selection,s=e.activeFile?.language||"";t.push(`Selected lines ${r}-${o}:`),t.push(`\`\`\`${s}`),t.push(n),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt"),Ci=["\n","\r","","[27;2;13~","[27;2;13~","[13;2u"],vi=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isNewlineShortcutKey(e){const{inputChar:t,key:n,isPasting:r}=e;return!r&&(!(!n.return||!n.shift)||!(!n.ctrl||!n.return)||!(!n.ctrl||"j"!==t)||!("\r"!==t||n.return||n.ctrl||n.shift||n.meta)||Ci.includes(t))}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isNewlineShortcutKey,"isNewlineShortcutKey"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var Ti=__name(()=>L.createElement(z,{flexDirection:"column",paddingLeft:1},L.createElement(W,{color:"dim",bold:!0},"Available Shortcuts:"),L.createElement(z,{columnGap:4},L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"dim"},"! for bash mode"),L.createElement(W,{color:"dim"},"/ for commands"),L.createElement(W,{color:"dim"},"@ for file paths"),L.createElement(W,{color:"dim"},"shift + tab to toggle auto-accept")),L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"dim"},"double tap esc to clear input"),L.createElement(W,{color:"dim"},"ctrl + j / shift + ⏎ for newline"),L.createElement(W,{color:"dim"},"ctrl + g to open in editor"),L.createElement(W,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Ai=__name(({input:e,onSubmit:t,setInput:r,showCursor:o=!0,placeholder:s="Enter your input…",showFileList:a,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:E,updateFailedInfo:w,currentProvider:b,showProviderInfo:S,autoAcceptMode:k=!1,onToggleAutoAccept:C,hintMessage:v,historyManager:T,pendingExitKey:A=null,onOverlayVisibilityChange:P,onDoubleEscapeEmpty:x,onAltP:I,isProcessing:D=!1,ideContextEnabled:R=!0})=>{const[$,F]=_(0),[N,O]=_(!1),[H,G]=_(!1),[K,J]=_(!1),[Y,Q]=_(!1),[Z,X]=_(""),[ee,te]=_(!1),[ne,re]=_(0),[oe,se]=_([]),[ae,ie]=_([]),[ce,le]=_(""),de=M(!1),ue=M(!1),[me,ge]=_(-1),[pe,fe]=_(""),ye=M(0),{isEditorOpen:Ee,editorError:we,handleOpenInEditor:be,clearEditorError:Se}=useExternalEditor({input:e,setInput:r,setInputKey:F,onEditorClose:__name(()=>{de.current=!1},"onEditorClose")}),{handlePaste:ke,resetPasteState:Ce,isPasting:ve}=useBracketedPaste({input:e,detectedImages:ae,detectedContent:oe,setInput:r,setDetectedImages:ie,setDetectedContent:se,incrementInputKey:__name(()=>F(e=>e+1),"incrementInputKey")}),{context:Te,connected:Ae,refresh:Pe,connectionIndicator:xe}=Si({enabled:R,paused:D}),{stdout:Ie}=q(),De=Ie?.columns??80;U(()=>{const e=a||Y||ee;P?.(e)},[a,Y,ee,P]);const Re=j(()=>{r(""),G(!1),Q(!1),X(""),te(!1),se([]),ie([]),le(""),Ce(),ge(-1),fe(""),F(e=>e+1)},[r,Ce]);V(async(t,n)=>{if(n.upArrow){if(a||Y||ee)return;const t=e.indexOf("\n"),n=-1===t||ye.current<=t;if(0!==e.length&&-1===me&&!n)return;const o=T?.count()??0;if(0===o)return;-1===me&&fe(e);const s=Math.min(me+1,o-1);return void(s!==me&&(ge(s),r(T?.getAt(s)||""),F(e=>e+1)))}if(n.downArrow){if(a||Y||ee)return;if(-1===me)return;const t=e.lastIndexOf("\n");if(!(-1===t||ye.current>t))return;const n=me-1;return ge(n),r(-1===n?pe:T?.getAt(n)||""),void F(e=>e+1)}if(""===t||n.ctrl&&"c"===t)return;if(isCtrlKey({inputChar:t,key:n,letter:"g",ctrlCode:7}))return de.current=!0,void be();if(getIsExpandToolShortcut(n,t))return de.current=!0,r(e),F(e=>e+1),void setTimeout(()=>{de.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:n,isPasting:ve()}))return ue.current=!0,de.current=!0,r(e+"\n"),F(e=>e+1),void setTimeout(()=>{ue.current=!1,de.current=!1},0);if(n.meta&&n.backspace)return void Re();if(n.meta&&"w"===t)return de.current=!0,void Re();const o=n.ctrl&&"v"===t||vi.includes(t),s=n.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e,n=await detectClipboardImage();if(n){const e=`[Image#${ae.length+1}]`;ie(e=>[...e,n]),r(t+e),F(e=>e+1)}return void(de.current=!0)}}else if(!n.ctrl&&!n.meta||"u"!==t){if(n.ctrl&&"z"===t?.toLowerCase())return J(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(n.escape){if(Y)return;if(ee)return te(!1),r(ce),void F(e=>e+1);const t=Date.now();return t-ne<500?(e.length>0?Re():x?.(),re(0)):re(t),O(!1),void G(!1)}N&&(n.backspace||n.delete)&&0===e.length&&O(!1)}});const $e=j(async t=>{if(Ee)return;const n=removeAltPCharacter(t);if(null!==n)return r(n),void I?.();if(await ke(t))return;if(de.current)return void(de.current=!1);-1!==me&&ge(-1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!N)return O(!0),r(""),void F(e=>e+1);if("!"===s&&!H)return O(!1),G(!0),r(""),void F(e=>e+1)}if("/"!==s||Y||"/"!==t||(Q(!0),X("")),Y&&!t.startsWith("/")&&(Q(!1),X("")),Y&&t.startsWith("/")){const e=t.substring(1);X(e)}"@"!==s||a||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(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),n=!e.includes(" "),r=c>0?t[c-1]:"";n&&isPrecededByWhitespace(r)&&(i(!0),l(e))}if(a)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)}}N&&(t!==e||t.length<e.length)&&O(!1),we&&Se(),0===t.length&&(G(!1),Q(!1),X(""),te(!1),ie([]),se([]),l(""),le(""),Ce()),r(t)},[N,e,r,a,i,Y,H,ae,me,ke,Ce,I,we,Se,Ee]),Fe=j(async()=>{if(Pe(),N)return void O(!1);let n=e.trim();if(!H&&n.startsWith("/"))return T?.add(n),d&&d(n),G(!1),Q(!1),X(""),ie([]),se([]),ge(-1),void fe("");n.length>0&&T?.add(n),ge(-1),fe("");let r=[];const o=ae.length>0,s=oe.length>0;if(!H&&o){const e=[];ae.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!H&&s){let e=n;oe.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:H?"bash":"user",images:r,ideContext:Te?ki(Te):void 0}),G(!1),Q(!1),X(""),ie([]),se([])},[t,d,N,e,H,ae,oe,T,Pe]),Ne=j(t=>{const o=n(process.cwd(),t);let s;if(a&&""!==c){const t=e.lastIndexOf("@");s=-1!==t?e.substring(0,t+1)+o+" ":o+" "}else s=`${e}${o} `;r(s),i(!1),l(""),F(e=>e+1)},[r,i,e,a,c,l]),Oe=j(()=>{i(!1),l("")},[i,l]),Le=j(t=>{if("/resume"===t)T?.add(t),ge(-1),fe(""),le(e),Q(!1),X(""),te(!0),r(""),F(e=>e+1);else{const e=Object.values(mi).includes(t);Q(!1),X(""),e?(T?.add(t),ge(-1),fe(""),r(""),F(e=>e+1),d&&d(t)):(r(t+" "),F(e=>e+1))}},[d,r,e,T]),_e=j(()=>{Q(!1),X(""),r(""),ge(-1),fe(""),F(e=>e+1)},[r]),Me=j(e=>{te(!1),r(""),le(""),ge(-1),fe(""),F(e=>e+1),d&&d(`/resume:${e}`)},[d,r]),Ue=j(()=>{te(!1),r(ce),ge(-1),fe(""),F(e=>e+1)},[ce,r]),je=j(e=>{ye.current=e},[]),Be=B(()=>k||Ae?!N&&!ee:!N&&0===e.length&&!H&&!ee,[N,e,H,ee,k,Ae]),ze=__name(()=>N||a||Y||ee||K?0:Be||A||H?3:4,"getBottomMargin"),We=__name(()=>!(!Ae||!Te?.selection&&!Te?.activeFile?.relativePath),"hasIDEContext"),He=__name(()=>{const e=Ae?Te?.selection:null;if(e)return`${e.lineCount} lines selected`;const t=Ae?Te?.activeFile:null;if(t?.relativePath){const e=t.relativePath.split("/").pop()||"",n=De<80?15:De<120?25:40;return`In ${e.length>n?e.slice(0,n-1)+"…":e}`}return"? for shortcuts"},"getIndicatorText");return L.createElement(z,{width:"100%",flexDirection:"column",marginBottom:ze()},!ee&&L.createElement(z,{flexDirection:"column",width:"100%"},L.createElement(W,{color:H?"green":"gray"},he.line.repeat(De)),L.createElement(TextInput,{key:$,value:e,placeholder:Ee?"Save and close the editor to continue...":s,onChange:$e,onSubmit:()=>{ue.current?ue.current=!1:a||Y||ee||Ee||Fe()},showCursor:!Ee&&o,onCursorChange:je,prefix:`${H?"!":he.pointer} `,prefixColor:H?"green":"white"}),L.createElement(W,{color:H?"green":"gray"},he.line.repeat(De))),N&&L.createElement(Ti,null),K&&L.createElement(z,{paddingTop:1},L.createElement(W,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),a&&L.createElement(hi,{onSelectFile:Ne,onClose:Oe,searchQuery:c}),Y&&L.createElement(pi,{onSelectCommand:Le,onClose:_e,searchQuery:Z}),ee&&L.createElement(bi,{onSelectSession:Me,onClose:Ue}),(Be||A)&&L.createElement(wi,{termWidth:De,indicatorText:He(),isIDEIndicator:We(),autoAcceptMode:k,tasteLearning:m,contextUsage:u,connectionIndicator:xe,pendingExitKey:A,updateStatus:E,updateFailedInfo:w,currentProvider:b,showProviderInfo:S,isBashMode:H,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y}),we&&L.createElement(z,{paddingLeft:1,flexDirection:"column"},L.createElement(W,{color:"yellow"},we)))},"InputBox"),Pi=L.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:a,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:E,tasteNotificationMessage:w,updateStatus:b,updateFailedInfo:S,currentProvider:k,showProviderInfo:C,autoAcceptMode:v,onToggleAutoAccept:T,hintMessage:A,historyManager:P,pendingExitKey:x,onResetPendingExitKey:I,onDoubleEscapeEmpty:D,retryAttempt:R,onAltP:$})=>{const[F,N]=_(0),O=M(o);return U(()=>{x&&o!==O.current&&o.length>0&&I?.(),O.current=o},[o,x,I]),U(()=>{if(!t)return void N(0);const e=setInterval(()=>{N(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),L.createElement(z,{flexDirection:"column"},L.createElement(ci,{messages:e}),L.createElement(z,{flexDirection:"row",justifyContent:"space-between"},L.createElement(z,{flexDirection:"column"},(t||n.isExecuting)&&null===R&&L.createElement(ri,{tokens:m,timeElapsed:F,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),A&&L.createElement(z,{marginLeft:1},L.createElement(W,{dimColor:!0}," ","⎿"," Tip: ",A)))),L.createElement(Ai,{input:o,setInput:s,onSubmit:a,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:E,tasteNotificationMessage:w,updateStatus:b,updateFailedInfo:S,currentProvider:k,showProviderInfo:C,autoAcceptMode:v,onToggleAutoAccept:T,hintMessage:A,historyManager:P,pendingExitKey:!x||t||n.isExecuting?null:x,onDoubleEscapeEmpty:D,onAltP:$,isProcessing:t}))});bt();var xi=__name(({onClose:e})=>{const[t,n]=_(ra.getEvents());V((t,n)=>{n.ctrl&&"t"===t&&(Ea(),e())},{isActive:!0}),U(()=>{const e=__name(()=>{n(ra.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return ra.on("new-event",e),ra.on("cleared",t),()=>{ra.off("new-event",e),ra.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`confidence: ${parseFloat(e).toString()}%`}const a={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:a,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"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"),a=__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 L.createElement(z,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(Be,{name:"vice"},L.createElement(W,null,Br()))),L.createElement(z,{marginBottom:1,width:"100%",justifyContent:"space-between"},L.createElement(z,null,L.createElement(W,{bold:!0},"Learning Feed"),L.createElement(W,{dimColor:!0}," - Real-time taste learning activity")),L.createElement(W,{dimColor:!0},"Press ctrl+t to close")),L.createElement(z,{flexDirection:"column"},0===t.length?L.createElement(z,null,L.createElement(W,{dimColor:!0},"No learning events yet...")):L.createElement(z,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:i}=o(e.message),c="moved"===t?a(e.details):null,l="upgraded"===t||"downgraded"===t?s(r):null;return L.createElement(z,{key:e.id,marginBottom:1},L.createElement(z,{flexDirection:"column"},L.createElement(z,null,L.createElement(W,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),c?L.createElement(W,{dimColor:!0}," (",c.fullPath,")"):e.details?L.createElement(W,{dimColor:!0}," (",e.details,")"):null),L.createElement(z,{marginLeft:1},L.createElement(W,{dimColor:!0},"⎿"," "),c?L.createElement(L.Fragment,null,L.createElement(W,null,c.category," package ("),L.createElement(W,{dimColor:!0},c.oldPath),L.createElement(W,null," → ",c.newPath),L.createElement(W,null,")")):l?L.createElement(L.Fragment,null,L.createElement(W,null,l.text," ("),L.createElement(W,{dimColor:!0},"confidence: "),L.createElement(W,{dimColor:!0},l.oldPercent,"%"),L.createElement(W,null," → "),L.createElement(W,{color:l.diff>0?"green":"red"},l.newPercent,"%"),L.createElement(W,null,")")):L.createElement(L.Fragment,null,L.createElement(W,null,r),i&&L.createElement(W,{dimColor:!0}," (",i,")")))))}return L.createElement(z,{key:e.id,marginBottom:1},L.createElement(W,{dimColor:!0},he.pointerSmall," ",e.message))}))))},"LearningFeedFull");bt(),vt(),Mt();var Ii=__name(({onClose:e})=>{const[t,n]=_([]),[r,o]=_(0),[s,a]=_(!0),[i,c]=_(null);U(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),a(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),a(!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(V((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]))}),s)return L.createElement(z,{paddingLeft:1,paddingTop:1},L.createElement(W,{color:"dim"},"Loading memory files..."));if(i)return L.createElement(z,{paddingLeft:1,paddingTop:1},L.createElement(W,{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 L.createElement(z,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},L.createElement(z,null,L.createElement(W,{color:"white",bold:!0},"Select memory to edit:")),L.createElement(z,{columnGap:4,marginTop:1},L.createElement(z,{flexDirection:"column"},u.map((e,t)=>L.createElement(W,{key:t,color:r===t?"white":"dim"},r===t?`${Ft} `:" ",e.label))),L.createElement(z,{flexDirection:"column"},u.map((e,t)=>L.createElement(W,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector");bt(),bt(),bt();var Di=class extends We{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}list(e,t=!1,n=""){let r=super.list(e,t,n);return r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),r}},Ri=new ze;Ri.setOptions({renderer:new Di({strong:J.bold,em:J.italic,del:J.strikethrough,codespan:J.yellow,code:J.yellow,heading:J.bold.underline,firstHeading:J.bold.underline,link:J.cyan,href:J.cyan.underline,blockquote:J.gray.italic,table:J.reset,hr:J.reset,paragraph:J.reset,html:J.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var $i=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=B(()=>{if(!e)return"";const t=[],n=e.replace($i,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=Ri.parse(n);return"string"!=typeof r?e:r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").trim()}catch{return e}},[e]);return L.createElement(W,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return L.createElement(z,null,L.createElement(W,null,he.nodejs),L.createElement(z,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},L.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage"),bt(),Mt();var Fi={"Interrupted by user":"Interrupted by user","Insufficient credits":Rt};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&&Fi[e]||e;return L.createElement(z,{paddingRight:1,backgroundColor:o?void 0:"#333333"},L.createElement(W,{color:o?"red":"#AAAAAA",bold:!o},he.pointer),L.createElement(z,{marginLeft:1},L.createElement(W,{color:o?"red":"white",wrap:"wrap"},s)))}__name(UserMessage,"UserMessage"),bt(),Lt(),kn();var Ni="#6B7280";function truncateToolOutputForDisplay({output:e,maxLines:t=1}){const n=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),r=n.split("\n");return r.length<=t?n:r.slice(0,t).join("\n")}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,dimDiff:a=!1,maxLines:i}){const c=He.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(L.createElement(z,{key:`${t}-${r}-removed`,width:"100%"},L.createElement(W,{color:"gray",dimColor:a},u.toString().padStart(3)," "),L.createElement(z,{backgroundColor:"#712F37"},L.createElement(W,{dimColor:a},"-"),L.createElement(W,{dimColor:a}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(L.createElement(z,{key:`${t}-${r}-added`,width:"100%"},L.createElement(W,{color:"gray",dimColor:a},u.toString().padStart(3)," "),L.createElement(z,{backgroundColor:"#325B30"},L.createElement(W,{dimColor:a},"+"),L.createElement(W,{dimColor:a}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:L.createElement(z,{flexDirection:"column"},o&&!r&&L.createElement(W,{color:"gray"},"Updated"," ",L.createElement(W,{color:"white",bold:!0},n)," ","with ",L.createElement(W,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",L.createElement(W,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&L.createElement(W,{color:"red"},"Rejected update to",L.createElement(W,{color:"red"},` ${n}`)),L.createElement(z,{flexDirection:"column",marginLeft:s},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=as(e);return t?L.createElement(z,{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 L.createElement(z,{key:e.id||t,flexDirection:"row"},L.createElement(z,{width:2},L.createElement(W,{color:r},n)),L.createElement(W,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):L.createElement(W,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:a=!1}){const i="Thinking…"===e,c="Todos"===e,l="Edit"===e,d=!0===s?.isTasteFile,u=s?.tasteCategory,m=!0===s?.permissionDenied,g=!i&&!c&&!d,{name:p}=detectTerminal(),h="iTerm2"===p?"shift":"ctrl",f=!0===s?.isAgent,y=t&&f?(()=>{const e=t.split(/[.\n]/)[0];return e?e+(t.includes(".")||t.includes("\n")?".":""):t})():t,E=!i&&y&&!d,w=s?.status,b=s?.tokensUsed||0,S="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0;let k,C;if(r)k="yellow",C="→";else if(o)k="red",C=he.nodejs;else if(i)k=Ni,C="✻";else if(c&&n){const e=as(n),t=e?.every(e=>"completed"===e.status);k=t?"#22C55E":"#D4A017",C=he.nodejs}else k="#22C55E",C=he.nodejs;return L.createElement(z,null,i&&L.createElement(W,{color:k},C),L.createElement(z,{flexDirection:"column",marginLeft:i?1:2},L.createElement(z,null,i?L.createElement(L.Fragment,null,L.createElement(W,{color:Ni},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!a&&L.createElement(W,{dimColor:!0},"(",`${h}+o to expand`,")")):d?L.createElement(L.Fragment,null,L.createElement(W,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),L.createElement(W,null," ","Using your taste ",u?"package of ":"packages",u&&L.createElement(W,{bold:!0},u))):L.createElement(W,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),E&&L.createElement(W,null," ",L.createElement(Markdown,null,`(${y})`))),f&&("running"===w||n)&&L.createElement(z,{columnGap:1},g&&L.createElement(W,null,"⎿"," "),"running"===w?L.createElement(W,{color:"gray"},"Running (",formatTime2(S)," | ",formatTokens(b),")"):"interrupted"===w?L.createElement(W,{color:"red",wrap:"wrap"},"Interrupted by user"):"error"===w||o?L.createElement(W,{color:"red",wrap:"wrap"},n," (",formatTime2(S)," | ",formatTokens(b),")"):"Interrupted by user"===n?L.createElement(L.Fragment,null,L.createElement(W,{color:"red",wrap:"wrap"},"Interrupted by user")):L.createElement(L.Fragment,null,L.createElement(W,{wrap:"wrap"},"Done"),L.createElement(W,{color:"gray"}," ","(",formatTime2(S)," | ",formatTokens(b),")"))),n&&!d&&!f&&L.createElement(z,{columnGap:1},g&&L.createElement(W,null,"⎿"," "),c?formatTodosForDisplay(n):i?a?L.createElement(z,{width:"100%",flexDirection:"column"},L.createElement(W,null," "),L.createElement(W,{color:Ni,wrap:"wrap",italic:!0},n)):null:l&&s?.oldValue&&s?.newValue?L.createElement(z,{flexDirection:"column"},(()=>{const e=a?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:m,permissionDenied:m,maxLines:e});return L.createElement(L.Fragment,null,n,r&&L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"… (",o-10," more lines) (",`${h}+o to expand`,")")))})(),m&&n&&L.createElement(z,{marginTop:1},L.createElement(W,{color:"red",wrap:"wrap"},n))):L.createElement(z,{width:"100%"},L.createElement(W,{color:o?"red":"",wrap:"wrap"},a?n:L.createElement(L.Fragment,null,truncateToolOutputForDisplay({output:n,maxLines:"Question"===e?10:1}),n.includes("\n")&&"Question"!==e&&L.createElement(W,{dimColor:!0}," ","(",`${h}+o to expand`,")"))))),r&&!f&&L.createElement(z,{columnGap:1},L.createElement(W,null,"⎿"," "),L.createElement(W,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,s;return n?(o="yellow",s="→"):r?(o="red",s="✗"):(o="green",s="✓"),L.createElement(z,null,L.createElement(W,{color:o},s),L.createElement(z,{flexDirection:"column",marginLeft:1},L.createElement(z,null,L.createElement(W,{color:"gray"},"$ "),L.createElement(W,{color:o,bold:!0},e)),L.createElement(z,{columnGap:1,marginLeft:1},L.createElement(W,null,"⎿"," "),L.createElement(W,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),bt(),__name(BashMessage,"BashMessage"),bt(),bt(),vt();bt(),vt();var Oi="Coding agent that continuously learns your taste of writing code.",Li=34,_i=[{key:"Shift+Tab",description:"Toggle auto-accept mode"},{key:"Ctrl+T",description:"Toggle learning feed"},{key:"Ctrl+O",description:"Toggle expanded tool output (Shift+O in iTerm2)"},{key:"Alt+P",description:"Quick model switch (Option+P on macOS)"},{key:"Ctrl+G",description:"Open input in external editor ($EDITOR)"},{key:"Esc Esc",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],Mi=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume",description:"Resume a conversation"},{key:"-c, --continue",description:"Continue the last conversation"},{key:"-t, --trust",description:"Auto-trust project (skip initial permission prompt)"},{key:"-p, --print [query]",description:"Run in non-interactive mode, output response and exit"},{key:"--dangerously-skip-permissions",description:"Bypass all permission prompts (use with caution)"},{key:"--add-dir <directory>",description:"Add directory to workspace context"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"--ide-setup",description:"Setup extension for editor context"},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],Ui=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/model",description:"Switch between Command Code models"},{key:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{key:"/compact",description:"Compact the conversation history"},{key:"/ide",description:"Setup extension to fetch editor context"},{key:"/login",description:"Authenticate with CommandCode via browser"},{key:"/logout",description:"Remove stored authentication"},{key:"/feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"/add-dir",description:"Manage additional directory scope"},{key:"/exit",description:"Exit the REPL"}],ji=[{key:"cmd info",description:"Display system information"},{key:"cmd config",description:"Manage CLI configuration"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Bi=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],zi=[{key:"cmd",description:"Start interactive session"},{key:'cmd "fix the login bug"',description:"Start with a task"},{key:"cmd -c",description:"Continue last conversation"},{key:"cmd -r",description:"Resume a past session"},{key:'cmd -p "your query"',description:"Run non-interactive query"},{key:"cmd --add-dir ../shared",description:"Start with additional directory scope"},{key:"cmd info",description:"Show system information"},{key:'cmd feedback "title"',description:"Open feedback form with title"}],Wi='Start with a prompt: cmd "fix the login bug"';bt(),Rn();var Hi="cmd";function getBinNames(){const e=getPackageJson();return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name]:[Hi]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||Hi;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||Hi}catch{return Hi}}function HelpMessage(){const e=getInvokedCommandName(),t=B(()=>Ui.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return L.createElement(z,{flexDirection:"column",paddingY:1},L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(z,null,L.createElement(W,{bold:!0},"Command Code"),L.createElement(W,{color:"gray"}," v","0.10.17")),L.createElement(W,{color:"gray"},Oi)),L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(W,{bold:!0},"Usage"),L.createElement(z,{paddingLeft:2},L.createElement(W,null,e," <command> [options]"))),L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(W,{bold:!0},"Options"),L.createElement(z,{flexDirection:"column",paddingLeft:2},Mi.map(t=>L.createElement(z,{key:t.key},L.createElement(W,null,t.key.replace(/^cmd/,e).padEnd(Li)),L.createElement(W,{color:"gray"},t.description))))),L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(W,{bold:!0},"Commands"),L.createElement(z,{flexDirection:"column",paddingLeft:2},ji.map(t=>L.createElement(z,{key:t.key},L.createElement(W,null,t.key.replace(/^cmd/,e).padEnd(Li)),L.createElement(W,{color:"gray"},t.description))))),L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(W,{bold:!0},"Slash Commands"),L.createElement(z,{flexDirection:"column",paddingLeft:2},t.map(e=>L.createElement(z,{key:e.key},L.createElement(W,null,e.key.padEnd(Li)),L.createElement(W,{color:"gray"},e.description))))),L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(W,{bold:!0},"Keyboard Shortcuts"),L.createElement(z,{flexDirection:"column",paddingLeft:2},_i.map(e=>L.createElement(z,{key:e.key},L.createElement(W,null,e.key.padEnd(Li)),L.createElement(W,{color:"gray"},e.description))))),L.createElement(z,{flexDirection:"column",marginBottom:1},L.createElement(W,{bold:!0},"Examples"),L.createElement(z,{flexDirection:"column",paddingLeft:2},zi.map(t=>L.createElement(z,{key:t.key},L.createElement(W,null,t.key.replace(/^cmd/,e).padEnd(Li)),L.createElement(W,{color:"gray"},t.description))))),L.createElement(z,{marginBottom:1},L.createElement(W,{color:"cyan"},"❯"),L.createElement(W,{color:"gray"}," ",Wi.replace(/cmd/,e))),L.createElement(z,{flexDirection:"column"},L.createElement(W,{bold:!0},"Links"),L.createElement(z,{flexDirection:"column",paddingLeft:2},Bi.map(e=>L.createElement(z,{key:e.key},L.createElement(W,null,e.key.padEnd(Li)),L.createElement(W,{color:"cyan"},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?L.createElement(HelpMessage,null):L.createElement(z,{flexDirection:"column"},L.createElement(W,{wrap:"wrap"},L.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return L.createElement(z,null,L.createElement(W,{color:"red"},t?he.pointer:he.warning),L.createElement(z,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?L.createElement(W,{color:"red",wrap:"wrap"},e):L.createElement(Markdown,{color:"red"},e)))}function InfoMessage({content:e}){return L.createElement(z,null,L.createElement(W,{dimColor:!0},he.info),L.createElement(z,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},L.createElement(Markdown,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return L.createElement(z,{flexDirection:"column",marginBottom:0,marginTop:-1},L.createElement(z,{columnGap:1},L.createElement(W,null,"⎿"," "),L.createElement(z,{flexGrow:1,flexShrink:1,minWidth:0},L.createElement(W,{color:n?"yellow":void 0},e))),t&&L.createElement(z,{marginLeft:3},L.createElement(W,{dimColor:!0},"See ",t)))}function IDEStatusMessage({status:e,ide:t,details:n}){return L.createElement(z,{flexDirection:"column"},L.createElement(z,null,"connected"===e&&L.createElement(W,null,L.createElement(W,{color:"green"},he.tick),L.createElement(W,null," Connected to "),L.createElement(W,{color:"cyan"},t)),"installed"===e&&L.createElement(W,null,L.createElement(W,{color:"green"},he.tick),L.createElement(W,null," Installed for "),L.createElement(W,{color:"cyan"},t)),"needs_reload"===e&&L.createElement(W,null,L.createElement(W,{color:"yellow"},he.circle),L.createElement(W,null," "),L.createElement(W,{color:"cyan"},t),L.createElement(W,null," extension needs reload")),"failed"===e&&L.createElement(W,null,L.createElement(W,{color:"red"},he.cross),L.createElement(W,null," Install failed")),"not_in_ide"===e&&L.createElement(W,null,L.createElement(W,{color:"yellow"},he.circle),L.createElement(W,null," Not in IDE"))),n?.map((e,t)=>L.createElement(W,{key:t,dimColor:!0}," ",e)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),Sn(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),bt(),__name(ErrorMessage,"ErrorMessage"),bt(),__name(InfoMessage,"InfoMessage"),bt(),__name(CommandResultMessage,"CommandResultMessage"),bt(),__name(IDEStatusMessage,"IDEStatusMessage"),Rn(),vt(),bt(),bt(),vt(),fn(),Cn(),Rn(),bt(),vt();var Gi=t.join(g.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(Gi);f.existsSync(e)||f.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!f.existsSync(Gi))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=f.readFileSync(Gi,"utf-8");return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null,...JSON.parse(e)}}catch{return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}}}function writeUpdatesConfig(e){ensureDir(),f.writeFileSync(Gi,JSON.stringify(e,null,2))}function updateUpdatesConfig(e){writeUpdatesConfig({...readUpdatesConfig(),...e})}function shouldCheckForUpdate(){const e=readUpdatesConfig();return!!e.autoUpdate&&Date.now()-e.lastCheckedAt>=e.checkIntervalMs}function recordUpdateCheck(){updateUpdatesConfig({lastCheckedAt:Date.now()})}function setPendingUpdate(e){updateUpdatesConfig({lastCheckedAt:Date.now(),pending:e})}function clearPendingUpdate(){updateUpdatesConfig({pending:null})}function getPendingUpdate(e){const t=readUpdatesConfig();return t.pending?t.pending.currentVersion!==e?(clearPendingUpdate(),null):t.pending:null}__name(function getDefaultConfig(){return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}},"getDefaultConfig"),__name(ensureDir,"ensureDir"),__name(readUpdatesConfig,"readUpdatesConfig"),__name(writeUpdatesConfig,"writeUpdatesConfig"),__name(updateUpdatesConfig,"updateUpdatesConfig"),__name(shouldCheckForUpdate,"shouldCheckForUpdate"),__name(recordUpdateCheck,"recordUpdateCheck"),__name(setPendingUpdate,"setPendingUpdate"),__name(clearPendingUpdate,"clearPendingUpdate"),__name(getPendingUpdate,"getPendingUpdate"),Cn();var qi=ue(T),Vi=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=v("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return Vi.version}function isAlphaVersion(e){return e.includes("alpha")}function filterVersions(e){return{stable:e.filter(e=>!e.includes("alpha")),alpha:e.filter(e=>e.includes("alpha"))}}function getLatestVersion(e){return 0===e.length?null:e.sort(Ge.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Ge.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Ge.gt(t,e))return{latestVersion:t,updateAvailable:!0}}return{latestVersion:e,updateAvailable:!1}}async function checkForUpdateAvailable(){const e=fetchVersions();if(!e)return null;const t=getCurrentVersion(),{stable:n,alpha:r}=filterVersions(e),{latestVersion:o,updateAvailable:s}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:o,updateAvailable:s}}async function executeUpdate(e){try{return await qi(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;if(!Ge.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=xe(`Updating ${e} → ${t.targetVersion}`).start(),r=await executeUpdate(t.targetVersion);if(clearPendingUpdate(),!r)return n.fail("Update failed"),void console.log("Run `cmd update` to try again.");n.succeed(`Updated to v${t.targetVersion}`)}async function performAutoUpdate(e){const{silent:t,updateInfo:n,onStart:r}=e||{};if(isLocalDevelopmentBuild())return{success:!1};const o=n||await checkForUpdateAvailable();return o?.updateAvailable?(r?.(o.latestVersion),await executeUpdate(o.latestVersion)?{success:!0,updateInfo:o}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:o})):{success:!1}}function getCurrentGitBranch(){try{return v("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","ignore"],cwd:process.cwd()}).trim()||null}catch(e){return null}}function getGitHeaderInfo(){return{branch:getCurrentGitBranch(),isLocal:isLocalDevelopmentBuild()}}function getModelShortName(e){const t=Object.values(pt).find(t=>t.id===e);return t?t.name.toLowerCase().replace(" ","-"):e.includes("sonnet")?"sonnet-4.5":e.includes("opus-4-6")?"opus-4.6":e.includes("opus")?"opus-4.5":"sonnet-4.5"}__name(shouldSkipUpdateSystem,"shouldSkipUpdateSystem"),__name(fetchVersions,"fetchVersions"),__name(getCurrentVersion,"getCurrentVersion"),__name(isAlphaVersion,"isAlphaVersion"),__name(filterVersions,"filterVersions"),__name(getLatestVersion,"getLatestVersion"),__name(determineUpdateTarget,"determineUpdateTarget"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(executeUpdate,"executeUpdate"),__name(checkForUpdateAsync,"checkForUpdateAsync"),__name(doUpdateCheck,"doUpdateCheck"),__name(maybeRunPendingUpdate,"maybeRunPendingUpdate"),__name(performAutoUpdate,"performAutoUpdate"),__name(getCurrentGitBranch,"getCurrentGitBranch"),__name(getGitHeaderInfo,"getGitHeaderInfo"),Sn(),__name(getModelShortName,"getModelShortName");var Ki=L.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const s=t?["header",...e]:e,a=Br();getTerminalWidth();const i=getPackageJson().version||"0.0.0",c=o?getModelShortName(o):"sonnet-4.5",l=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",u=l.replace(d,"~"),m=getGitHeaderInfo();return L.createElement(H,{items:s,key:n,style:{width:"100%"}},e=>{if("header"===e)return L.createElement(z,{key:"header",marginBottom:1,flexDirection:"column"},L.createElement(Be,{name:"vice"},L.createElement(W,null,a.trimEnd())),L.createElement(z,{flexDirection:"column",marginTop:1},L.createElement(z,null,L.createElement(W,{color:"gray"},"# "),L.createElement(W,{bold:!0},"Command Code"),L.createElement(W,{color:"gray"}," v",i)),L.createElement(W,{color:"gray"},"# models: ",c," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),L.createElement(z,null,L.createElement(W,{color:"gray"},"# ",u,m&&m.isLocal&&m.branch&&L.createElement(W,{color:"gray"}," (branch: ",m.branch,")")))));const t=e,n=(()=>{switch(t.role){case"user":return L.createElement(UserMessage,{content:t.input});case"assistant":return L.createElement(AssistantMessage,{content:t.input});case"tool":return L.createElement(ToolMessage,{name:os(t.name||""),input:t.input,output:t.output||"",isPending:ts(t),hasError:es(t),metadata:t.metadata,expandedOutput:r});case"bash":return L.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:ts(t),hasError:es(t)});case"system":return L.createElement(SystemMessage,{content:t.input});case"info":return L.createElement(InfoMessage,{content:t.input});case"error":return L.createElement(ErrorMessage,{content:t.input});case"command-result":return L.createElement(CommandResultMessage,{message:t.input,details:t.details,hasError:t.hasError??!1});case"ide-status":return L.createElement(IDEStatusMessage,{status:t.status,ide:t.ide,details:t.details});default:return L.createElement(L.Fragment,null)}})();return L.createElement(z,{key:t.id,marginBottom:1,width:"90%"},n)})});function getModelOptions(){return Object.values(pt).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}bt(),vt(),__name(getModelOptions,"getModelOptions");var Ji=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");V((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0;return L.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},L.createElement(z,null,L.createElement(W,{color:"#E4CCFF",bold:!0},"Select model")),L.createElement(z,{marginBottom:1},L.createElement(W,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),L.createElement(Ue,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const o=r.find(e=>e.label===t),s=o?.value===n,a=o?.description?`${o.label} (${o.description})`:o?.label||t;return L.createElement(z,null,L.createElement(W,{color:e?"green":"gray"},` ${a.padEnd(24)}`),L.createElement(W,{color:e?"green":"gray"},o?.modelName),s&&L.createElement(W,{color:"green"}," ✓"))}}),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press "),L.createElement(W,{dimColor:!0,bold:!0},"Esc"),L.createElement(W,{dimColor:!0}," to cancel")))},"ModelSelector");bt(),vt();var Yi=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[o]=_(0),s=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",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}],a=__name(e=>{const t=s.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),i=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),c=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const n=t.basename(e.filePath),r=t.relative(process.cwd(),e.filePath);return r&&!r.startsWith("../")&&r.length<50?r:n||e.filePath}catch{return e.filePath}},"getDisplayPath"),l=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},L.createElement(z,{marginBottom:1},L.createElement(W,{bold:!0,color:"yellow"},`${l()} ${"edit"===e.action?c():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&L.createElement(z,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c(),marginLeft:0}).diffContent),L.createElement(z,{marginBottom:1},L.createElement(W,{bold:!0},"Do you want to ",i()," ",L.createElement(W,{color:"cyan"},c()),"?")),L.createElement(Ue,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:o,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:"cyan"},e?he.pointer:" "),itemComponent:({label:e,isSelected:t})=>L.createElement(W,{color:t?"cyan":"white"},e.includes("(shift+tab)")?L.createElement(L.Fragment,null,e.split("(shift+tab)")[0],L.createElement(W,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?L.createElement(L.Fragment,null,e.split("(")[0],L.createElement(W,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt");bt(),Sn();var Qi=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");V((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,a=n&&-1===s;return L.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},L.createElement(z,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},L.createElement(z,null,L.createElement(W,{bold:!0},"Select AI Provider")),n&&L.createElement(z,{flexDirection:"row"},L.createElement(W,{dimColor:!0},"Current: "),L.createElement(W,{color:"green"},getProviderDisplayName(n)),a&&L.createElement(W,{color:"yellow"}," [OAuth enforced]"))),L.createElement(z,{marginBottom:0},L.createElement(W,{dimColor:!0},"Available Providers:")),L.createElement(Ue,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>L.createElement(W,{color:e?"cyan":"gray",bold:e},` ${t}`)}),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");bt();var Zi=__name(({staticKey:e})=>L.createElement(H,{items:[{staticKey:e}],key:e},()=>L.createElement(W,{key:e},"\0")),"Responsive");function RetryMessage({attempt:e}){const[t,n]=_(0);if(U(()=>{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 L.createElement(z,{marginBottom:1},L.createElement(W,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}bt(),__name(RetryMessage,"RetryMessage"),bt(),Mt();var Xi=[{mode:"both",label:"Both",description:"Restore conversation and code (recommended)"},{mode:"conversation",label:"Conversation only",description:"Rewind conversation, keep current code"},{mode:"files",label:"Code only",description:"Restore code, keep conversation"}],ec=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=B(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=_(Math.max(0,r.length-1)),[a,i]=_(Math.max(0,r.length-8)),[c,l]=_("checkpoint"),[d,u]=_(null),[m,g]=_(0),p=B(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),h=B(()=>p?Xi:Xi.filter(e=>"conversation"===e.mode),[p]);if(U(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),V((e,p)=>{p.escape?"mode"===c?(l("checkpoint"),u(null),g(0)):n():"checkpoint"===c?p.upArrow?s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t}):p.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(t-8+1),t}):p.return&&r.length>0&&(u(r[o]),l("mode"),g(0)):"mode"===c&&(p.upArrow?g(e=>Math.max(0,e-1)):p.downArrow?g(e=>Math.min(h.length-1,e+1)):p.return&&d&&h[m]&&t({messageId:d.messageId,mode:h[m].mode}))}),0===r.length)return L.createElement(z,{flexDirection:"column",paddingLeft:2,paddingTop:1},L.createElement(W,{color:"#E4CCFF",bold:!0},"Rewind"),L.createElement(W,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press "),L.createElement(W,{dimColor:!0,bold:!0},"Esc"),L.createElement(W,{dimColor:!0}," to close")));if("mode"===c&&d)return L.createElement(z,{flexDirection:"column",paddingLeft:2,paddingTop:1},L.createElement(W,{color:"#E4CCFF",bold:!0},"Rewind"),L.createElement(z,{marginBottom:1},L.createElement(W,{dimColor:!0},"Restore to: "),L.createElement(W,{color:"white"},truncateString2({text:d.userPrompt||"checkpoint",maxLength:50}))),L.createElement(z,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return L.createElement(z,{key:e.mode,flexDirection:"column"},L.createElement(z,{flexDirection:"row"},L.createElement(W,{color:n?"#E4CCFF":void 0},n?`${Ft} `:" "),L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:n?"#E4CCFF":"white"},e.label),L.createElement(W,{dimColor:!0},e.description))),!r&&L.createElement(W,null," "))})),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press "),L.createElement(W,{dimColor:!0,bold:!0},"Enter"),L.createElement(W,{dimColor:!0}," to confirm, "),L.createElement(W,{dimColor:!0,bold:!0},"Esc"),L.createElement(W,{dimColor:!0}," to go back")));const f=r.slice(a,a+8);return L.createElement(z,{flexDirection:"column",paddingLeft:2,paddingTop:1},L.createElement(W,{color:"#E4CCFF",bold:!0},"Rewind"),L.createElement(W,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),L.createElement(z,{marginTop:1}),L.createElement(z,{flexDirection:"column"},f.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,c=t===f.length-1,l=n===r.length-1;return L.createElement(z,{key:e.messageId,flexDirection:"column"},L.createElement(z,{flexDirection:"row"},L.createElement(W,{color:s?"#E4CCFF":void 0},s?`${Ft} `:" "),L.createElement(z,{flexDirection:"column"},L.createElement(z,null,L.createElement(W,{color:s?"#E4CCFF":"white"},truncateString2({text:e.userPrompt||"(no prompt)",maxLength:60})),L.createElement(W,{dimColor:!0}," • "),L.createElement(W,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),l&&" (latest)")),L.createElement(W,{dimColor:!0},i>0?`${i} file${i>1?"s":""} changed`:"No code changes"))),!c&&L.createElement(W,null," "))})),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press "),L.createElement(W,{dimColor:!0,bold:!0},"Enter"),L.createElement(W,{dimColor:!0}," to select, "),L.createElement(W,{dimColor:!0,bold:!0},"Esc"),L.createElement(W,{dimColor:!0}," to cancel")))},"RewindSelector");bt();var tc=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=K(),[r,o]=_([]),[s,a]=_(0),[i,c]=_(!0),[l,d]=_(0),u=30;U(()=>{m()},[]);const m=__name(async()=>{c(!0);const e=await Vs.listSessions();o(e),c(!1)},"loadSessions");if(V((t,o)=>{o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t}):o.downArrow?a(e=>{const t=Math.min(r.length-1,e+1);return t>=l+u&&d(t-u+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),i)return L.createElement(z,{flexDirection:"column",paddingLeft:2,paddingTop:1},L.createElement(W,{color:"gray"},"Loading sessions..."));const g=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5),a=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:s<7?`${s} day${s>1?"s":""} ago`:1===a?"1 week ago":`${a} weeks ago`},"formatRelativeTime"),p=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return L.createElement(z,{flexDirection:"column"},L.createElement(W,{color:"gray"},"No sessions available"));const h=r.slice(l,l+u),f=l;return L.createElement(z,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>u&&L.createElement(z,{marginBottom:1},L.createElement(W,{color:"dim"},"Showing ",l+1,"-",Math.min(l+u,r.length)," ","of ",r.length," sessions",l>0&&" (↑ for more)",l+u<r.length&&" (↓ for more)")),L.createElement(z,{columnGap:2,marginBottom:1},L.createElement(z,{width:7},L.createElement(W,{color:"gray"}," ")),L.createElement(z,{width:13},L.createElement(W,{color:"gray"},"Modified")),L.createElement(z,{width:11},L.createElement(W,{color:"gray"},"# Messages")),L.createElement(z,{width:20},L.createElement(W,{color:"gray"},"Git Branch")),L.createElement(z,null,L.createElement(W,{color:"gray"},"Summary"))),L.createElement(z,{columnGap:2},L.createElement(z,{flexDirection:"column",width:7},h.map((e,t)=>{const n=f+t;return L.createElement(W,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${he.pointer} ${n+1}.`:` ${n+1}.`)})),L.createElement(z,{flexDirection:"column",width:13},h.map((e,t)=>{const n=f+t;return L.createElement(W,{key:`mod-${e.id}`,color:s===n?"white":"gray"},g(e.lastModified))})),L.createElement(z,{flexDirection:"column",width:11},h.map((e,t)=>{const n=f+t;return L.createElement(W,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),L.createElement(z,{flexDirection:"column",width:20},h.map((e,t)=>{const n=f+t;return L.createElement(W,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),L.createElement(z,{flexDirection:"column"},h.map((e,t)=>{const n=f+t;return L.createElement(W,{key:`summary-${e.id}`,color:s===n?"white":"gray"},p(e.firstMessage))}))))},"SessionTable");function moveFocusDown(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?n>0?{...e,zone:"suggestions",suggestionIndex:0}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:e:"suggestions"===e.zone?e.suggestionIndex<n-1?{...e,suggestionIndex:e.suggestionIndex+1}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:{...e,zone:"input"}:e.activeDirIndex<r-1?{...e,activeDirIndex:e.activeDirIndex+1}:{...e,zone:"input"}}function moveFocusUp(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?r>0?{...e,zone:"active-dir",activeDirIndex:r-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:e:"suggestions"===e.zone?e.suggestionIndex>0?{...e,suggestionIndex:e.suggestionIndex-1}:{...e,zone:"input"}:e.activeDirIndex>0?{...e,activeDirIndex:e.activeDirIndex-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:{...e,zone:"input"}}function getAdjustedSuggestionOffset(e){const{selectedIndex:t,currentOffset:n,maxVisible:r,totalSuggestions:o}=e;return o<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),o=e.replace(/\\/g,"/");if(o.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${o.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:o};const s=o.lastIndexOf("/");return-1===s?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:o.slice(0,s+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),o=n.startsWith(".")||r.includes("/.");return f.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!o||!e.name.startsWith(".")).filter(e=>!n||e.name.toLowerCase().startsWith(n.toLowerCase())).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>`${r}${e.name}/`)}catch(e){const t=e.code;return"ENOENT"!==t&&"ENOTDIR"!==t&&console.error(`Warning: Could not list directory suggestions: ${t}`),[]}}function getFooterText(e){return"active-dir"===e.focusZone?"[Enter] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}bt(),It(),bt(),It(),__name(function createInitialFocusState(){return{zone:"input",suggestionIndex:0,activeDirIndex:0}},"createInitialFocusState"),__name(moveFocusDown,"moveFocusDown"),__name(moveFocusUp,"moveFocusUp"),__name(getAdjustedSuggestionOffset,"getAdjustedSuggestionOffset"),__name(getSuggestionBase,"getSuggestionBase"),__name(getDirectorySuggestions,"getDirectorySuggestions"),__name(getFooterText,"getFooterText");var nc=__name(({onClose:e})=>{const[t,n]=_(""),[r,o]=_(null),[s,a]=_([]),[i,c]=_(getAdditionalDirectories()),[l,d]=_({zone:"input",suggestionIndex:0,activeDirIndex:0}),[u,m]=_(0);U(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),U(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const g=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),c(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),p=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void c(getAdditionalDirectories());o({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),c(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");V((r,a)=>{if(a.escape)e();else{if(a.return)return"active-dir"===l.zone&&i[l.activeDirIndex]?void p(i[l.activeDirIndex]):"suggestions"===l.zone&&s[l.suggestionIndex]?void g(s[l.suggestionIndex]):void g(t);if((a.delete||a.backspace)&&"active-dir"===l.zone&&i[l.activeDirIndex])p(i[l.activeDirIndex]);else{if(a.tab&&s.length>0){const e=s[l.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}if(a.downArrow)d(e=>moveFocusDown(e,{suggestionCount:s.length,activeDirCount:i.length}));else if(a.upArrow)d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:i.length}));else if("input"===l.zone){if(a.backspace||a.delete)return n(e=>e.slice(0,-1)),void o(null);!r||a.ctrl||a.meta||(n(e=>e+r),o(null))}}}}),U(()=>{"suggestions"===l.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:l.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[l,s.length]),U(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=s.length?{...e,zone:"input",suggestionIndex:Math.max(0,s.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=i.length?{...e,zone:"input",activeDirIndex:Math.max(0,i.length-1)}:e)},[s.length,i.length]);const h=s.slice(u,u+8),f=getFooterText({focusZone:l.zone});return L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},L.createElement(W,{bold:!0,color:"cyan"},"Add directory to workspace"),L.createElement(W,{color:"gray"},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),L.createElement(z,{marginTop:1,flexDirection:"column"},L.createElement(W,{color:"gray"},"Added directories"),0===i.length?L.createElement(W,{color:"gray"}," None yet"):i.map((e,t)=>{const n="active-dir"===l.zone&&l.activeDirIndex===t;return L.createElement(W,{key:e,color:n?"yellow":"green",bold:n},n?` ${he.pointer} `:" ",formatDirectoryForDisplay(e))})),L.createElement(z,{marginTop:1},L.createElement(W,{bold:!0,color:"white"},"Path")),L.createElement(z,null,L.createElement(W,{color:"input"===l.zone?"cyan":"gray"},"input"===l.zone?he.pointer:" "),L.createElement(W,null," "),L.createElement(W,{color:"white"},t),"input"===l.zone&&L.createElement(W,{color:"gray"},"█")),!t&&L.createElement(z,{marginTop:1},L.createElement(W,{color:"gray"},"Examples: ../shared ~/docs /abs/path")),r&&L.createElement(z,{marginTop:1},L.createElement(W,{color:{error:"red",warning:"yellow",success:"green"}[r.tone]},r.text)),s.length>0&&L.createElement(z,{flexDirection:"column",marginTop:1},L.createElement(W,{color:"gray"},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===l.zone&&l.suggestionIndex===n;return L.createElement(W,{key:e,color:r?"cyan":"gray",bold:r},r?` ${he.pointer} `:" ",e)})),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},f)))},"AddDirModal");bt(),vt();var rc=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=_(0),o=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",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}],s=__name(e=>{const r=o.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),a=__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 L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},L.createElement(z,{marginBottom:1},L.createElement(W,{bold:!0,color:"yellow"},"Execute Shell Command")),L.createElement(z,{marginBottom:1},L.createElement(W,{bold:!0},"Command Code needs to execute ",L.createElement(W,{color:"cyan"},a()),".")),e.workingDirectory&&L.createElement(z,{marginBottom:1},L.createElement(W,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&L.createElement(z,{marginBottom:1},L.createElement(W,{color:"gray",italic:!0},e.description)),L.createElement(Ue,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:"cyan"},e?he.pointer:" "),itemComponent:({label:e,isSelected:t})=>L.createElement(W,{color:t?"cyan":"white"},e.includes("(shift+tab)")?L.createElement(L.Fragment,null,e.split("(shift+tab)")[0],L.createElement(W,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt");bt();var oc=__name(({onClose:e,staticKey:t})=>{const[n,r]=_([]),[o,s]=_(!0),[a,i]=_(null),{stdout:c}=q(),l=c?.columns??80,d=__name((e,t)=>e.length<=t?e:t<=3?e.substring(0,t):e.substring(0,t-3)+"...","truncateText");U(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),n=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];r(n)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=__name(async t=>{const r=n.find(e=>e.value===t.value);if(r)try{await qe([{file:r.filePath,line:1}]),Ea(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(m()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelect");V((t,n)=>{n.escape&&(Ea(),e())});const m=__name(()=>{const e=process.platform;return"win32"===e?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===e?"~/.zshrc":"~/.bashrc")},"getEditorSetupMessage");return o?L.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},L.createElement(W,{color:"#E4CCFF",bold:!0},"Agent Skills"),L.createElement(W,{dimColor:!0},"Loading skills...")):a?L.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},L.createElement(W,{color:"red",bold:!0},"Agent Skills"),L.createElement(W,{dimColor:!0},a),L.createElement(z,{marginTop:1}),L.createElement(W,{dimColor:!0},"Press ",L.createElement(W,{bold:!0},"Esc")," to close")):0===n.length?L.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},L.createElement(W,{color:"#E4CCFF",bold:!0},"Agent Skills"),L.createElement(z,{marginBottom:1},L.createElement(W,{dimColor:!0},"No skills found")),L.createElement(W,{dimColor:!0},"Create skills in:"),L.createElement(W,{dimColor:!0}," ~/.commandcode/skills/ (user)"),L.createElement(W,{dimColor:!0}," .commandcode/skills/ (project)"),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press ",L.createElement(W,{bold:!0},"Esc")," to close"))):L.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},L.createElement(z,null,L.createElement(W,{color:"#E4CCFF",bold:!0},"Agent Skills")),L.createElement(z,{marginBottom:1},L.createElement(W,{dimColor:!0},"Select a skill to open in your editor. Skills provide specialized guidance for coding tasks.")),L.createElement(Ue,{items:n,onSelect:u,initialIndex:0,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const r=n.find(e=>e.label===t),o=r?.location?` (${r.location})`:"",s=Math.max(30,l-35),a=r?.description?d(r.description,s):"";return L.createElement(z,null,L.createElement(W,{color:e?"green":"white"},` ${t}`),L.createElement(W,{color:"gray"},o.padEnd(25-t.length)),L.createElement(W,{color:"gray"},a))}}),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press ",L.createElement(W,{bold:!0},"Esc")," to cancel")))},"SkillsConfig");bt(),wn();var sc=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=_(!1),[s,a]=_(!0);U(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{a(!1)}},"loadSettings")()},[]),V((t,n)=>{if(!n.return&&" "!==t)return n.escape?(Ea(),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 s?L.createElement(z,{key:n,borderStyle:"single",borderColor:"blue",padding:1,flexDirection:"column"},L.createElement(W,{color:"blue",bold:!0},"Taste Settings"),L.createElement(W,{dimColor:!0},"Loading configuration...")):L.createElement(z,{key:n,borderStyle:"single",borderColor:"gray",padding:1,flexDirection:"column"},L.createElement(W,{bold:!0},"Taste Learning"),L.createElement(W,{dimColor:!0},"Configure taste learning preferences for this project"),L.createElement(z,{marginTop:1}),L.createElement(z,{justifyContent:"space-between"},L.createElement(W,null,"Taste learning",L.createElement(W,{dimColor:!0}," - Learn from your interactions")),L.createElement(W,{color:r?"green":"gray"},r?"enabled":"disabled")),L.createElement(z,{marginTop:1}),L.createElement(W,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),L.createElement(W,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig");bt(),fn(),bt(),bt();var ac=__name(e=>{const[t,n]=_(e),[r,o]=_(null);return U(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),o(null)},"handleReset"),r=__name(e=>{"error"!==e.type?n(t=>{if("step_start"===e.type){const n=t.findIndex(t=>t.id===e.step);return n<0?t:t.map((t,r)=>r<n?{...t,active:!1,complete:!0}:r===n?{...t,active:!0,message:e.message||"",...e.label&&{label:e.label},..."complete"===e.step&&{complete:!0},...void 0!==e.learningCount&&void 0!==e.categories&&void 0!==e.storage&&t.summary&&{summary:{learningCount:e.learningCount,categories:e.categories,storage:e.storage}}}:t)}if("progress"===e.type){const n=t.findIndex(e=>e.active);return n<0?t:t.map((t,r)=>r===n?{...t,items:[...t.items,e.message]}:t)}if("insight"===e.type){const n=t.findIndex(e=>"learning"===e.id);return n<0?t:t.map((t,r)=>r===n?{...t,insights:[...t.insights,e.message]}:t)}return t}):o(e.message)},"handleNewEvent");return ra.on("reset",t),ra.on("new-event",r),()=>{ra.off("reset",t),ra.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new ao({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;if(n===ut.ANTHROPIC)try{const e=await Nt.getValidAccessToken();validateOAuthToken({token:e,provider:n}),o=e}catch(e){dlog("Failed to get or validate Anthropic OAuth token:",e instanceof Error?e.message:String(e))}const s={[it.PROJECT_SLUG]:Vs.getCurrentProjectDirName(),[it.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(s[it.OAUTH_TOKEN]=`Bearer ${o}`),{request:t,headers:s}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}bt(),bt(),fn(),bt(),fn(),bt(),bt(),vt(),Ut(),fn(),wn(),kn(),__name(createRequestClient,"createRequestClient"),bt(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),bt(),bt(),vt(),fn(),Lt(),bt();var ic="claude-haiku-4-5-20251001";function buildObserverPrompt(e,t){return`Scan prompts. ${t} casual observations like a dev friend glancing at your work.\n\nPLAIN TEXT ONLY. No markdown, no formatting.\n\nBe natural and VARIED. Don't repeat the same sentence starters.\n\nGood (notice the variety):\npnpm over npm, nice\ndebugging that auth flow\nreact + typescript stack\ncircular deps came up\ntui flicker stuff\nah the classic memory leak\nsession persistence wip\nfighting with imports again\nhaiku model issues huh\n\nBad (too repetitive - NEVER do this):\nI see you prefer pnpm\nI see debugging auth\nI see react stack\nI see circular deps\noh, TUI issues\noh, memory leak\n\nRules:\n- plain text, lowercase is fine\n- vary your sentence starts - mix it up\n- max 6 words\n- sound human, not robotic\n\nPrompts:\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:`anthropic:${ic}`,max_tokens:200,temperature:.7,stream:!0},threadId:`observer-${Date.now()}`}}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),ra.addEvent({type:"insight",message:n}))}e=t[t.length-1]}},"emitCompletedLines");return{addText:__name(r=>{t++,dlog(`[ObserverAPI] text chunk ${t}: "${r.substring(0,50)}..."`),e+=r,n()},"addText"),emitRemaining:__name(()=>{e.trim()&&(dlog(`[ObserverAPI] emitting final insight: ${e.trim()}`),ra.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=Ne.fromReadableStream(e),dlog("[ObserverAPI] created MessageStream")}catch(e){throw dlog(`[ObserverAPI] MessageStream creation failed: ${e instanceof Error?e.message:String(e)}`),e}const n=createInsightEmitter();t.on("text",e=>{n.addText(e)});try{await t.finalMessage(),dlog(`[ObserverAPI] stream complete, ${n.getChunkCount()} chunks received`)}catch(e){throw dlog(`[ObserverAPI] stream failed: ${e instanceof Error?e.message:String(e)}`),e}n.emitRemaining()}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${ct.ALPHA.GENERATE} with model: ${ic}`);const r=buildRequestBody(n);let o;try{o=await e.post({endpoint:ct.ALPHA.GENERATE,body:r,headers:t,stream:!0}),dlog("[ObserverAPI] got response stream")}catch(e){throw dlog(`[ObserverAPI] request failed: ${e instanceof Error?e.message:String(e)}`),e}await processStream(o),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const a=buildObserverPrompt(n,4);await callObserverAPI(e,t,a)}async function observeSessionPrompts(e){if(ra.observerHasRun)return;ra.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${r.length} batches`);const o=Math.min(r.length,6);for(let t=0;t<o;t++){if(ra.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const o=r[t];try{await processBatch(e,n,o,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),ra.addEvent({type:"progress",message:"Continuing without live observations..."})}}__name(buildObserverPrompt,"buildObserverPrompt"),__name(buildRequestBody,"buildRequestBody"),__name(createInsightEmitter,"createInsightEmitter"),__name(processStream,"processStream"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var cc=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(m.homedir(),".claude","projects");await P.access(r);const o=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await P.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await P.stat(s)).isDirectory())continue;const r=(await P.readdir(s)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const o of r){const r=e.join(s,o),a=await P.stat(r),i=o.replace(".jsonl","");if(n.push({id:i,filePath:r,createdAt:a.birthtime,lastModified:a.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{ra.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&ra.addEvent({type:"progress",message:`Scanning Codex: ${e.processedFiles}/${e.totalFiles} files (${e.matchedSessions} matched)`})},e);return dlog(`[Import] found ${n.length} Codex sessions`),n}catch(e){return dlog("[Import] no codex sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await P.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[];try{ra.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const o=await loadProjectSettings(),s=o.tasteOnboarding?.learnedSessions||{},a=s["claude-code"]?.length||0,i=s.codex?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${i} learned`);const c=await findNewSessions(s),l=c["claude-code"]||[],d=c.codex||[],u=l.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${l.length} new, codex=${d.length} new`),0===u){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=e.length+t.length,r=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);ra.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:n>0?`From ${r.join(" + ")} sessions`:"No sessions found for this project"});const o=[];return e.length>0&&o.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&o.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:n,learnedSessions:a+i,agentSessions:o,status:"already-learned"}}if(l.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>l.includes(e.id));n.push(...e)}if(d.length>0){const e=(await this.findCodexSessions()).filter(e=>d.includes(e.id));r.push(...e)}const m=n.length+r.length;dlog(`[Import] total sessions: ${m} (claude-code: ${n.length}, codex: ${r.length})`),ra.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const g=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of g){ra.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const p=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${p.length} batches`);const h=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});ra.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${p.length} batch${1===p.length?"":"es"}`});try{const o=getApiBaseUrl(),s=new ao({baseUrl:o});let a=!0;for(let e=0;e<p.length;e++){const t=p[e],n=e+1,r=p.length;r>1&&ra.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),i=new sa({request:s,sessionId:`taste-import-batch-${e}-${Date.now()}`,projectRoot:process.cwd()}),c=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await i.checkAndProcess({messages:c})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),ra.markLearningComplete(),await h,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const i=await this.extractLearningSummary(),c=[];if(n.length>0&&c.push(`Claude Code (${n.length})`),r.length>0&&c.push(`Codex (${r.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),ra.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}return ra.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${c.join(" + ")}`,learningCount:i.totalLearnings,categories:i.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),ra.addEvent({type:"error",message:r}),{success:!1,totalPrompts:t.length,preferencesLearned:0,errors:e}}}catch(t){const n=t instanceof Error?t.message:String(t);return e.push(n),{success:!1,totalPrompts:0,preferencesLearned:0,errors:e}}}static async extractLearningSummary(){try{const t=e.join(process.cwd(),".commandcode","taste","taste.md"),n=await P.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),o=r?r.length:0;return{totalLearnings:o,categories:n.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}},lc=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),dc=__name(e=>{const[t,n]=_({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return U(()=>{ra.reset(),ra.markImportStarted(),(async()=>{try{const t=await Promise.race([cc.importAndLearn(),lc(12e4)]);if(t.success)return void n(e=>({...e,isImporting:!1,waitingForInput:!0}));if("already-learned"===t.status)return void n(e=>({...e,isImporting:!1,alreadyLearned:!0,learnedSessionCount:t.learnedSessions||0,totalSessionCount:t.totalSessions||0,agentSessions:t.agentSessions||[],waitingForInput:!0}));const r=t.errors.join("\n");n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}catch(t){const r=t instanceof Error?t.message:String(t);n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}})()},[e]),t},"useImportProcess");bt();var uc=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{V((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");bt(),fn();var mc=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=_(null),[o,s]=_(null),a=M(!1);return U(()=>{if(a.current)return;let n=null;return(async()=>{try{a.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{ra.reset(),e()}}async function skipOnboarding(e){try{await markOnboardingSkipped(),dlog("[Helper] onboarding marked skipped")}catch(e){dlog(`[Helper] skip error: ${e instanceof Error?e.message:String(e)}`)}finally{ra.reset(),e()}}bt(),fn(),bt(),fn(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var gc=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=M(n),o=j(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=j(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=j(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=j(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current())},[e]),c=j(async()=>{dlog("[Handler] demo complete → done"),e("done"),await markDemoShown(),await completeOnboarding(()=>r.current())},[e]),l=j(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current())},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:a,handleErrorDismiss:i,handleDemoComplete:c,handleSkip:l}},"useOnboardingHandlers");bt(),fn();var pc=__name(({conditions:e,autoLearn:t})=>{const[n,r]=_("checking"),o=M(!1);return U(()=>{if(e&&!o.current){if(o.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),U(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");bt(),bt();var hc=__name(({error:e})=>L.createElement(z,{padding:1},L.createElement(z,{flexDirection:"column",borderColor:"red",padding:1},L.createElement(z,{marginBottom:1},L.createElement(W,null,"Error initializing onboarding: ",e)),L.createElement(z,null,L.createElement(W,null,"Continuing without onboarding...")))),"OnboardingError");bt(),bt();var fc=[{type:"user",text:"I always prefer pnpm",duration:2e3},{type:"learned",text:"Learned: pnpm (95% preference)",details:".commandcode/taste/taste.md",duration:2e3},{type:"user",text:"I prefer commander over meow",duration:2e3},{type:"updated",text:"Updated: commander boosted (60% → 95%), meow adjusted (90% → 35%)",details:".commandcode/taste/cli/taste.md",duration:2e3},{type:"user",text:"I prefer TypeScript for Node CLIs",duration:2e3},{type:"learned",text:"Learned: TypeScript for CLIs (90% preference)",details:".commandcode/taste/cli/taste.md",duration:2e3}],yc=__name(({onComplete:e})=>{const[t,n]=_(0),[r,o]=_(!1),s=t>=fc.length;U(()=>{if(t>=fc.length)return;if(r)return;const e=fc[t],o=setTimeout(()=>{n(e=>Math.min(e+1,fc.length))},e.duration);return()=>clearTimeout(o)},[t,r]),V((t,r)=>{r.escape?e():s?(r.return||" "===t)&&e():" "===t?o(e=>!e):r.return&&n(e=>Math.min(e+1,fc.length))});const a=fc.slice(0,t);return L.createElement(z,{flexDirection:"column"},L.createElement(z,null,L.createElement(W,{color:"cyan"},"Meet Your Coding Taste")),L.createElement(z,null,L.createElement(W,null,"Command Code learns your coding style as you work.")),L.createElement(z,null,L.createElement(W,null,"Here's how your preferences evolve in real-time:")),L.createElement(z,{flexDirection:"column",marginY:1},0===a.length&&!s&&L.createElement(W,{dimColor:!0},"Starting demo..."),a.map((e,t)=>"user"===e.type?L.createElement(z,{key:t},L.createElement(W,{color:"white"},`${he.pointer} ${e.text}`)):L.createElement(z,{key:t,marginBottom:1,marginTop:0,marginLeft:1},L.createElement(z,null,L.createElement(W,null,"⎿"),L.createElement(z,{flexDirection:"column",marginLeft:2,marginTop:0},L.createElement(W,{color:"green"},e.text),e.details&&L.createElement(W,{dimColor:!0},"Saved(",e.details,")")))))),s&&L.createElement(z,{flexDirection:"column",marginY:1,width:80},L.createElement(z,null,L.createElement(W,{color:"green",bold:!0},"Demo Complete!"," ")),L.createElement(W,null,"Command Code will now use these preferences to generate better suggestions tailored to your coding style. The more you code, the smarter it gets."),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Press Enter to get started →"))),!s&&L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"," ",r?"(paused)":"")))},"TasteDemoComponent");bt(),vt();var Ec=__name(()=>`(run /${gt.LEARN_TASTE} anytime)`,"getSkipHint"),wc=__name(()=>L.createElement(W,null,"Skip for now"," ",L.createElement(W,{dimColor:!0},Ec())),"SkipOptionText"),bc=__name(({sessionCount:e,agentSessions:t,onImport:n,onDemo:r,onSkip:o,demoShown:s=!1})=>{const[a,i]=_(1),c=s?2:3,l=s?2:3;return V((e,t)=>{if(t.escape)o();else if(t.upArrow)i(e=>1===e?c:e-1);else if(t.downArrow)i(e=>e===c?1:e+1);else if("1"!==e)if("2"!==e)if("3"!==e||s){if(t.return){if(1===a)return void n();if(2===a)return void(s?o():r());o()}}else o();else s?o():r();else n()}),L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},L.createElement(W,{color:"cyan",bold:!0},"Build Your Coding Taste"),L.createElement(z,{marginTop:1,flexDirection:"column"},L.createElement(W,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),L.createElement(z,{marginTop:1},L.createElement(W,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),L.createElement(z,{marginTop:1,flexDirection:"column"},L.createElement(z,null,L.createElement(W,{color:1===a?"cyan":"gray"},1===a?he.pointer:" "," 1. Yes, learn from my sessions (recommended)")),!s&&L.createElement(z,null,L.createElement(W,{color:2===a?"cyan":"gray"},2===a?he.pointer:" "," ","2. No, show me a demo instead")),L.createElement(z,null,L.createElement(W,{color:a===l?"cyan":"gray"},a===l?he.pointer:" "," ",l,". ",L.createElement(wc,null)))),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice"),Sc=__name(({onDemo:e,onSkip:t})=>{const[n,r]=_(1);return V((o,s)=>{s.escape?t():s.upArrow||s.downArrow?r(e=>1===e?2:1):"1"!==o?"2"!==o?s.return&&(1===n?e():t()):t():e()}),L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",padding:1},L.createElement(W,{color:"cyan",bold:!0},"No Previous Sessions Found"),L.createElement(z,{marginTop:1,flexDirection:"column"},L.createElement(W,null,"No previous sessions found to analyze."),L.createElement(z,{marginTop:1},L.createElement(W,null,"Would you like to see how taste learning works?"))),L.createElement(z,{marginTop:1,flexDirection:"column"},L.createElement(z,null,L.createElement(W,{color:1===n?"cyan":"gray"},1===n?he.pointer:" "," 1. Yes, show me a demo")),L.createElement(z,null,L.createElement(W,{color:2===n?"cyan":"gray"},2===n?he.pointer:" "," 2."," ",L.createElement(wc,null)))),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"NoSessionsChoice");bt(),bt();var kc=__name(({error:e})=>L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"red",paddingX:2,paddingY:1,marginBottom:2},L.createElement(W,{color:"red",bold:!0},"Oops, something went wrong:"),L.createElement(z,{marginTop:1},L.createElement(W,null,e))),"ErrorSection");bt(),bt(),bt(),bt(),bt();var Cc=[he.bullet,he.squareSmallFilled,he.lozenge,he.star,he.triangleRight,he.triangleUp,he.circleFilled,he.pointer],vc=__name(()=>L.createElement(W,{backgroundColor:"green",color:"black"}," TASTE "),"TasteBadge"),Tc=["percolating","excavating","deciphering","triangulating","osmosing","metabolizing","grokking","spelunking","interpolating","marinating","crystallizing","synthesizing","calibrating","fermenting","coalescing","transmuting","simmering","distilling","ruminating","perusing","assimilating","untangling","decoding","absorbing","harmonizing","digesting","contemplating","extrapolating","materializing","finalizing"],Ac=__name(()=>{const[e,t]=_(()=>Math.floor(Math.random()*Tc.length));U(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*Tc.length))},2e3);return()=>clearInterval(e)},[]);const n=Tc[e];return L.createElement(W,{color:"yellow"},n,"...")},"PulsingText"),Pc=__name(e=>String(e).padStart(3," "),"padNum"),xc=__name(e=>Cc[e%Cc.length],"getSymbol"),Ic=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${Pc(t)} ↓${Pc(n)} (↑↓ scroll)`,"buildStatusLine"),Dc=__name(({insights:e})=>{const[t,n]=_(0),[r,o]=_(!0),s=e.length,a=s>10,i=Math.max(0,s-10);if(U(()=>{r&&a&&n(i)},[s,r,a,i]),V((e,t)=>{if(a)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(i,e+1);return t===i&&o(!0),t}))}),0===s)return null;const c=e.slice(t,t+10),l=t,d=s-t-10;return L.createElement(z,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&L.createElement(W,{dimColor:!0},Ic(s,l,d,r)),c.map((e,n)=>{const r=t+n;return L.createElement(z,{key:r,marginBottom:0},L.createElement(W,{dimColor:!0},xc(r)," ",e))}))},"ScrollableInsights"),Rc=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:c})=>{if(a)return L.createElement(z,{flexDirection:"column",marginBottom:0},L.createElement(vc,null),L.createElement(z,{marginTop:0},L.createElement(W,{dimColor:!0},"⎿"),L.createElement(z,{marginLeft:2},i?L.createElement(W,{color:"green"},"learned your coding taste"):L.createElement(Ac,null))));const l=__name(()=>{const[e,t]=_(!0);return U(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),L.createElement(W,{color:"yellow"},e?he.circleFilled:he.circle)},"PulsingDot"),d=__name(()=>r?L.createElement(W,{color:"green"},he.nodejs):n?L.createElement(l,null):L.createElement(W,{dimColor:!0},he.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||c&&c.learningCount>0;return!r||n||u?L.createElement(z,{flexDirection:"column",marginBottom:0},(n||r)&&L.createElement(z,{marginBottom:0},L.createElement(z,{marginRight:1},d()),L.createElement(W,{color:r?"white":n?"yellow":"dim"},e)),r&&t&&(!c||0===c.learningCount)&&L.createElement(z,{marginLeft:3,marginBottom:0},L.createElement(W,{dimColor:!0},t)),o.length>0&&L.createElement(z,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>L.createElement(W,{key:t,dimColor:!0},`${he.bullet} ${e}`))),s.length>0&&L.createElement(Dc,{insights:s}),r&&c&&c.learningCount>0&&L.createElement(z,{flexDirection:"column",marginLeft:1,marginBottom:0},L.createElement(z,{marginBottom:1,flexDirection:"row"},L.createElement(W,null,"⎿"),L.createElement(z,{marginLeft:2},L.createElement(W,{color:"green"},"Learned ",c.learningCount," preference",1===c.learningCount?"":"s",c.categories.length>0?` across ${c.categories.length} ${1===c.categories.length?"category":"categories"}`:""))),L.createElement(z,{flexDirection:"column",marginLeft:1},L.createElement(W,{dimColor:!0},he.pointerSmall," Stored in"," ",c.storage),L.createElement(W,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),$c=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return L.createElement(z,{flexDirection:"column",marginBottom:1},e.map((e,n)=>L.createElement(z,{key:e.id,marginLeft:0===n?0:3},L.createElement(Rc,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),Fc=__name(({steps:e})=>L.createElement($c,{steps:e}),"ProgressSection");bt();var Nc=__name(({isImporting:e=!1,waitingForInput:t=!1})=>L.createElement(L.Fragment,null,e&&L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"ESC to cancel")),t&&L.createElement(z,{marginTop:1},L.createElement(W,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");bt();var Oc=[{id:"importing",label:"Initializing Taste Profile",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"batching",label:"Organizing your sessions",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"learning",label:"Learning your coding taste",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"complete",label:"Learned your coding taste!",message:"",active:!1,complete:!1,items:[],insights:[],summary:{learningCount:0,categories:[],storage:".commandcode/taste/taste.md"}}],Lc=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=ac(Oc),{isImporting:s,waitingForInput:a,error:i}=dc(t);return uc({onEscape:e,onEnter:__name(()=>{a&&(i&&n?n():e())},"onEnter"),enabled:s||a}),L.createElement(z,{flexDirection:"column",padding:1},o&&L.createElement(kc,{error:o}),!o&&L.createElement(Fc,{steps:r}),L.createElement(Nc,{isImporting:s,waitingForInput:a}))},"ImportProgress"),_c=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onDemoComplete:a,onDemo:i,onSkip:c})=>"asking"===e?"has_sessions"!==t?.reason?L.createElement(Sc,{onDemo:i,onSkip:c}):L.createElement(bc,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onDemo:i,onSkip:c,demoShown:t.demoShown}):"learning"===e?L.createElement(Lc,{onComplete:r,onError:o,onErrorDismiss:s}):"demo"===e?L.createElement(yc,{onComplete:a}):null,"OnboardingStepRenderer"),Mc=__name(({onComplete:e,autoLearn:t=!1})=>{U(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=mc({autoLearn:t,onShouldSkip:e}),{step:s,setStep:a}=pc({conditions:n,autoLearn:t}),{handleImportStart:i,handleImportComplete:c,handleImportError:l,handleErrorDismiss:d,handleDemoComplete:u,handleSkip:m}=gc({onStepChange:__name(e=>{a(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?L.createElement(hc,{error:r}):"done"===s?null:L.createElement(_c,{step:s,conditions:n,onImportStart:i,onImportComplete:c,onImportError:l,onErrorDismiss:d,onDemoComplete:u,onDemo:()=>a("demo"),onSkip:m})},"TasteOnboarding");bt(),vt();var Uc=__name(({onTrust:e,onExit:t})=>{const{exit:n}=K(),[r,o]=_(1),s=process.cwd().replace(process.env.HOME||"","~");return V((s,a)=>{a.upArrow||a.downArrow?o(1===r?2:1):a.return?1===r?e():(t(),n()):"1"===s?e():("2"===s||a.escape||a.ctrl&&"c"===s)&&(t(),n())}),L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",padding:1},L.createElement(W,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),L.createElement(z,{marginTop:1},L.createElement(W,{color:"gray"},s)),L.createElement(z,{marginTop:1,flexDirection:"column"},L.createElement(W,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),L.createElement(z,{marginTop:1},L.createElement(W,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),L.createElement(z,{marginTop:1,flexDirection:"column"},L.createElement(z,null,L.createElement(W,{color:1===r?"cyan":"gray"},1===r?he.pointer:" "," 1. Yes, proceed")),L.createElement(z,null,L.createElement(W,{color:2===r?"cyan":"gray"},2===r?he.pointer:" "," 2. No, exit"))))},"TrustPrompt");bt(),bn(),Sn();var jc=__name(({onComplete:e,onCancel:t})=>{const[n,r]=_(!1),[o,s]=_(""),{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u,cancel:m}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return V((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");m()}}),n?L.createElement(yn,{onSuccess:()=>{e(!0,o?`Logged in as ${o} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,o?`Logged in as ${o}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):L.createElement(wr,{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u})},"LoginOverlay");bt(),bt(),kn();var Bc=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),zc=__name(e=>{const t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`},"formatUptime"),Wc=__name(({icon:e,label:t,children:n})=>L.createElement(W,null,L.createElement(W,{color:"cyan"},e," "),L.createElement(W,{dimColor:!0},t.padEnd(12)),n),"Row"),Hc=__name(({title:e})=>L.createElement(W,null,L.createElement(W,{color:"gray"},"───"),L.createElement(W,{color:"white"}," ",e," "),L.createElement(W,{color:"gray"},"─".repeat(35))),"Header"),Gc=__name(({title:e,marginTop:t=0,children:n})=>L.createElement(z,{flexDirection:"column",marginTop:t},L.createElement(Hc,{title:e}),L.createElement(z,{flexDirection:"column",paddingY:1},n)),"Section"),qc=__name(({cpuCount:e,totalMem:t})=>L.createElement(Gc,{title:"System Information"},L.createElement(Wc,{icon:pe.bullet,label:"Date"},L.createElement(W,null,formatDate())),L.createElement(Wc,{icon:pe.pointer,label:"Platform"},L.createElement(W,{color:"green"},Bc(m.platform())),L.createElement(W,{dimColor:!0}," ","(",m.platform(),", ",m.arch(),")")),L.createElement(Wc,{icon:pe.triangleUp,label:"Hostname"},L.createElement(W,null,m.hostname())),L.createElement(Wc,{icon:pe.bullet,label:"User"},L.createElement(W,{color:"yellow"},m.userInfo().username)),L.createElement(Wc,{icon:pe.bullet,label:"CPUs"},L.createElement(W,{color:"magenta"},e," cores")),L.createElement(Wc,{icon:pe.bullet,label:"Memory"},L.createElement(W,{color:"cyan"},t," GB")),L.createElement(Wc,{icon:pe.play,label:"Uptime"},L.createElement(W,null,zc(m.uptime()))),L.createElement(Wc,{icon:pe.arrowRight,label:"Home"},L.createElement(W,{dimColor:!0},m.homedir())),L.createElement(Wc,{icon:pe.pointer,label:"Shell"},L.createElement(W,null,process.env.SHELL||"N/A")),L.createElement(Wc,{icon:pe.bullet,label:"Node"},L.createElement(W,{color:"green"},process.version))),"SystemInfoSection"),Vc=__name(({cpus:e})=>L.createElement(Gc,{title:"CPU Details",marginTop:1},e.map((e,t)=>L.createElement(Wc,{key:t,icon:pe.bullet,label:`Core ${t}`},L.createElement(W,null,e.model.trim()),L.createElement(W,{color:"yellow"}," @ ",e.speed," MHz")))),"CPUDetailsSection"),Kc=__name(({networkInterfaces:e})=>L.createElement(Gc,{title:"Network",marginTop:1},Object.entries(e).map(([e,t])=>{const n=t?.filter(e=>"IPv4"===e.family&&!e.internal);return n&&0!==n.length?n.map((t,n)=>L.createElement(Wc,{key:`${e}-${n}`,icon:pe.bullet,label:e},L.createElement(W,{color:"green"},t.address))):null})),"NetworkSection"),Jc=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>L.createElement(z,{flexDirection:"column"},L.createElement(W,null,"System Information"),L.createElement(W,null,"─".repeat(40)),L.createElement(W,null,"Date ",formatDate()),L.createElement(W,null,"Platform ",Bc(m.platform())," (",m.platform(),","," ",m.arch(),")"),L.createElement(W,null,"Hostname ",m.hostname()),L.createElement(W,null,"User ",m.userInfo().username),L.createElement(W,null,"CPUs ",e.length," cores"),L.createElement(W,null,"Memory ",t," GB"),L.createElement(W,null,"Uptime ",zc(m.uptime())),L.createElement(W,null,"Home ",m.homedir()),L.createElement(W,null,"Shell ",process.env.SHELL||"N/A"),L.createElement(W,null,"Node ",process.version),r&&L.createElement(L.Fragment,null,L.createElement(W,null,"\n","CPU Details"),L.createElement(W,null,"─".repeat(40)),e.map((e,t)=>L.createElement(W,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),L.createElement(W,null,"\n","Network"),L.createElement(W,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>L.createElement(W,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Yc=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>L.createElement(z,{flexDirection:"column"},L.createElement(qc,{cpuCount:e.length,totalMem:t}),r&&L.createElement(Vc,{cpus:e}),r&&L.createElement(Kc,{networkInterfaces:n})),"StyledInfo"),Qc=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=K();U(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=m.cpus(),o=m.networkInterfaces(),s=Math.round(m.totalmem()/1024/1024/1024);return t?L.createElement(Jc,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e}):L.createElement(Yc,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e})},"InfoUI"),Zc={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},Xc=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),el=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(Xc("__CFBundleIdentifier","com.todesktop"))return"Cursor";const e=[process.env.VSCODE_GIT_ASKPASS_MAIN,process.env.VSCODE_GIT_ASKPASS_NODE,process.env.GIT_ASKPASS].filter(Boolean);for(const t of e){const e=t.toLowerCase();if(e.includes("cursor"))return"Cursor";if(e.includes("windsurf"))return"Windsurf"}return"vscode"===process.env.TERM_PROGRAM&&"1"===process.env.VSCODE_INJECTION?"VSCode":null},"detectIDE"),tl=__name(()=>{const e=el();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&Zc[t]?Zc[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),nl=__name(()=>{if("win32"===g.platform()){const e=process.env.COMSPEC;return e?i(e):process.env.SHELL?i(process.env.SHELL):"cmd.exe"}if(process.env.FISH_VERSION)return"fish";if(process.env.ZSH_VERSION)return"zsh";if(process.env.BASH_VERSION)return"bash";try{const e=process.ppid;if(e){const t=v(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=i(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?i(e):"N/A"},"getShellName"),rl=__name(()=>{const e=el();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),ol=__name(()=>{try{const e=v("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:Bc(g.platform()),terminal:tl(),shell:nl(),version:ol(),ide:rl()}}function buildGitHubIssueUrl(e){const t=getSystemInfo(),n=new URLSearchParams;if(n.append("template","1.bug_report.yml"),e){const t=e.slice(0,256).trim();t&&n.append("title",t)}return n.append("version",t.version),n.append("os",t.os),n.append("terminal",t.terminal),n.append("shell",t.shell),`https://github.com/CommandCodeAI/command-code/issues/new?${n.toString()}`}function createOSC8Link(e,t,n=!0){return`${n?"":""}]8;;${e}${t||e}]8;;${n?"":""}`}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),bt(),__name(createOSC8Link,"createOSC8Link"),bt(),bt(),fn();var sl=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;constructor(){this.filePath=e.join(m.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await P.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean).slice(-100);let t=0;this.buffer=e.map(e=>{try{return JSON.parse(e).p}catch{return t++,""}}).filter(Boolean),t>0&&dlog(`[PromptHistory] Skipped ${t} corrupted entries`)}catch(e){e instanceof Error&&"code"in e&&"ENOENT"===e.code||dlog(`[PromptHistory] Failed to load history: ${e instanceof Error?e.message:String(e)}`),this.buffer=[]}this.initialized=!0}}add(e){if(!e||0===e.trim().length)return;const t=e.length>500?e.slice(0,500)+"...":e;this.buffer.push(t),this.buffer.length>500&&(this.buffer=this.buffer.slice(-500)),this.writeQueue.push({p:t,t:Date.now()}),this.scheduleFlush()}getAt(e){if(e<0||e>=this.buffer.length)return;const t=this.buffer.length-1-e;return this.buffer[t]}count(){return this.buffer.length}getAll(){return[...this.buffer]}isInitialized(){return this.initialized}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,await this.flush()},100))}async flush(){if(0===this.writeQueue.length)return;if(this.isFlushing)return void this.scheduleFlush();if(this.writeFailures>=3)return void(this.writeQueue=[]);this.isFlushing=!0;const t=this.writeQueue;this.writeQueue=[];try{const n=e.dirname(this.filePath);await P.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await P.appendFile(this.filePath,r),this.writeFailures=0,await this.rotateIfNeeded()}catch(e){this.writeFailures++;const n=e instanceof Error?e.message:String(e);this.writeFailures<3?(this.writeQueue.unshift(...t),dlog(`[PromptHistory] Write failed, retrying (${this.writeFailures}/3): ${n}`)):dlog(`[PromptHistory] Write disabled after 3 failures: ${n}`)}finally{this.isFlushing=!1}}async rotateIfNeeded(){try{const e=await P.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await P.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await P.writeFile(this.filePath,n.join("\n")+"\n"),dlog(`[PromptHistory] Rotated: kept ${n.length} of ${t.length} entries`)}catch(e){dlog(`[PromptHistory] Rotation failed (non-critical): ${e instanceof Error?e.message:String(e)}`)}}async cleanup(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);const e=Date.now();for(;this.isFlushing;){if(Date.now()-e>=5e3){dlog("[PromptHistory] Cleanup timed out waiting for flush after 5000ms");break}await new Promise(e=>setTimeout(e,10))}await this.flush()}};function createHistoryManager(){return new sl}__name(createHistoryManager,"createHistoryManager"),bt();var al=__name((e,t)=>{if(!e.startsWith("option_"))return null;const n=e.slice(7),r=parseInt(n,10);return Number.isNaN(r)||r<0||r>t?null:r},"parseOptionIndex"),il=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r})=>{const o=[];e.forEach((s,a)=>{const i=a===t&&!r,c=n.has(a);let l,d;i?(l="●",d="cyan"):c?(l="✓",d="green"):(l="○",d="gray"),o.push(L.createElement(W,{key:a},L.createElement(W,{color:d},l),L.createElement(W,{color:i?"cyan":void 0}," ",s.header),a<e.length-1?L.createElement(W,{dimColor:!0}," | "):null))});const s=r;return o.push(L.createElement(W,{key:"review"},L.createElement(W,{dimColor:!0}," | "),L.createElement(W,{color:s?"cyan":"gray"},s?"●":"○"),L.createElement(W,{color:s?"cyan":void 0,bold:s}," ","Review"))),L.createElement(z,null,o)},"TabIndicator"),cl=__name(({questions:e,onResponse:t})=>{const[n,r]=_(0),[o,s]=_(new Map),a=M(new Map),[i,c]=_(""),[l,d]=_(new Set),[u,m]=_(null),[g,p]=_(!1),[h,f]=_(!1),[y,E]=_(!1),[w,b]=_(null),[S,k]=_(!1),C=e[n],v=C?.multiSelect??!1,T=o.get(n),A=C?[...C.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],P=A.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),x=new Map(P.map((e,t)=>[e.label,A[t]])),I=__name(e=>{"submit"===e.value?O():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),D=__name(()=>{if(!T||0===T.length)return 0;const e=T[0],t=C.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),R=__name(e=>{if(!g)if(v){const t=al(e.value,C.options.length-1);if(null===t)return;const n=C.options[t]?.label||"";d(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=al(e.value,C.options.length-1);if(null===t)return;p(!0);const n=C.options[t]?.label||"";N([n])}},"handleSelect"),$=__name(()=>{if(g)return;p(!0);const e=Array.from(l);N(e)},"handleMultiSelectDone"),F=__name(()=>{if(!g&&i.trim())if(v){const e=new Set(C.options.map(e=>e.label));d(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(i.trim()),n})}else p(!0),N([i.trim()])},"handleOtherSubmit"),N=__name(t=>{a.current.set(n,t);const o=new Map(a.current);s(o);const i=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){d(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),n?.multiSelect||1!==r?.length)c("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);c(t&&e?e:"")}},"restoreStateForQuestion");if(n<e.length-1){const e=n+1;i(e),r(e),p(!1),E(!1),b(null),k(!1)}else if(e.every((e,t)=>o.has(t)))d(new Set),c(""),f(!0),p(!1);else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(i(t),r(t)),p(!1),E(!1),b(null),k(!1)}},"finishQuestion"),O=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),U=__name(t=>{f(!1),r(t),k(!1),E(!1),b(null);const n=e[t],o=a.current.get(t);if(n?.multiSelect&&o){d(new Set(o));const e=o.find(e=>!n.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),n?.multiSelect||1!==o?.length)c("");else{const e=o[0],t=!n.options.some(t=>t.label===e);c(t&&e?e:"")}},"editQuestion"),j=__name(t=>{if(t<0||t>=e.length)return;v&&(l.size>0?a.current.set(n,Array.from(l)):a.current.delete(n),s(new Map(a.current))),p(!1),E(!1),b(null),k(!1);const o=e[t],i=a.current.get(t);if(o?.multiSelect&&i){d(new Set(i));const e=i.find(e=>!o.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),o?.multiSelect||1!==i?.length)c("");else{const e=i[0],t=!o.options.some(t=>t.label===e);c(t&&e?e:"")}r(t)},"navigateToQuestion"),B=__name(()=>{if(!u||!v)return;if("done"===u.value)return;const e=al(u.value,C.options.length-1);if(null===e)return;const t=C.options[e]?.label||"";d(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return V((t,r)=>{if(" "===t&&v&&!y&&B(),"d"!==t||!v||y||h||$(),!h&&!g){if(r.downArrow&&!y&&!S&&u&&P.length>0&&u.value===P[P.length-1]?.value&&E(!0),r.upArrow&&!y&&!S&&u&&P.length>0&&u.value===P[0]?.value&&(v?k(!0):(E(!0),b(P.length-1))),r.upArrow&&y){E(!1),b(P.length-1);const e=P[P.length-1];e&&m(e)}if(r.downArrow&&y)if(E(!1),v)k(!0);else{b(0);const e=P[0];e&&m(e)}if(r.upArrow&&S&&(k(!1),E(!0)),r.downArrow&&S){k(!1),b(0);const e=P[0];e&&m(e)}r.return&&S&&v&&$()}if(g||y||S||(h?r.leftArrow&&U(e.length-1):r.leftArrow&&n>0?j(n-1):r.rightArrow&&(n<e.length-1?j(n+1):(v&&(l.size>0?a.current.set(n,Array.from(l)):a.current.delete(n),s(new Map(a.current))),f(!0)))),r.escape&&!g)if(h)f(!1);else if(y){E(!1);const e=w??P.length-1;b(e);const t=P[e];t&&m(t)}else if(S){k(!1);const e=P[P.length-1];e&&m(e)}}),C||h?h?L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},L.createElement(z,{marginBottom:1},L.createElement(il,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>L.createElement(z,{key:t,marginBottom:1,flexDirection:"column"},L.createElement(W,{dimColor:!0},t+1,". ",e.question),L.createElement(W,{color:"green"}," ",o.get(t)?.join(", ")||"No answer"))),L.createElement(Ue,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:I,initialIndex:0,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:"cyan"},e?he.pointer:" "),itemComponent:({label:e,isSelected:t})=>L.createElement(W,{color:t?"cyan":"white"},e)}),L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},he.arrowLeft," to go back and edit"))):L.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},L.createElement(z,{marginBottom:1},L.createElement(il,{questions:e,currentIndex:n,answeredQuestions:new Set(o.keys()),isReviewPage:!1})),L.createElement(z,{marginBottom:1},L.createElement(W,{bold:!0},C.question)),y||S?L.createElement(z,{flexDirection:"column"},P.map((e,t)=>{const n=x.get(e.label),r=v&&n&&l.has(n.label),o=!v&&n&&T?.includes(n.label),s=r||o;return L.createElement(z,{key:t,flexDirection:"column"},L.createElement(z,null,L.createElement(W,null," "),L.createElement(W,{color:s?"green":"white"}," ",t+1,"."," "),v&&(s?L.createElement(W,{color:"green"},"[",he.tick,"]"," "):L.createElement(W,{dimColor:!0},"[ ] ")),L.createElement(W,{color:s?"green":"white"},n?.label||""),!v&&s&&L.createElement(W,{color:"green"}," ",he.tick)),n?.description&&L.createElement(z,null,L.createElement(W,null," "),L.createElement(W,{dimColor:!0},v?" ":" ",n.description)))})):L.createElement(Ue,{key:`${n}-${w??"default"}`,items:P,initialIndex:w??D(),onSelect:R,onHighlight:m,indicatorComponent:({isSelected:e})=>L.createElement(W,{color:"cyan"},e?he.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=x.get(e),r=v&&n&&l.has(n.label),o=!v&&n&&T?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",c=a?.[2]||e;return L.createElement(z,{flexDirection:"column"},L.createElement(z,null,L.createElement(W,{color:t?"cyan":s?"green":"white"}," ",i,"."," "),v&&(s?L.createElement(W,{color:"green"},"[",he.tick,"]"," "):L.createElement(W,{dimColor:!0},"[ ] ")),L.createElement(W,{color:t?"cyan":s?"green":"white"},c),!v&&s&&L.createElement(W,{color:"green"}," ",he.tick)),n?.description&&L.createElement(W,{dimColor:!0},v?" ":" ",n.description))}}),L.createElement(z,null,L.createElement(W,{color:"cyan"},y?he.pointer:" "),L.createElement(W,{color:y?"cyan":void 0}," ",P.length+1,"."," "),v&&(l.has(i.trim())?L.createElement(W,{color:"green"},"[",he.tick,"] "):L.createElement(W,{dimColor:!0},"[ ] ")),L.createElement(Ve,{value:i,onChange:e=>{const t=i.trim();c(e),v&&d(n=>{const r=new Set(n);return t&&r.has(t)&&r.delete(t),e.trim()&&r.add(e.trim()),r})},onSubmit:F,placeholder:"Type something...",focus:y})),v&&L.createElement(z,null,L.createElement(W,{color:"cyan"},S?he.pointer:" "),L.createElement(W,{color:S?"cyan":void 0,bold:S}," ",n===e.length-1?"Submit":"Next")),e.length>1&&L.createElement(z,{marginTop:1},L.createElement(W,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function LiveAgentStatusInner({entry:e}){const t=os(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,a=e.metadata?.elapsedSeconds||0,i=e.metadata?.recentTools||[],[c,l]=_(".");return U(()=>{const e=setInterval(()=>{l(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),L.createElement(z,{flexDirection:"column",marginBottom:1,width:"90%"},L.createElement(z,null,L.createElement(W,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${t} `),o&&L.createElement(W,null," ","(",o,")")),L.createElement(z,{columnGap:1,marginLeft:1},L.createElement(W,null,"⎿"," "),L.createElement(W,{color:"gray"},"Running (",formatTime2(a)," | ",formatTokens(s),")",c)),i.length>0&&L.createElement(z,{flexDirection:"column",marginLeft:1},i.map((e,t)=>{const n=os(e.name);return L.createElement(z,{key:t,columnGap:1},L.createElement(W,{color:"gray"},"⎿"),L.createElement(W,{color:"gray"}," ",n),e.input&&L.createElement(W,{color:"gray"},"(",e.input,")"))})))}function LiveAgentStatus({entry:e}){return"tool"!==e.role?null:L.createElement(LiveAgentStatusInner,{entry:e})}bt(),kn(),__name(LiveAgentStatusInner,"LiveAgentStatusInner"),__name(LiveAgentStatus,"LiveAgentStatus");var{setText:ll}=Ie,{runIDESetup:dl}=await Promise.resolve().then(()=>(dr(),lr));function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}__name(createKillShellPermissionRequest,"createKillShellPermissionRequest");var ul=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:o,updateFailedInfo:s,initialPrompt:a,skipOnboarding:i=!1})=>{const{exit:c}=K(),[l,d]=_(""),[u,m]=_("Ready..."),g=M(!1),[p,h]=_(null),[f,y]=_(o);U(()=>{if(f){const e=setTimeout(()=>{y(null)},3e4);return()=>clearTimeout(e)}},[f]);const{stdout:E}=q(),[w,b]=_(!1),[S,k]=_(!1),[C,v]=_(!1),[T,A]=_(!1),[P,x]=_(!1),[I,D]=_(!1),[R,$]=_(!1),[F,N]=_(!1),[O,B]=_(null),[H,G]=_(null),[J,Y]=_(getConfiguredModel()),[Q,Z]=_(!1),[ee,te]=_(!1),[ne,re]=_(!1),oe=M(null),se=M(null),[ae,ie]=_(0),[ce,le]=_(!1),{executeBash:de,executionState:ue}=ha(),[me,ge]=_(""),[pe,he]=_([]),[fe,ye]=_([]),[Ee,we]=_(!1),[be,Se]=_([]),[ke,Ce]=_(crypto.randomUUID()),[ve,Te]=_(!1),[Ae,Pe]=_(!1),[xe,Ie]=_(!1),De=M(null),[Re,$e]=_(!1),[Fe,Ne]=_(!1),[Oe,Le]=_(!0),[_e,Me]=_(!1),[Ue,je]=_(!1),[Be,ze]=_(null),[We,He]=_(!1),Ge=M(!1),[qe,Ve]=_(!1),[Ke,Je]=_(0),[Ye,Qe]=_(null),[Ze,Xe]=_(null),[et,tt]=_(null),nt=M(!1),rt=M(!1),ot=M(et);U(()=>{ot.current=et},[et]);const[st,at]=_(!1),[it,lt]=_(""),[dt,ut]=_(!1),[mt,ht]=_(!!r),[ft,yt]=_(""),Et=M(null),wt=M(null),bt=__name(()=>{Et.current&&clearTimeout(Et.current),wt.current&&clearTimeout(wt.current),oe.current&&clearTimeout(oe.current),se.current&&clearTimeout(se.current)},"cleanupTimers"),[St,Ct]=_(!1),[vt,Tt]=_(!1),At=M(null),Pt=M(0),[xt,It]=_(null),Dt=j(()=>{At.current=null,It(null),wt.current&&(clearTimeout(wt.current),wt.current=null)},[]);U(()=>{if(qe){bt();try{c()}catch{process.exit(0)}}},[qe,c]);const Rt=j(()=>{je(!0),Me(!1),He(!1),Ea(),ie(e=>e+1),e&&Te(!0)},[e,t]),$t=__name(async()=>{try{const e=await isTasteLearningEnabled();ut(e),e&&await Wa.initializeProject()}catch(e){}},"loadTasteStatus"),Ft=__name(async()=>{const e=await getConfiguredProvider();G(e);const t=await isOAuthEnforced();Z(t)},"loadCurrentProvider"),Ot=M([]),Lt=M(null),_t=M(null),[Mt,Ut]=_(null),[jt,Bt]=_(null),{requestShellPermission:zt,service:Wt,respondToPrompt:Ht,clearSessionPermissions:Gt,setEnabled:qt}=ya({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{Ut({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),Lt.current&&m("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Ut({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),Lt.current&&m("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?m("Permission granted"):m("Permission denied")},"onPermissionResponse")}),Vt=__name(e=>{Et.current&&clearTimeout(Et.current),yt(e),Et.current=setTimeout(()=>{yt(""),Et.current=null},5e3)},"showHintMessage");U(()=>()=>bt(),[]),U(()=>{Wt&&applyAutoAcceptMode({enabled:mt,service:Wt})},[mt,Wt]),U(()=>{(async()=>{if(await Vs.isProjectInitialized())if(Ne(!0),Le(!1),$t(),Ft(),t){const e=await Vs.listSessions();if(e.length>0){const t=e[0];En(t.id)}}else e&&Te(!0);else if(n)if(await Vs.initializeProject(),Ne(!0),Le(!1),$t(),Ft(),t){const e=await Vs.listSessions();if(e.length>0){const t=e[0];En(t.id)}}else e&&Te(!0);else isDirectoryEmpty()?(await Vs.initializeProject(),Ne(!0),Le(!1),$t(),Ft()):($e(!0),Le(!1))})()},[e,t,n,c]),U(()=>{i||triggerTasteOnboarding({projectTrusted:Fe,onboardingComplete:Ue,isOnboardingMode:_e,tasteOnboardingCheckedRef:Ge,setIsOnboardingMode:Me})},[Fe,Ue,_e,i]),U(()=>{if(_e&&!Be){const e=Ko();ze(e.id),he(t=>[...t,e])}else!_e&&Be&&(he(e=>e.filter(e=>e.id!==Be)),ze(null))},[_e,Be]),U(()=>{Ot.current=be},[be]),U(()=>{(async()=>{if(H&&"anthropic"===H&&Q)try{await Nt.getValidAccessToken()||m("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){m("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[H,Q]),U(()=>{if(!Ee)return void(g.current=!1);if(null!==p)return;const e=setInterval(()=>{g.current||m(rs())},7e3);return()=>clearInterval(e)},[Ee,p]);const Kt=j(()=>{const e=!Ee&&!Mt&&!jt,t=Lt.current?.hasCheckpoints()??!1;e&&t&&Ct(!0)},[Ee,Mt]),Jt=j(()=>{if(!Lt.current)return;Lt.current.interrupt(!0);const e=fe.length>0;if(we(!1),h(null),ye([]),m("Interrupted by user"),!e){const e=Vo("Interrupted by user");he(t=>[...t,e])}if(Ot.current.length>0){const e=Ot.current.join("\n");d(t=>t?e+"\n"+t:e),Se([]),Ot.current=[]}},[fe]),Yt=__name(()=>{ht(e=>{const t=!e;return t&&Mt&&(Ht({label:"Yes",value:"yes",description:"Allow this action",scope:void 0}),Mt.resolve(!0),Ut(null)),t})},"handleToggleAutoAccept");async function getBillingLink(){if(Ze)return Ze;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return Xe(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return Xe(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}V((e,t)=>{if(t.shift&&t.tab||""===e)Yt();else if(C||T||P||I||R||O||F||St||vt||Ae)xt&&Dt();else{if(""===e||t.ctrl&&"c"===e){if(Ee&&Lt.current)return void Jt();const e=Date.now(),t=e-Pt.current;return Pt.current=e,void("ctrl-c"===At.current&&t<2e3?(wt.current&&(clearTimeout(wt.current),wt.current=null),Ve(!0)):(d(""),At.current="ctrl-c",It("ctrl-c"),wt.current&&clearTimeout(wt.current),wt.current=setTimeout(()=>{At.current=null,It(null),wt.current=null},2e3)))}if(t.ctrl&&"t"===e)return Ea(),N(e=>!e),void ie(e=>e+1);if(getIsExpandToolShortcut(t,e))return Ea(),le(e=>!e),void ie(e=>e+1);if(t.meta&&"p"===e||isAltP(e))D(!0);else{if(t.escape){if(jt)return jt.reject(new Error("Question cancelled by user")),Bt(null),void m("Question cancelled");Mt?(Ht({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),Mt.resolve(!1),Ut(null),m("Permission denied")):Ee&&Lt.current&&Jt()}t.meta||t.ctrl}}}),U(()=>{const e=__name(()=>{Ea(),ie(e=>e+1)},"handleResize");if(E)return E.on("resize",e),()=>{E.off("resize",e)}},[E]),U(()=>{Lt.current||!Fe||ve||xe||(Lt.current=new da({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?ye(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(ye(t=>t.filter(t=>t.id!==e.id)),he(t=>[...t,e])):he(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Ot.current];return Ot.current=[],Se([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Je(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Qe(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{h(e)},"onRetryUpdate"),onProviderChange:__name(e=>{G(e)},"onProviderChange"),onStatusUpdate:__name(e=>{g.current=!0,m(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&Wt){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 Wt.requestShellPermission(n).then(e=>e.allowed)}if("kill_shell"===e&&Wt){const e=createKillShellPermissionRequest(t);return Wt.requestShellPermission(e).then(e=>e.allowed)}if(Wt){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 Wt.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Bt({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const e=ot.current;return e?{sessionId:ke,secret:e.secret}:null},"getShareInfo")},ke),(async()=>{await cn()})())},[ke,ve,xe,Fe]),U(()=>{if(!Fe)return;const e=createHistoryManager();return De.current=e,e.init(),()=>{e.cleanup()}},[Fe]),U(()=>{a&&Fe&&!Oe&&Lt.current&&!ve&&!rt.current&&(rt.current=!0,Qt({role:"user",input:a}))},[a,Fe,Oe,ve]),__name(getBillingLink,"getBillingLink");const Qt=__name(async({role:e,input:t,images:n,ideContext:r})=>{if(t.length)if(f&&y(null),Je(0),"bash"===e){if(nt.current)return;nt.current=!0;const e=Go(t);he([...pe,e]),d(""),await de(t,e=>{he(e)},()=>{Ea(),ie(e=>e+1)}),nt.current=!1}else{if(Ee)return Se(e=>[...e,t]),void d("");if(nt.current)return;nt.current=!0,we(!0),m(rs()),d("");try{Lt.current&&await Lt.current.sendMessage(t,n,r)}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){m("Insufficient credits");const e=await getBillingLink(),t=Vo(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);he(e=>[...e,t])}else if(e.message.startsWith("Error:")){m("Error");const t=Vo(e.message);he(e=>[...e,t])}else{m("Error");const t=e.message||"An unexpected error occurred",n=Vo(t);he(e=>[...e,n])}}finally{we(!1),"Interrupted by user"!==u&&"Permission denied"!==u&&"Insufficient credits"!==u&&m("Ready..."),nt.current=!1}}},"handleSubmit"),Zt=__name(()=>{he(e=>[...e,qo("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),Xt=__name(()=>{const e=Bo(`/${gt.TERMINAL_SETUP}`),t=setupVSCodeTerminal(),n=Jo(t.message,!t.success,t.details);he(t=>[...t,e,n])},"handleTerminalSetupCommand"),en=__name(async()=>{const e=await dl(),t=Yo(e.status,e.ide,e.details);he(e=>[...e,t])},"handleIDESetupCommand"),tn=__name(async()=>{if(he([]),ye([]),Ea(),ht(!!r),tt(null),at(!1),lt(""),Lt.current){const e=Lt.current.getSessionManager();e&&await e.deleteShareInfo(),Lt.current=null;const t=crypto.randomUUID();Ce(t),Gt(),Lt.current=new da({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?ye(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(ye(t=>t.filter(t=>t.id!==e.id)),he(t=>[...t,e])):he(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Ot.current];return Ot.current=[],Se([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Je(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Qe(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{h(e)},"onRetryUpdate"),onProviderChange:__name(e=>{G(e)},"onProviderChange"),onStatusUpdate:__name(e=>{g.current=!0,m(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&Wt){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 Wt.requestShellPermission(n).then(e=>e.allowed)}if("kill_shell"===e&&Wt){const e=createKillShellPermissionRequest(t);return Wt.requestShellPermission(e).then(e=>e.allowed)}if(Wt){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 Wt.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Bt({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const e=ot.current;return e?{sessionId:t,secret:e.secret}:null},"getShareInfo")},t)}ie(e=>e+1),Qe(null),Je(0)},"handleClearCommand"),nn=__name(()=>{Lt.current?Lt.current.hasCheckpoints()?Ct(!0):he(e=>[...e,zo("No checkpoints available. Start sending messages to create checkpoints.")]):he(e=>[...e,zo("No active conversation to rewind.")])},"handleRewindCommand"),rn=__name(async e=>{const{messageId:t,mode:n}=e;if(Ct(!1),Lt.current)try{const e=Lt.current.listCheckpoints().find(e=>e.messageId===t);m("Restoring checkpoint...");const r=await Lt.current.restoreToCheckpoint({messageId:t,mode:n});if(r.success){const t=Lt.current.getSessionManager(),n=Lt.current.getMessages(),o=t.reconstructFeedFromMessages(n);he(o),Ea(),ie(e=>e+1),e&&e.userPrompt&&d(e.userPrompt);const s=[];r.filesRestored>0&&s.push(`${r.filesRestored} file${r.filesRestored>1?"s":""} restored`),r.filesDeleted>0&&s.push(`${r.filesDeleted} file${r.filesDeleted>1?"s":""} deleted`),r.messagesRemoved>0&&s.push(`${r.messagesRemoved} message${r.messagesRemoved>1?"s":""} removed`);const a=s.length>0?`Restored to checkpoint: ${s.join(", ")}.`:"Restored to checkpoint.";he(e=>[...e,zo(a)]),m("Ready...")}else he(e=>[...e,Vo(`Failed to restore: ${r.error}`)]),m("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;he(e=>[...e,Vo(t)]),m("Ready...")}},"handleRewindSelect"),on=__name(()=>{Ct(!1)},"handleRewindCancel"),sn=__name(async()=>{if(Lt.current)if(Lt.current.isRequestInProgress())he(e=>[...e,zo("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{we(!0),m("Compacting conversation...");const e=await Lt.current.manualCompact();Ea(),ie(e=>e+1);let t="Compacted conversation.";e.didCompact||(t="Conversation is already compact."),e.didCompact&&e.tokensSaved>0&&(t=`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`),he(e=>[...e,zo(t)]),we(!1),m("Ready..."),Qe({current:Lt.current.getContextTokensUsed()||0,limit:Gs})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;he(e=>[...e,Vo(t)]),we(!1),m("Ready...")}else he(e=>[...e,zo("No active conversation to compact.")])},"handleCompactCommand"),an=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await En(t)}const t=parseCommandInput({input:e});if(!t)return;const{commandName:n,rawArguments:r,positionalArgs:o}=t;switch(n){case"/exit":return void Ve(!0);case"/clear":return void await tn();case"/help":return void Zt();case"/share":return void ln();case"/unshare":return void fn();case"/taste":return void v(!0);case"/learn-taste":return void await yn();case"/skills":return void A(!0);case"/provider":return void(isInternalTeamFlagEnforced()?x(!0):m("Provider selection not available"));case"/model":return void D(!0);case"/memory":return void $(!0);case"/init":return void dn();case"/agents":return void k(!0);case"/compact":return void await sn();case"/rewind":return void nn();case"/login":return void await un();case"/logout":return void await pn();case"/feedback":return void await hn();case"/terminal-setup":return void Xt();case"/ide":return void await en();case"/add-dir":return void Pe(!0)}const s=getCustomCommandContent(n);if(s){const e=processCommandTemplate({template:s,rawArguments:r,positionalArgs:o});await Qt({input:e.content,role:"user"})}},"handleCommand"),cn=__name(async()=>{const e=Lt.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&tt({url:t.url,secret:t.secret})}},"loadShareInfo"),ln=__name(async()=>{if(ke){if(et)return await ll(et.url),m(""),at(!0),void setTimeout(()=>{at(!1)},3e3);try{m("Creating share link...");const e=Lt.current?.getMessages()||[],t=Jr.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new ao({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:ct.ALPHA.SHARE.CREATE,body:{sessionId:ke,messages:t}}),o={url:r.url,secret:r.secret};tt(o);const s=Lt.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await ll(r.url),m(""),at(!0),setTimeout(()=>{at(!1)},5e3)}catch(e){m(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else m("No active session to share")},"handleShareCommand"),dn=__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.`;he(e=>[...e,zo(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;he(e=>[...e,zo(t)])}},"handleInitCommand"),un=__name(async()=>{const e=kt();if(await getAuthKey(e)){let e="";try{const t=await loadCredentials();e=t?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const t=e&&"API Key"!==e&&"Manual API Key"!==e?` as ${e}`:"";return void he(e=>[...e,zo(`Already logged in${t}`)])}Tt(!0)},"handleLoginCommand"),mn=j((e,t)=>{Tt(!1),e?(he(e=>[...e,zo(t)]),Lt.current&&Lt.current.refreshRequest()):he(e=>[...e,Vo(t)]),m("Ready...")},[]),gn=j(()=>{Tt(!1),he(e=>[...e,zo("Authentication cancelled.")]),m("Ready...")},[]),pn=__name(async()=>{const e=await performLogout();e.success?(Lt.current&&Lt.current.refreshRequest(),e.wasAuthenticated?e.warnings.length>0?he(t=>[...t,zo(`Successfully logged out from Command Code. Warnings: ${e.warnings.join(", ")}`)]):he(e=>[...e,zo("Successfully logged out from Command Code.")]):he(e=>[...e,zo("Not currently authenticated.")])):he(t=>[...t,Vo(`Logout failed: ${e.error}`)])},"handleLogoutCommand"),hn=__name(async e=>{const t=buildGitHubIssueUrl(e);try{await X(t,{wait:!1,background:!0}),he(e=>[...e,zo(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`)])}catch(e){he(e=>[...e,Vo("Failed to open browser"),qo(createOSC8Link(t,"Open GitHub issue manually"))])}},"handleFeedbackCommand"),fn=__name(async()=>{if(ke){if(!et)return lt("NOT SHARED: Session is not currently shared"),void setTimeout(()=>lt(""),5e3);try{m("Removing share link...");const e=new ao({baseUrl:getApiBaseUrl()});await e.delete({endpoint:ct.ALPHA.SHARE.DELETE,body:{sessionId:ke,secret:et.secret}});const t=Lt.current?.getSessionManager();t&&await t.deleteShareInfo(),lt("UNSHARED: Sharing has stopped"),m(""),tt(null),setTimeout(()=>{lt("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;m(t),setTimeout(()=>m(""),5e3)}}else m("No active session to unshare")},"handleUnshareCommand"),yn=__name(async()=>{He(!0),Me(!0);const e=Ko();ze(e.id),he(t=>[...t,e])},"handleLearnCommand"),En=__name(async e=>{const t=crypto.randomUUID();_t.current=t;try{he([]),ye([]),Lt.current=null,ht(!1),Ce(e),Te(!1),Ie(!0),Lt.current=new da({onFeedUpdate:__name(e=>{if(_t.current!==t)return;const n=!0===e.metadata?.isAgent,r=e.metadata?.status;n&&"running"===r?ye(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):n&&r&&"running"!==r?(ye(t=>t.filter(t=>t.id!==e.id)),he(t=>[...t,e])):he(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Ot.current];return Ot.current=[],Se([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Je(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Qe(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{h(e)},"onRetryUpdate"),onProviderChange:__name(e=>{G(e)},"onProviderChange"),onStatusUpdate:__name(e=>{g.current=!0,m(e)},"onStatusUpdate"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Bt({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const t=ot.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const{feedEntries:n,corruptedLines:r,totalLines:o}=await Lt.current.loadSession(e);if(_t.current!==t)return;await cn();const s=[];if(0===n.length&&o>0?s.push(Vo(`Session could not be loaded. ${o} lines could not be parsed.`)):0===n.length?s.push(zo("Session loaded but contains no messages.")):(r>0&&s.push(zo(`Warning: ${r} message(s) could not be loaded.`)),s.push(...n)),_t.current!==t)return;he(s),Ea(),ie(e=>e+1)}catch(e){if(_t.current!==t)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";he([Vo(`Failed to load session: ${n}. Starting fresh session.`)]),Te(!1),Ie(!1),Ce(crypto.randomUUID())}},"handleSelectSession"),wn=__name(async()=>{he([]),ye([]),Lt.current=null,ht(!1),Ce(crypto.randomUUID()),Te(!1),Ie(!1)},"handleNewSession"),bn=__name(async()=>{try{await Vs.initializeProject(),$e(!1),e?(console.log("No conversations found to resume."),Ve(!0)):(Ne(!0),$t(),Ft())}catch(e){console.error("Failed to initialize project:",e),$e(!1),Ve(!0)}},"handleTrust"),Sn=__name(()=>{Ve(!0)},"handleNoTrust"),kn=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void B({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),G(e),x(!1);const n=getProviderDisplayName(e);m(`Provider set to ${n}`),oe.current&&clearTimeout(oe.current),te(!0),oe.current=setTimeout(()=>{te(!1),oe.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),m("Failed to set provider"),x(!1)}},"handleProviderSelect"),Cn=__name(()=>{x(!1)},"handleProviderCancel"),vn=__name(e=>{const t=Object.values(pt).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),Tn=__name(async e=>{try{await setSelectedModel({model:e}),Y(e),D(!1);const t=vn(e);m(`Model set to ${t}`),se.current&&clearTimeout(se.current),re(!0),se.current=setTimeout(()=>{re(!1),se.current=null},5e3)}catch(e){console.error("Failed to set model:",e),m("Failed to set model"),D(!1)}},"handleModelSelect"),An=__name(()=>{D(!1)},"handleModelCancel"),Pn=__name(()=>{if(O){B(null),x(!1),G(O.provider);const e=getProviderDisplayName(O.provider);m(`${e} authentication successful`),oe.current&&clearTimeout(oe.current),te(!0),oe.current=setTimeout(()=>{te(!1),oe.current=null},5e3)}},"handleAuthSuccess"),xn=__name(()=>{B(null)},"handleAuthCancel");if(qe)return null;if(Re)return L.createElement(L.Fragment,null,L.createElement(Zi,{staticKey:ae}),L.createElement(Uc,{onTrust:bn,onExit:Sn}));if(Oe)return null;if(ve)return L.createElement(tc,{onSelectSession:En,onNewSession:wn});if(!Fe)return null;if(jt)return L.createElement(z,{flexDirection:"column",width:"100%"},L.createElement(Ki,{staticKey:ae,feed:pe,showHeader:!0,expandedToolOutput:ce,currentModel:J}),L.createElement(z,{marginY:1},L.createElement(cl,{questions:jt.params.questions,onResponse:e=>{jt.resolve(e),Bt(null),m("Answers submitted")}})));if(Mt){if("shell_command"===Mt.toolName){const e=Mt.params;return L.createElement(z,{flexDirection:"column",width:"100%"},L.createElement(Ki,{staticKey:ae,feed:pe,showHeader:!0,expandedToolOutput:ce,currentModel:J}),fe.map(e=>L.createElement(LiveAgentStatus,{key:e.id,entry:e})),L.createElement(z,{marginY:1},L.createElement(rc,{request:e,onResponse:e=>{Ht(e);const t="no"!==e.value;Mt.resolve(t),Ut(null),t?(m("Shell command allowed"),mt||Vt("Use shift+tab to enable auto-accept")):m("Shell command denied")},onToggleAutoAccept:Yt})))}if("kill_shell"===Mt.toolName){const e=createKillShellPermissionRequest(Mt.params);return L.createElement(z,{flexDirection:"column",width:"100%"},L.createElement(Ki,{staticKey:ae,feed:pe,showHeader:!0,expandedToolOutput:ce,currentModel:J}),L.createElement(z,{marginY:1},L.createElement(rc,{request:e,onResponse:e=>{Ht(e);const t="no"!==e.value;Mt.resolve(t),Ut(null),t?(m("Process termination allowed"),mt||Vt("Use shift+tab to enable auto-accept")):m("Process termination denied")},onToggleAutoAccept:Yt})))}{const e={action:Mt.toolName.includes("edit")?"edit":Mt.toolName.includes("write")?"create":Mt.toolName.includes("delete")?"delete":"edit",filePath:Mt.params.filePath||Mt.params.file_path||Mt.params.path||Mt.params.absolutePath||Mt.params.notebook_path||"unknown",description:`Allow ${Mt.toolName} operation`,oldContent:"edit_file"===Mt.toolName?Mt.params.oldContent:void 0,newContent:"edit_file"===Mt.toolName?Mt.params.newContent:void 0};return L.createElement(z,{flexDirection:"column",width:"100%"},L.createElement(Ki,{staticKey:ae,feed:pe,showHeader:!0,expandedToolOutput:ce,currentModel:J}),fe.map(e=>L.createElement(LiveAgentStatus,{key:e.id,entry:e})),L.createElement(z,{marginY:1},L.createElement(Yi,{request:e,onResponse:e=>{Ht(e);const t="no"!==e.value;Mt.resolve(t),Ut(null),t?(m("File operation allowed"),mt||Vt("Use shift+tab to enable auto-accept")):m("File operation denied")},onToggleAutoAccept:Yt})))}}return F?L.createElement(xi,{onClose:()=>{N(!1),ie(e=>e+1)}}):C?L.createElement(L.Fragment,null,L.createElement(Zi,{staticKey:ae}),L.createElement(z,{flexDirection:"column",width:"100%"},L.createElement(z,{marginBottom:1},L.createElement(W,{dimColor:!0},"Press Esc to return to conversation")),L.createElement(sc,{onClose:()=>v(!1),onSettingsChange:$t,staticKey:ae}))):T?L.createElement(L.Fragment,null,L.createElement(Zi,{staticKey:ae}),L.createElement(z,{flexDirection:"column",width:"100%"},L.createElement(z,{marginBottom:1},L.createElement(W,{dimColor:!0},"Press Esc to return to conversation")),L.createElement(oc,{onClose:()=>A(!1),staticKey:ae}))):L.createElement(z,{flexDirection:"column",width:"100%"},L.createElement(Ki,{staticKey:ae,feed:pe.filter(e=>"taste-onboarding"!==e.role),showHeader:!0,expandedToolOutput:ce,currentModel:J}),Be&&L.createElement(Mc,{onComplete:Rt,autoLearn:We}),fe.map(e=>L.createElement(LiveAgentStatus,{key:e.id,entry:e})),L.createElement(RetryMessage,{attempt:p}),!P&&!I&&!O&&!R&&!S&&!St&&!vt&&!Ae&&!Be&&L.createElement(Pi,{queuedMessages:be,isProcessing:Ee,executionState:ue,status:u,input:l,setInput:d,onSubmit:Qt,showFileList:w,setShowFileList:b,fileSearchQuery:me,setFileSearchQuery:ge,onCommand:an,outputTokens:Ke,contextUsage:Ye,tasteLearning:dt,shareInfo:et,showShareNotification:st,unshareNotificationMessage:it,updateStatus:f,updateFailedInfo:s,currentProvider:H,showProviderInfo:ee,autoAcceptMode:mt,onToggleAutoAccept:Yt,hintMessage:ft,historyManager:De.current,pendingExitKey:xt,onResetPendingExitKey:Dt,onDoubleEscapeEmpty:Kt,retryAttempt:p,onAltP:()=>D(!0)}),P&&L.createElement(z,{marginY:1},L.createElement(Qi,{onSelect:kn,onCancel:Cn,currentProvider:H})),I&&L.createElement(z,{marginY:1},L.createElement(Ji,{onSelect:Tn,onCancel:An,currentModel:J})),S&&L.createElement(z,{marginY:1},L.createElement(ii,{onCancel:()=>k(!1)})),R&&L.createElement(z,{marginY:1},L.createElement(Ii,{onClose:()=>$(!1)})),St&&Lt.current&&L.createElement(z,{marginY:1},L.createElement(ec,{checkpoints:Lt.current.listCheckpoints(),onSelect:rn,onCancel:on})),O&&L.createElement(z,{marginY:1},L.createElement(O.Component,{onSuccess:Pn,onCancel:xn})),vt&&L.createElement(z,{marginY:1},L.createElement(jc,{onComplete:mn,onCancel:gn})),Ae&&L.createElement(z,{marginY:1},L.createElement(nc,{onClose:()=>{Pe(!1)}})))},"InteractiveCLI");pn(),rn();var ml=__name(e=>e?{isValid:!0}:{isValid:!1,errorMessage:["Error: Interactive mode requires a TTY terminal.","Please run this command directly in your terminal, not through a pipe or redirect."].join("\n")},"validateTtyEnvironment"),gl=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),pl=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),hl=__name(({options:e})=>({resume:e.resume,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding}),"buildInteractiveCLIProps"),fl=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),yl=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),El=__name(()=>{yl()},"initializeTerminal"),wl=__name(async(e={})=>{const t=ml(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),El(),gl(e)){const e=await Vs.isProjectInitialized(),t=e?await Vs.listSessions():[],n=pl({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=hl({options:e}),r=fl();G(L.createElement(ul,{...n}),r)},"interactiveMode");bt(),vt(),Ut(),wn(),kn(),Lt();var bl=null,Sl=!1,kl=new Set([go,po,Eo]);async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n.trim())}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}async function isAuthenticated(){return null!==await getAuthKey()}function setupSignalHandlers(){if(Sl)return;Sl=!0;const e=__name(e=>{bl?.abort(),process.stderr.write(`\n${e}\n`),process.exit(130)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated.")),process.stdout.on("error",e=>{"EPIPE"===e.code&&process.exit(0),process.stderr.write(`Error writing to stdout: ${e.message}\n`),process.exit(1)})}async function printMode(e={}){setupSignalHandlers(),bl=new AbortController;let t=e.query||"";if(!t){process.stdin.isTTY&&(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1));try{t=await readStdin()}catch(e){const t=e instanceof Error?e.message:"Unknown error";process.stderr.write(`Error reading from stdin: ${t}\n`),process.exit(1)}}t.trim()||(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1)),await isAuthenticated()||(process.stderr.write('Error: Not authenticated. Please run "cmd login" first.\n'),process.exit(3)),e.dangerouslySkipPermissions&&process.stderr.write("Warning: Running with --dangerously-skip-permissions. File writes and shell commands will execute without prompts.\n");try{const n=await processQuery({query:t,signal:bl.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions});process.stdout.write(n),n.endsWith("\n")||process.stdout.write("\n"),process.exit(0)}catch(e){e instanceof Error&&"AbortError"===e.name&&(process.stderr.write("\nCancelled.\n"),process.exit(130)),e instanceof Xr&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof eo&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof oo&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Qr&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof so&&(process.stderr.write("Error: The API server encountered an error. Please try again later.\n"),process.exit(7));const t=e instanceof Error?e.message:"Unknown error";/permission denied|access denied|not permitted|unauthorized/i.test(t)&&(process.stderr.write(`Error: ${t}\n`),process.exit(4)),process.stderr.write(`Error: ${t}\n`),process.exit(1)}}__name(readStdin,"readStdin"),__name(isAuthenticated,"isAuthenticated"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode");var Cl=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===ut.ANTHROPIC&&(r=await Nt.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o=getEnvironmentContext(),s=await getMemoryContent([]),a=await getTasteContent(),i=generateSkillsXML(await loadAllSkillSummaries())||null,c=crypto.randomUUID(),l=await isTasteLearningEnabled(),d={[it.PROJECT_SLUG]:Vs.getCurrentProjectDirName(),[it.TASTE_LEARNING]:l.toString(),[it.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(d[it.OAUTH_TOKEN]=`Bearer ${r}`),{tools:e,config:o,memory:s,taste:a,skills:i,headers:d,sessionId:c}}async function callApi(e,t,n,r){const o={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:`anthropic:${getConfiguredModel()}`},s={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:o,threadId:t.sessionId},a=await e.post({body:s,stream:!0,endpoint:ct.ALPHA.GENERATE,headers:t.headers,signal:r});return Ne.fromReadableStream(a).finalMessage()}async function executeToolCall(e,t,n){if(kl.has(e.name)&&!n)return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool "${e.name}" requires permissions. Use --dangerously-skip-permissions to enable file writes and shell commands in print mode.`,is_error:!0};try{const n=await executeTool(e.name,e.input,{abortSignal:t});return{type:"tool_result",tool_use_id:e.id,content:n}}catch(t){if(t instanceof Xr||t instanceof eo||t instanceof oo||t instanceof Qr||t instanceof so)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1}=e,o=getApiBaseUrl(),s=new ao({baseUrl:o}),a=[{role:"user",content:t}],i=await setupConversationContext();let c=0,l="";for(;c<Cl;){if(c++,n.aborted)throw new Error("Cancelled");const e=await callApi(s,i,a,n),t=e.content.filter(e=>"text"===e.type),o=e.content.filter(e=>"tool_use"===e.type),d=t.map(e=>e.text).join("");if(d&&(l+=d),0===o.length)break;const u=[];for(const e of o){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);u.push(t)}a.push({role:"assistant",content:e.content}),a.push({role:"user",content:u})}return c>=Cl&&process.stderr.write(`Warning: Reached maximum conversation turns (${Cl}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),l}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery"),It();var vl=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),Tl=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),Al=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),t},"buildRuntimeOptions"),Pl=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),xl=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)addDirectory(e);if(void 0!==t.print){const n=xl(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=vl(e);await Tl();const r=Al(t),o=Pl({options:t,runtimeOptions:r,initialPrompt:n});wl(o)}__name(interactiveModeAction,"interactiveModeAction"),bt(),fn(),dr(),globalThis.COMMAND_CODE_CWD=process.cwd();var Il=__name(()=>process.cwd(),"getCwd"),Dl=__name(()=>process.argv.slice(2),"getArgs"),Rl=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),$l=__name(()=>{const e=Il(),t=Dl(),n=Rl(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`)},"logStartupInfo");async function preRun(){$l(),process.argv.includes("--ide-setup")&&(formatSetupResult(await runIDESetup()).forEach(e=>console.log(e)),process.exit(0)),await maybeRunPendingUpdate(),checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100)}__name(preRun,"preRun"),bt(),vt(),fn(),Rn(),Sn();var Fl=getPackageJson(),Nl=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=Fl.version,t=getInvokedCommandName(),n=Ui.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(J.bold("Command Code")+J.gray(` v${e}`)),console.log(J.gray(Oi)),console.log(),console.log(J.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(J.bold("Options"));for(const e of Mi){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Li)+J.gray(e.description))}console.log(),console.log(J.bold("Commands"));for(const e of ji){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Li)+J.gray(e.description))}console.log(),console.log(J.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Li)+J.gray(e.description));console.log(),console.log(J.bold("Keyboard Shortcuts"));for(const e of _i)console.log(" "+e.key.padEnd(Li)+J.gray(e.description));console.log(),console.log(J.bold("Examples"));for(const e of zi){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Li)+J.gray(e.description))}console.log(),console.log(J.cyan("❯")+" "+J.gray(Wi.replace(/cmd/,t))),console.log(),console.log(J.bold("Links"));for(const e of Bi)console.log(" "+e.key.padEnd(Li)+J.cyan(e.description));console.log()}function createProgram(){const e=new ye;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(Fl.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume","Resume a session (pick from history)").option("-c, --continue"," Continue the most recent session in the current directory").option("-t, --trust","Trust the project (skip initial trust permission prompt)").option("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").option("--ide-setup","Setup extension to fetch IDE context").option("--add-dir <directory>","Add directory to workspace context",Nl,[]).addOption(new Ee(st).hideHelp()).addOption(new Ee(at).hideHelp()).addOption(new Ee("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ee("--local","Use local server").hideHelp()).addOption(new Ee("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(`[cmd] ${r&&r!==n?"subcommand":"running"}: ${n}`);const o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const a=t.args;a.length>0&&dlog(`[cmd] arguments: ${a.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),bt(),ir();var Ol=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=m.platform(),n=m.arch();let r,o,s,a;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,o=e.user?.id,s=e.org?.login,a=e.org?.id)}catch{}if(!o)try{const e=await loadCredentials();o=e?.userId}catch{}systemInfo({userName:r,userId:o,orgLogin:s,orgId:a,nodeVersion:e,platform:t,arch:n})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){Ol||(Ol=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=xe("Opening GitHub issues...").start();try{await X(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually")),console.log("")}}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal"),bt(),__name(openGitHubIssue,"openGitHubIssue");var Ll=new ye("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);bt();var _l=new ye("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});bt();var Ml=new ye("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{const{waitUntilExit:t}=G(L.createElement(Qc,{verbose:e.verbose,text:e.text}));await t()});bt(),vt(),fn(),ir();var Ul=new ye(gt.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{const{unmount:e}=G(L.createElement(Lc,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:Bn.LEARN_TASTE_COMMAND,heading:"Learn taste render failed"}}),dlog(`[/learn-taste] render failed: ${e instanceof Error?e.message:String(e)}`),await shutdownTelemetry(),process.exit(1)}});function getTastePath(t){const{target:n}=t;switch(n){case"local-project":return e.join(process.cwd(),".commandcode","taste");case"local-global":return e.join(m.homedir(),".commandcode","taste");case"remote-project":case"remote-user":throw new Error(`Remote storage not yet implemented: ${n}`);default:throw new Error(`Unknown storage target: ${n}`)}}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"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 s=[];for(const e of t){const t=parseLearning({line:e});t&&s.push(t)}s.length>0&&r.push({category:normalizeCategory({category:o}),learnings:s,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}bt(),vt(),bt(),bt(),bt(),bt(),bt(),vt(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),bt(),__name(parseTasteBuckets,"parseTasteBuckets"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),bt(),__name(formatBucket,"formatBucket");var jl=class{static{__name(this,"LocalProjectStorage")}target="local-project";async getAllBuckets(){const e=getTastePath({target:this.target});if(!y(e))return[];const t=[],n=getRootTasteFile({target:this.target});if(y(n)){let e=await P.readFile(n,"utf-8");const r=migrateHeader({content:e});r!==e&&(await P.writeFile(n,r,"utf-8"),e=r);const o=parseTasteBuckets({content:e,sourcePath:n});t.push(...o)}const r=await P.readdir(e,{withFileTypes:!0});for(const e of r)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(y(n)){let r=await P.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await P.writeFile(n,o,"utf-8"),r=o);const s=parseTasteBuckets({content:r,sourcePath:n});for(const t of s)t.category=e.name;t.push(...s)}}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 P.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:this.target}),o=t.learnings.length,s=await this.removeBucket({category:t.category});o<=5?await this.writeToRoot({bucket:t,rootFile:r,categoryPosition:s}):await this.writeToSubdirectory({bucket:t,rootFile:r,categoryPosition:s})}async removeBucket(t){const{category:n}=t,r=getRootTasteFile({target:this.target});let o=null;if(y(r)){let e=await P.readFile(r,"utf-8");e=migrateHeader({content:e});const t=e.split("\n");let s=-1,a=-1;const i=new RegExp(`^# ${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i");for(let e=0;e<t.length;e++)if(i.test(t[e])){s=e;for(let n=e+1;n<t.length;n++)if(t[n].startsWith("# ")){let r=n-1;for(;r>e&&""===t[r].trim();)r--;a=r;break}-1===a&&(a=t.length-1);break}if(-1!==s){const e=t.slice(0,s),n=a<t.length-1?t.slice(a+1):[];o={before:e.join("\n").trim(),after:n.join("\n").trim()};const i=[...e,...n].join("\n").trim();""===i?await P.rm(r,{force:!0}):await P.writeFile(r,i+"\n","utf-8")}}const s=getCategoryTasteFile({target:this.target,category:n}),a=e.dirname(s);return y(a)&&await P.rm(a,{recursive:!0,force:!0}),o}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(Ba)&&(e=Ba+"\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 P.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";y(n)&&(e=await P.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(Ba)||(e=Ba+"\n\n"+e):e=Ba+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o,await P.writeFile(n,e.trim()+"\n","utf-8")}}async writeToSubdirectory(t){const{bucket:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:this.target,category:n.category}),a=e.dirname(s);await P.mkdir(a,{recursive:!0});const i=formatBucket({bucket:n});await P.writeFile(s,i,"utf-8");const c=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=o.before;e=migrateHeader({content:e}),e&&!e.trim().startsWith(Ba)&&(e=Ba+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=c.trim(),o.after&&(e+="\n\n"+o.after),await P.writeFile(r,e.trim()+"\n","utf-8")}else{let e="";y(r)&&(e=await P.readFile(r,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(Ba)||(e=Ba+"\n\n"+e):e=Ba+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=c,await P.writeFile(r,e.trim()+"\n","utf-8")}}exists(){const e=getTastePath({target:this.target});return y(e)}};bt();var Bl=class{static{__name(this,"LocalGlobalStorage")}target="local-global";async getAllBuckets(){const e=getTastePath({target:this.target});if(!y(e))return[];const t=[],n=await P.readdir(e,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(y(n)){let r=await P.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await P.writeFile(n,o,"utf-8"),r=o);const s=parseTasteBuckets({content:r,sourcePath:n});for(const t of s)t.category=e.name;t.push(...s)}}return t}async getBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t});if(!y(n))return null;let r=await P.readFile(n,"utf-8");const o=migrateHeader({content:r});return o!==r&&(await P.writeFile(n,o,"utf-8"),r=o),parseTasteBuckets({content:r,sourcePath:n})[0]||null}async writeBucket(t){const{bucket:n}=t,r=getTastePath({target:this.target});await P.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:this.target,category:n.category}),s=e.dirname(o);await P.mkdir(s,{recursive:!0});const a=formatBucket({bucket:n});await P.writeFile(o,a,"utf-8")}async deleteBucket(t){const{category:n}=t,r=getCategoryTasteFile({target:this.target,category:n}),o=e.dirname(r);y(o)&&await P.rm(o,{recursive:!0,force:!0})}async listBuckets(){const e=await this.getAllBuckets(),t=[];for(const n of e){let e;try{e=(await P.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 y(e)}};async function prepareUploadFormData(t){const{packageName:n,bucket:r,description:o,type:s="category",isPublic:a=!1}=t,i=new FormData;if(i.append("name",n),o&&i.append("description",o),i.append("type",s),i.append("isPublic",String(a)),"category"===s){const e=formatBucket({bucket:r}),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",n)}else{const t=formatBucket({bucket:r}),n=new Blob([t],{type:"text/markdown"}),o=new File([n],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",o);const s=getTastePath({target:"local-project"}),a=e.join(s,r.category);if(y(a)){const e=getCategoryTasteFile({target:"local-project",category:r.category});if(y(e)){const t=await P.readFile(e,"utf-8"),n=new Blob([t],{type:"text/markdown"}),o=new File([n],"taste.md",{type:"text/markdown"});i.append(`files[${r.category}/taste.md]`,o)}}}return i}async function prepareMultiplePackagesUpload(e){const{buckets:t,projectName:n,description:r,isPublic:o=!1}=e,s=new FormData;s.append("name",n),r&&s.append("description",r),s.append("type","project"),s.append("isPublic",String(o));const a=getRootTasteFile({target:"local-project"});if(y(a)){const e=await P.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",n)}for(const e of t){const t=getCategoryTasteFile({target:"local-project",category:e.category});if(y(t)){const n=await P.readFile(t,"utf-8"),r=new Blob([n],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});s.append(`files[${e.category}/taste.md]`,o)}}return s}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}bt(),bt(),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),vt(),bt(),__name(parseTasteContent,"parseTasteContent"),ir();var zl=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()}${ct.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{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"list_packages_error"}),context:{component:Bn.TASTE_REMOTE_STORAGE,heading:"Failed to list taste packages","http.status":n.status}}),t}const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const s=[];for(const e of o)try{const t=await this.getBucket({category:e.name});t&&s.push(t)}catch(t){trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"download_package_error"}),context:{component:Bn.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${t instanceof Error?t.message:String(t)}`)}return s}async downloadPackage(e){const{namespace:t,packageName:n}=e,r=getApiBaseUrl(),o=`${r}${ct.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",t).replace(":packageName",n)}`;try{const e=await fetch(o,{method:"GET"});if(e.ok){const{data:t}=await e.json();return{type:t.type||"category",files:t.files||[],isPublic:!0}}if(404!==e.status){let t="Failed to download taste package";try{const n=await e.json();t=n.error?.message||n.message||`${t} (${e.status})`}catch{t=`${t} (${e.status})`}const n=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_public_error"}),context:{component:Bn.TASTE_REMOTE_STORAGE,heading:"Failed to download taste package (public)","http.status":e.status}}),n}if(!await getAuthKey())throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`")}catch(e){if(e instanceof Error)throw e}const s=await getAuthKey();if(!s)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");const a=`${r}${ct.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",t).replace(":packageName",n)}`,i=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${s}`}});if(!i.ok){if(404===i.status)return null;let e="Failed to download taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"download_auth_error"}),context:{component:Bn.TASTE_REMOTE_STORAGE,heading:"Failed to download taste package (authenticated)","http.status":i.status}}),t}const{data:c}=await i.json();return{type:c.type||"category",files:c.files||[],isPublic:c.isPublic??!1}}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 s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async writeBucket(e){const{bucket:t,namespace:n,isPublic:r=!1}=e,o=await getAuthKey();if(!o)throw new Error("No API key found. Please authenticate with: cmd login");const s=await prepareUploadFormData({packageName:t.category,bucket:t,type:"category",isPublic:r}),a=`${getApiBaseUrl()}${ct.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,i=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:s});if(!i.ok){let e="Failed to upload taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"upload_package_error"}),context:{component:Bn.TASTE_REMOTE_STORAGE,heading:"Failed to upload taste package","http.status":i.status}}),t}await i.json()}async writeBuckets(e){const{buckets:t,projectName:n,namespace:r,isPublic:o=!1}=e,s=await getAuthKey();if(!s)throw new Error("No API key found. Please authenticate with: cmd login");const a=await prepareMultiplePackagesUpload({buckets:t,projectName:n,isPublic:o}),i=`${getApiBaseUrl()}${ct.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,c=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:a});if(!c.ok){let e="Failed to upload taste packages";try{const t=await c.json();e=t.error?.message||t.message||e}catch{}const n=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:n,label:"upload_packages_error"}),context:{component:Bn.TASTE_REMOTE_STORAGE,heading:"Failed to upload taste packages","http.status":c.status,"package.count":t.length}}),n}await c.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()}${ct.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{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"list_buckets_error"}),context:{component:Bn.TASTE_REMOTE_STORAGE,heading:"Failed to list buckets","http.status":n.status}}),t}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:"",isPublic:e.isPublic??!1,starCount:e.starCount??0,downloadCount:e.downloadCount??0,type:e.type??"category"}))}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 s=new Map(o);for(const e of t){const t=o.get(e.text);t?e.confidence>t.confidence?(s.set(e.text,e),r.updated++):(e.confidence,t.confidence,r.unchanged++):(s.set(e.text,e),r.added++)}for(const e of n)t.some(t=>t.text===e.text)||r.unchanged++;return{merged:Array.from(s.values()),details:r}}bt(),__name(mergeLearnings,"mergeLearnings"),bt();var Wl=/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"),s=[];let a=0;for(;a<o.length;){const e=o[a],t=a+1,n=e.trim();if(n.startsWith("-"))if(Wl.test(n))s.push({text:e,originalLineNum:t}),a++;else{let n=e,r=a+1;for(;r<o.length;){const e=o[r].trim();if(e.startsWith("#")||e.startsWith("-"))break;if(e.length>0&&(n=n+" "+e),Wl.test(e)){r++;break}r++}s.push({text:n,originalLineNum:t}),a=r}else s.push({text:e,originalLineNum:t}),a++}let i=null,c=null,l=0;for(const{text:e,originalLineNum:t}of s){if(!e.trim())continue;if(e.trim().startsWith("# ")){if("# Taste (Continuously Learned by CommandCode.ai)"===e.trim()||"# Taste (Continuously Learned by CommandCode)"===e.trim())continue;i&&0===l&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:c-1})||r.push({line:c,severity:"warning",message:`Category '${i}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),i=e.trim().substring(2).trim(),c=t,l=0;continue}if(e.trim().startsWith("-")){if(!i){r.push({line:t,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'});continue}l++;const n=validateLearningLine({line:e.trim(),lineNum:t});r.push(...n);continue}const n=e.trim();/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i.test(n)||r.push({line:t,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 i&&0===l&&c&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:c-1})||r.push({line:c,severity:"warning",message:`Category '${i}' 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(!Wl.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 s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),a=s.length>0?s[s.length-1]:null;if(!a)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=a[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=a&&void 0!==a.index?o.substring(0,a.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),s=0===r.length;let a;if(0===t.length)a=`✓ ${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":""}`),a=`${r.length>0?"✗":"⚠"} ${n} has ${e.join(", ")}`}return{valid:s,issues:t,summary:a}}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`${J.green(e)} ${J.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity),s=[r.length>0?J.red(t.summary):J.yellow(t.summary),""];if(r.length>0){s.push(J.bold(J.red("Errors:")));for(const e of r){const t=e.line?J.dim(` Line ${e.line}: `):" ";s.push(`${t}${J.red(e.message)}`),e.suggestion&&s.push(J.dim(` → ${e.suggestion}`))}s.push("")}if(o.length>0){s.push(J.bold(J.yellow("Warnings:")));for(const e of o){const t=e.line?J.dim(` Line ${e.line}: `):" ";s.push(`${t}${J.yellow(e.message)}`),e.suggestion&&s.push(J.dim(` → ${e.suggestion}`))}s.push("")}return s.join("\n").trim()}async function promptMergeStrategy(e){const{packageName:t,namespace:n,localBucket:r,remoteLearningsCount:o}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${r.learnings.length} learnings`),console.log(`Remote: ${o} learnings (from ${n})\n`);const s=await we.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} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});return we.isCancel(s)&&(we.cancel("Operation cancelled"),process.exit(0)),s}async function promptPushStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteBucket:o}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${o.learnings.length} learnings (in ${n})\n`);const s=await we.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 (${o.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"}],initialValue:"merge"});return we.isCancel(s)&&(we.cancel("Operation cancelled"),process.exit(0)),s}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalBucket:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists in global storage\n`)),console.log(`Local: ${n} learnings`),console.log(`Global: ${r.learnings.length} learnings\n`);const o=await we.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 we.isCancel(o)&&(we.cancel("Operation cancelled"),process.exit(0)),o}async function promptGlobalPullStrategy(e){const{packageName:t,localBucket:n,globalLearningsCount:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${n.learnings.length} learnings`),console.log(`Global: ${r} learnings\n`);const o=await we.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 we.isCancel(o)&&(we.cancel("Operation cancelled"),process.exit(0)),o}async function promptTypeMismatchStrategy(e){const{packageName:t,namespace:n,localType:r,remoteType:o,localLearningsCount:s,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, skipping push`)),"skip";const i=`https://commandcode.ai/${n}/${t}`;console.log(J.yellow(`\n${pe.warning} Pushing local project taste to individual package '${t}'\n`)),console.log(`Local: ${t} (${s} learnings)`),console.log(`Remote: ${t} (${a} learnings) in ${n}\n`),console.log(`Review package: ${J.cyan(i)}\n`);const c=await we.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});return we.isCancel(c)&&(we.cancel("Operation cancelled"),process.exit(0)),c}async function promptSameTypeStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteLearningsCount:o}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(J.yellow(`\n${pe.warning} Non-interactive terminal detected, skipping push`)),"skip";const s=`https://commandcode.ai/${n}/taste/${t}`;console.log(J.yellow(`\n${pe.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${o} learnings\n`),console.log(`Review taste package: ${J.cyan(s)}\n`);const a=await we.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${o} → ${r} learnings)`}],initialValue:"skip"});return we.isCancel(a)&&(we.cancel("Operation cancelled"),process.exit(0)),a}async function push(t){const n=void 0!==t.isPublic,{buckets:r,target:o,overwrite:s=!1,isPublic:a=!1}=t,i=new jl,c={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!i.exists())return c.success=!1,c.errors.push({bucket:"all",error:"No taste directory found in project"}),c;const l=await i.getAllBuckets();if(0===l.length)return c.success=!1,c.errors.push({bucket:"all",error:"No taste packages found in project"}),c;for(const e of l){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){c.success=!1;const n=formatValidationIssues({result:t,verbose:!0});c.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(c.errors.length>0)return c;const d=r.length>0?l.filter(e=>r.includes(e.category)):l;if(r.length>0&&0===d.length){c.success=!1;for(const e of r)c.errors.push({bucket:e,error:"Taste package not found in project"});return c}let u,m;if("remote-project"===o||"remote-user"===o)try{const e=await getAuthenticatedEntity();e.success&&e.user?.userName&&(u=e.user.userName)}catch{}if("remote-project"===o&&0===r.length){const t=e.basename(process.cwd()),r=new zl;if(!u)return c.success=!1,c.errors.push({bucket:"all",error:"Failed to get user namespace for remote push"}),c;try{const e=await r.downloadPackage({namespace:u,packageName:t});let o="overwrite";const i="project",l=e?.type??"category",m=d.reduce((e,t)=>e+t.learnings.length,0),g=e?.files?e.files.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0):0;if(o=s?"overwrite":e?l!==i?await promptTypeMismatchStrategy({packageName:t,namespace:u,localType:i,remoteType:l,localLearningsCount:m,remoteLearningsCount:g}):await promptSameTypeStrategy({packageName:t,namespace:u,type:i,localLearningsCount:m,remoteLearningsCount:g}):"overwrite","skip"===o)return c;await r.writeBuckets({buckets:d,projectName:t,namespace:u,type:"project",isPublic:n?a:e?.isPublic??!1});for(const e of d)c.bucketsPushed.push(e.category),c.filePaths[e.category]=`${u}/${t}`,c.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if(e)for(const e of d)c.overwritten.push(e.category);return c}catch(e){return c.success=!1,c.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),c}}switch(o){case"local-global":m=new Bl;break;case"remote-project":case"remote-user":m=new zl;break;default:return c.success=!1,c.errors.push({bucket:"all",error:`Invalid target: ${o}`}),c}for(const e of d)try{const t=await m.getBucket({category:e.category});let n;if(n=s?"overwrite":t&&"local-global"===o?await promptGlobalPushStrategy({packageName:e.category,localLearningsCount:e.learnings.length,globalBucket:t}):"merge","skip"===n)continue;if("overwrite"===n){if("local-global"===o)await m.writeBucket({bucket:e});else{if(!u)throw new Error("Failed to get user namespace for remote push");await m.writeBucket({bucket:e,namespace:u,isPublic:a})}c.bucketsPushed.push(e.category),c.overwritten.push(e.category)}else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},c.mergeDetails[e.category]=r.details}else n=e,c.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if("local-global"===o)await m.writeBucket({bucket:n});else{if(!u)throw new Error("Failed to get user namespace for remote push");await m.writeBucket({bucket:n,namespace:u,isPublic:a})}c.bucketsPushed.push(e.category)}if("local-global"===o){const t=getCategoryTasteFile({target:"local-global",category:e.category});c.filePaths[e.category]=t}else"remote-project"!==o&&"remote-user"!==o||!u||(c.filePaths[e.category]=`${u}/${e.category}`)}catch(t){c.success=!1,c.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return c}async function pull(e){const{buckets:t,source:n,overwrite:r=!1}=e,o=new jl,s={success:!0,bucketsPulled:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},a=__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 Bl;break;case"remote-project":case"remote-user":i=new zl;break;default:return s.success=!1,s.errors.push({bucket:"all",error:`Invalid source: ${n}`}),s}try{c=await i.getAllBuckets()}catch(e){return s.success=!1,s.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),s}if(0===c.length)return s.success=!1,s.errors.push({bucket:"all",error:`No taste packages found in ${a}`}),s;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){s.success=!1;const n=formatValidationIssues({result:t,verbose:!0});s.errors.push({bucket:e.category,error:`Validation failed for taste package in ${a}:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in ${a} has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(s.errors.length>0)return s;const l=t.length>0?c.filter(e=>t.includes(e.category)):c;if(t.length>0&&0===l.length){s.success=!1;for(const e of t)s.errors.push({bucket:e,error:`Taste package not found in ${a}`});return s}for(const e of l)try{const t=await o.getBucket({category:e.category});let a;if(a=r?"overwrite":t&&"local-global"===n?await promptGlobalPullStrategy({packageName:e.category,localBucket:t,globalLearningsCount:e.learnings.length}):"merge","skip"===a)continue;if("overwrite"===a)await o.writeBucket({bucket:e}),s.bucketsPulled.push(e.category),s.overwritten.push(e.category);else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},s.mergeDetails[e.category]=r.details}else n=e,s.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),s.bucketsPulled.push(e.category)}const i=getCategoryTasteFile({target:"local-project",category:e.category});s.filePaths[e.category]=i}catch(t){s.success=!1,s.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return s}async function pullRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new jl,s=new zl,a={success:!0,bucketsPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};try{const e=await s.downloadPackage({namespace:t,packageName:n});if(!e)return a.success=!1,a.errors.push({bucket:n,error:"Taste package not found in remote"}),a;const{type:i,files:c}=e;for(const e of c){const t=validateTasteFile({content:e.content,filePath:e.file});if(!t.valid){a.success=!1;const r=formatValidationIssues({result:t,verbose:!0});a.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(a.errors.length>0)return a;"project"===i?await pullProjectPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:a}):await pullCategoryPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:a})}catch(e){a.success=!1,a.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return a}async function pullProjectPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:s,result:a}=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:s,result:a})}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:s,result:a})}}async function processBucket(e){const{bucket:t,namespace:n,overwrite:r,targetStorage:o,result:s}=e;try{const e=await o.getBucket({category:t.category});let a;if(a=r?"overwrite":e?await promptMergeStrategy({packageName:t.category,namespace:n,localBucket:e,remoteLearningsCount:t.learnings.length}):"merge","skip"===a)return void s.skipped.push(t.category);if("overwrite"===a)await o.writeBucket({bucket:t}),s.bucketsPulled.push(t.category),s.overwritten.push(t.category);else{let n;if(e){const r=mergeLearnings({source:t.learnings,target:e.learnings});n={...t,learnings:r.merged},s.mergeDetails[t.category]=r.details}else n=t,s.mergeDetails[t.category]={added:t.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),s.bucketsPulled.push(t.category)}const i=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=i}catch(e){s.success=!1,s.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:s,result:a}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return a.success=!1,void a.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:s,result:a})}async function pushRemote(e){const t=void 0!==e.isPublic,{namespace:n,packageName:r,overwrite:o=!1,isPublic:s=!1}=e,a=new jl,i=new zl,c={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!a.exists())return c.success=!1,c.errors.push({bucket:r,error:"No taste directory found in project"}),c;try{const e=await a.getBucket({category:r});if(!e)return c.success=!1,c.errors.push({bucket:r,error:`Taste package '${r}' not found in local project`}),c;const l=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!l.valid){c.success=!1;const e=formatValidationIssues({result:l,verbose:!0});return c.errors.push({bucket:r,error:`Validation failed:\n${e}`}),c}if(l.issues.filter(e=>"warning"===e.severity).length>0){console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`);const e=formatValidationIssues({result:l,verbose:!0});console.warn(e+"\n")}const d=await i.downloadPackageToBucket({namespace:n,packageName:r});let u;u=o?"overwrite":d?await promptPushStrategy({packageName:r,namespace:n,localLearningsCount:e.learnings.length,remoteBucket:d}):"merge";const m=t?s:d?.isPublic??!1;if("skip"===u)return c;if("overwrite"===u)await i.writeBucket({bucket:e,namespace:n,isPublic:m}),c.bucketsPushed.push(r),c.overwritten.push(r);else{let t;if(d){const n=mergeLearnings({source:e.learnings,target:d.learnings});t={...e,learnings:n.merged},c.mergeDetails[r]=n.details}else t=e,c.mergeDetails[r]={added:e.learnings.length,updated:0,unchanged:0};await i.writeBucket({bucket:t,namespace:n,isPublic:m}),c.bucketsPushed.push(r)}c.filePaths[r]=`${n}/${r}`}catch(e){c.success=!1,c.errors.push({bucket:r,error:e instanceof Error?e.message:String(e)})}return c}async function list(e){const{location:t}=e;let n;switch(t){case"local-project":n=new jl;break;case"local-global":n=new Bl;break;case"remote-project":case"remote-user":n=new zl;break;default:throw new Error(`Invalid location: ${t}`)}return n instanceof Bl||n instanceof zl?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 Bl;break;case"remote-project":case"remote-user":o=new zl;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(!y(o))return r.success=!1,r.errors.push({file:"all",error:"No taste directory found in "+("local-global"===n?"global":"project")}),r;const s=[];if(t.length>0)for(const e of t){const t=getCategoryTasteFile({target:n,category:e});y(t)?s.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});y(e)&&s.push({path:e,displayName:"taste.md"});const t=await P.readdir(o,{withFileTypes:!0});for(const e of t)if(e.isDirectory()){const t=getCategoryTasteFile({target:n,category:e.name});y(t)&&s.push({path:t,displayName:`${e.name}/taste.md`})}}if(0===s.length&&r.errors.length>0)return r;if(0===s.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 s){let t=await P.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await P.writeFile(e.path,n,"utf-8"),t=n);const o=validateTasteFile({content:t,filePath:e.displayName}),s=o.issues.filter(e=>"error"===e.severity),a=o.issues.filter(e=>"warning"===e.severity);r.totalErrors+=s.length,r.totalWarnings+=a.length,o.valid||(r.success=!1);const i=formatValidationIssues({result:o});r.filesLinted.push({file:e.displayName,valid:o.valid,errors:s.length,warnings:a.length,formatted:i})}return r}async function open6(e){const{package:t,target:n}=e;try{let e;switch(n){case"local-project":e=new jl;break;case"local-global":e=new Bl;break;case"remote-project":case"remote-user":e=new zl;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,s=await findCategoryLineNumber({filePath:o,category:t});return await qe([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}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(t){const{filePath:n,category:r}=t;try{const t=await P.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const o=t.split("\n");for(let e=0;e<o.length;e++)if(o[e].trim().toLowerCase()===`# ${r.toLowerCase()}`)return e+1;return 1}catch{return 1}}function getEditorSetupInstructions(){const e=Ke.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 t=e.join(m.homedir(),".commandcode","taste",".metadata.json");if(y(t))try{await P.unlink(t)}catch{}}__name(validateTasteFile,"validateTasteFile"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(validateLearningLine,"validateLearningLine"),__name(buildResult,"buildResult"),__name(formatValidationIssues,"formatValidationIssues"),bt(),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptPushStrategy,"promptPushStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),__name(push,"push"),bt(),__name(pull,"pull"),bt(),__name(pullRemote,"pullRemote"),__name(pullProjectPackage,"pullProjectPackage"),__name(processBucket,"processBucket"),__name(pullCategoryPackage,"pullCategoryPackage"),bt(),__name(pushRemote,"pushRemote"),bt(),__name(list,"list"),bt(),__name(deleteBuckets,"deleteBuckets"),bt(),__name(lint,"lint"),bt(),__name(open6,"open"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),bt(),__name(runMigrations,"runMigrations"),__name(removeMetadataFile,"removeMetadataFile");var Hl=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 open6(e)}};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 we.select({message:"Select namespace to push to\n",options:r,initialValue:t});return we.isCancel(o)&&(we.cancel("Operation cancelled"),process.exit(0)),o}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new ao({baseUrl:e}),n=await t.get({endpoint:ct.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}}function createTasteCommand(){const e=new ye(gt.TASTE);e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments();const t=new Hl;return e.command("push").description("Push taste packages from project to remote or global storage (prompts on conflicts)").argument("[package]","Package name (optional if using --all)").option("--all","Push all packages").option("--remote","Push to remote (default)").option("-g, --global","Push to global storage").addOption(new Ee("--local","Use local server").hideHelp()).option("--public","Make this package publicly discoverable").option("--overwrite","Overwrite target without prompting (default: interactive merge)").addOption(new Ee("--staging","Push to staging environment").hideHelp()).action(async(e,n)=>{try{let r;if(n.global||n.remote||(n.remote=!0),n.global&&n.remote&&(console.error(J.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),e||n.all||(console.error(J.red("Error: Please specify a package name or use --all flag")),console.error(J.gray("Usage: cmd taste push <package> (pushes to remote by default)")),console.error(J.gray(" cmd taste push --all (pushes whole project)")),console.error(J.gray(" cmd taste push <package> -g (for global)")),process.exit(1)),e&&n.all&&(console.error(J.red("Error: Cannot use both package name and --all flag")),process.exit(1)),n.remote)if(n.all)r=await t.push({buckets:[],target:"remote-project",overwrite:n.overwrite,isPublic:n.public});else{let o,s;if(e&&e.includes("/")){const[t,n]=e.split("/");t&&n||(console.error(J.red("Error: Invalid namespace/package format")),console.error(J.gray("Usage: cmd taste push --remote username/packageName")),console.error(J.gray(" cmd taste push --remote org-name/packageName")),process.exit(1)),o=t,s=n}else{e||(console.error(J.red("Error: Please specify a package name")),console.error(J.gray("Usage: cmd taste push <namespace>/<package>")),console.error(J.gray(" or: cmd taste push <package> (interactive namespace selection)")),process.exit(1)),s=e;let n;(await t.list({location:"local-project"})).some(e=>e.category===s)||(console.error(J.red(`Error: Taste package '${s}' not found in local project`)),process.exit(1));try{n=await fetchUserNamespaces()}catch(e){throw e}o=n.orgs.length>0?await promptNamespaceSelection(n):n.userName}r=await t.pushRemote({namespace:o,packageName:s,overwrite:n.overwrite,isPublic:n.public})}else{const o="local-global",s=n.all?[]:[e];r=await t.push({buckets:s,target:o,overwrite:n.overwrite})}if(!r.success){for(const e of r.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(J.red(`Error: ${t}`))}process.exit(1)}let o=!1;if(n.all&&r.bucketsPushed.length>0){const e=r.filePaths?.[r.bucketsPushed[0]];if(e)if(n.overwrite)console.log(J.green(`✓ Replaced taste in ${e}`));else if(r.mergeDetails){let t=0,n=0,s=0;for(const e of Object.values(r.mergeDetails))t+=e.added??0,n+=e.updated??0,s+=e.unchanged??0;const a=[];t>0&&a.push(`${t} ${1===t?"learning":"learnings"} added`),n>0&&a.push(`${n} ${1===n?"learning":"learnings"} updated`),s>0&&a.push(`${s} ${1===s?"learning":"learnings"} unchanged`),a.length>0?console.log(J.green(`✓ Pushed taste to ${e} (${a.join(", ")})`)):console.log(J.green(`✓ Pushed taste to ${e}`)),(t>0||n>0)&&s>0&&(o=!0)}else console.log(J.green(`✓ Pushed taste to ${e}`));else console.log(J.green("✓ Pushed taste to remote"))}else if(1===r.bucketsPushed.length){const e=r.bucketsPushed[0],t=r.filePaths?.[e];if(n.overwrite)n.remote&&t?console.log(J.green(`✓ Replaced '${e}' taste package in ${t}`)):(console.log(J.green(`✓ Replaced '${e}' taste package in global`)),t&&console.log(J.gray(` Path: ${t}`)));else if(r.mergeDetails?.[e]){const s=r.mergeDetails[e],a=[];s.added>0&&a.push(`${s.added} ${1===s.added?"learning":"learnings"} added`),s.updated>0&&a.push(`${s.updated} ${1===s.updated?"learning":"learnings"} updated`),s.unchanged>0&&a.push(`${s.unchanged} ${1===s.unchanged?"learning":"learnings"} unchanged`),n.remote&&t?console.log(J.green(`✓ Pushed '${e}' taste package to ${t} (${a.join(", ")})`)):(console.log(J.green(`✓ Pushed '${e}' taste package to global (${a.join(", ")})`)),t&&console.log(J.gray(` Path: ${t}`))),(s.added>0||s.updated>0)&&s.unchanged>0&&(o=!0)}else n.remote&&t?console.log(J.green(`✓ Pushed '${e}' taste package to ${t}`)):(console.log(J.green(`✓ Pushed '${e}' taste package to global`)),t&&console.log(J.gray(` Path: ${t}`)))}else if(r.bucketsPushed.length>0){const e=n.remote?"remote":"global";if(console.log(J.green(`✓ Pushed ${r.bucketsPushed.length} taste packages (${r.bucketsPushed.join(", ")}) to ${e}`)),!n.overwrite&&r.mergeDetails)for(const e of Object.values(r.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){o=!0;break}}o&&console.log(J.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("pull").argument("[package]","Package name (optional if using --all)").option("-g, --global","Pull from global").addOption(new Ee("--local","Use local server").hideHelp()).option("--remote","Pull from remote").option("--all","Pull all packages").option("--overwrite","Overwrite local without prompting (default: interactive merge)").addOption(new Ee("--staging","Use staging environment").hideHelp()).description("Pull packages from storage to project (prompts on conflicts)").action(async(e,n)=>{try{let r,o;if(n.global||n.remote||(n.remote=!0),n.global&&n.remote&&(console.error(J.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),n.remote&&n.all&&(console.error(J.red("Error: The --all flag is not supported for remote pull")),console.error(J.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),n.remote&&!e&&(console.error(J.red("Error: Please provide both namespace and package name")),process.exit(1)),n.remote&&e&&!e.includes("/")&&(console.error(J.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),e||n.all||(console.error(J.red("Error: Please specify a package name or use --all flag")),console.error(J.gray("Usage: cmd taste pull <namespace>/<package> (remote by default)")),console.error(J.gray(" cmd taste pull <package> -g (from global)")),console.error(J.gray(" cmd taste pull --all -g (all from global)")),process.exit(1)),e&&n.all&&(console.error(J.red("Error: Cannot use both package name and --all flag")),process.exit(1)),n.remote){e.includes("/")||(console.error(J.red("Error: Package name must include namespace")),console.error(J.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1));const[s,a]=e.split("/");s&&a||(console.error(J.red("Error: Invalid namespace/package format")),console.error(J.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),o=s,r=await t.pullRemote({namespace:o,packageName:a,overwrite:n.overwrite})}else{const o="local-global",s=n.all?[]:[e];r=await t.pull({buckets:s,source:o,overwrite:n.overwrite})}const s=n.remote?o?`${o}`:"remote":"global";if(!r.success){for(const e of r.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(J.red(`Error: ${t}`))}process.exit(1)}if(r.skipped&&r.skipped.length>0)for(const e of r.skipped)console.log(J.yellow(`⊘ Skipped '${e}' - kept local version`));let a=!1;if(1===r.bucketsPulled.length){const e=r.bucketsPulled[0],t=r.filePaths?.[e];if(n.overwrite)console.log(J.green(`✓ Replaced '${e}' taste package in project`)),t&&console.log(J.gray(` Saved to: ${t}`));else if(r.mergeDetails?.[e]){const n=r.mergeDetails[e],o=[];n.added>0&&o.push(`${n.added} ${1===n.added?"learning":"learnings"} added`),n.updated>0&&o.push(`${n.updated} ${1===n.updated?"learning":"learnings"} updated`),n.unchanged>0&&o.push(`${n.unchanged} ${1===n.unchanged?"learning":"learnings"} unchanged`),console.log(J.green(`✓ Pulled '${e}' taste package from ${s} (${o.join(", ")})`)),t&&console.log(J.gray(` Saved to: ${t}`)),(n.added>0||n.updated>0)&&n.unchanged>0&&(a=!0)}else console.log(J.green(`✓ Pulled '${e}' taste package from ${s}`)),t&&console.log(J.gray(` Saved to: ${t}`))}else if(r.bucketsPulled.length>0){const e=` (${r.bucketsPulled.join(", ")})`;if(console.log(J.green(`✓ Pulled ${r.bucketsPulled.length} taste packages${e} from ${s}`)),!n.overwrite&&r.mergeDetails)for(const e of Object.values(r.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){a=!0;break}}a&&console.log(J.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("list").option("-g, --global","List global packages").addOption(new Ee("--local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ee("--staging","Use staging environment").hideHelp()).description("List available packages").action(async e=>{try{let n,r;e.global&&e.remote&&(console.error(J.red("Error: Cannot specify both --global and --remote flags")),process.exit(1)),e.remote?(n="remote-project",r="remote"):e.global?(n="local-global",r="global"):(n="local-project",r="project");const o=await t.list({location:n});if(0===o.length)return void console.log(J.yellow(`No taste packages found in ${r}`));let s;console.log(J.hex("#E4CCFF").bold("\nTaste Packages")),s="remote-project"===n?"Stored in your commandcode.ai account":"local-global"===n?"Stored globally in ~/.commandcode/taste":"Stored locally in .commandcode/taste",console.log(J.dim(s+"\n"));let a=0;const i=__name(e=>{let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ★${e.starCount}`.length),e.downloadCount&&(t+=` ↓${e.downloadCount}`.length),t},"getDisplayLength"),c=Math.max(...o.map(i));for(const e of o){a+=e.learningCount;const t=getTimeAgo(e.lastUpdated),n=" ".repeat(c-i(e)+2),r=J.white(e.category),o=e.isPublic?J.green(" [public]"):"",s=e.isPublic&&e.starCount?J.yellow(` ★${e.starCount}`):"",l=e.downloadCount?J.gray(` ↓${e.downloadCount}`):"";console.log(` ${r}${o}${s}${l}${n}${J.dim.gray(`(${e.learningCount} learnings, updated ${t})`)}`)}console.log(J.dim(`\nTotal: ${o.length} packages, ${a} learnings\n`))}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.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,n)=>{try{e||n.all||(console.error(J.red("Error: Please specify a package name or use --all flag")),console.error(J.gray("Usage: cmd taste lint <package>")),console.error(J.gray(" cmd taste lint --all")),process.exit(1)),e&&n.all&&(console.error(J.red("Error: Cannot use both package name and --all flag")),process.exit(1));const r=await t.lint({packages:e?[e]:[],target:n.global?"local-global":"local-project"});if(r.errors.length>0){for(const e of r.errors)console.error(J.red(`Error: ${e.error}`));process.exit(1)}for(const e of r.filesLinted)console.log(e.formatted);if(r.filesLinted.length>1)if(console.log(""),0===r.totalErrors&&0===r.totalWarnings)console.log(J.green(`✓ All ${r.filesLinted.length} taste files are valid`));else{const e=[];r.totalErrors>0&&e.push(J.red(`${r.totalErrors} error${r.totalErrors>1?"s":""}`)),r.totalWarnings>0&&e.push(J.yellow(`${r.totalWarnings} warning${r.totalWarnings>1?"s":""}`)),console.log(`Summary: ${e.join(", ")} across ${r.filesLinted.length} files`)}r.success||process.exit(1)}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("open").argument("<package>","Package name to open").option("-g, --global","Open from global").description("Open a package in your editor").action(async(e,n)=>{try{const r=n.global?"local-global":"local-project",o=await t.open({package:e,target:r});o.success||(console.error(J.red(o.error)),process.exit(1)),console.log(J.green(`✓ Opened '${e}' taste package from ${n.global?"global":"project"}`))}catch(e){console.error(J.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}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 formatVersion(e,t,n=!1){const r=n?Q.bold(Q.green(t)):Q.white(t);return`${Q.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${Q.bold(Q.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(Q.dim(`Run ${Q.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(Q.dim("Try updating manually:")),console.log(Q.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(Q.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=xe("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.stop(),console.log(""),console.log(`${Q.green(pe.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${Q.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=xe("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.text=`Updating ${t.currentVersion} ${pe.arrowRight} ${t.latestVersion}...`,(await performAutoUpdate({silent:!0,updateInfo:t})).success||(e.fail("Update failed"),trackError({error:sanitizeErrorForTelemetry({error:new Error("Update failed"),label:"cli_update_failed"}),context:{component:Bn.UPDATE_COMMAND,heading:"CLI update failed","update.current_version":t.currentVersion,"update.target_version":t.latestVersion}}),showManualUpdateHint(t.latestVersion),await shutdownTelemetry(),process.exit(1)),e.succeed(`Updated to v${t.latestVersion}`),showUpdateSuccessHint()):e.succeed(`Up to date ${Q.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}bt(),bt(),__name(promptNamespaceSelection,"promptNamespaceSelection"),bt(),vt(),__name(fetchUserNamespaces,"fetchUserNamespaces"),__name(createTasteCommand,"createTasteCommand"),__name(getTimeAgo,"getTimeAgo"),bt(),vt(),ir(),__name(formatVersion,"formatVersion"),__name(showVersionDetails,"showVersionDetails"),__name(showUpdateSuccessHint,"showUpdateSuccessHint"),__name(showManualUpdateHint,"showManualUpdateHint"),__name(showCheckFailure,"showCheckFailure"),__name(checkAction,"checkAction"),__name(performUpdateAction,"performUpdateAction"),__name(updateAction,"updateAction");var Gl=new ye("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);bt();var ql=__name((e,t)=>`${pe.info} ${e}: ${Q.cyan(t)}`,"formatInfoLine"),Vl=__name(e=>Q.bold(`${e}:`),"formatSectionHeader"),Kl=__name(e=>Q.red(e),"formatError"),Jl=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),Yl=__name(e=>["",Vl("User Information"),ql("Name",e.name),ql("Email",e.email),ql("Username",e.userName)],"buildUserOutput"),Ql=__name(e=>["",Vl("Organization"),ql("Name",e.name),ql("Login",e.login)],"buildOrgOutput"),Zl=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),Xl=__name((e,t)=>{Zl(Yl(e)),t&&Zl(Ql(t)),console.log("")},"displayUserInfo"),ed=__name(e=>null!==e&&e.length>0,"validateApiKey"),td=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=xe("Fetching user information...").start();try{const t=await getAuthKey();ed(t)||(e.fail(Kl('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();td(n)||(e.fail(Kl("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),Xl(n.user,n.org)}catch(t){e.fail(Kl(`Error: ${Jl(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var nd=new ye("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var rd=createProgram();rd.action(interactiveModeAction),rd.addCommand(_l),rd.addCommand(Ml),rd.addCommand(nd),rd.addCommand(Gl),rd.addCommand(Ll),rd.addCommand(createTasteCommand()),rd.addCommand(Ul),rd.addCommand(Cr),rd.addCommand(xr),rd.addCommand(Nr),setupCommanderHooks(rd),rd.parse();