command-code 0.17.2 → 0.17.3

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import*as e from"path";import t,{join as n,dirname as r,relative as s,resolve as o,extname as i,basename as a,isAbsolute as l}from"path";import{fileURLToPath as u,URL as d,pathToFileURL as m}from"url";import p,{z as g}from"zod";import*as h from"os";import f,{tmpdir as y}from"os";import*as w from"fs";import S,{readFileSync as b,existsSync as E,mkdirSync as C,writeFileSync as v,readdirSync as T,statSync as k,createReadStream as _,promises as P,constants as A}from"fs";import{exec as x,execSync as I,spawn as N,execFile as R}from"child_process";import*as $ from"fs/promises";import L,{writeFile as M,readFile as O,unlink as D,mkdir as q}from"fs/promises";import*as F from"crypto";import j,{randomUUID as z}from"crypto";import B,{memo as U,useState as W,useRef as Q,useEffect as G,useMemo as H,useCallback as V}from"react";import{Box as K,Text as Y,Static as J,useStdout as X,useInput as Z,render as ee,useApp as te,Newline as ne}from"ink";import re from"picocolors";import se from"strip-ansi";import oe from"sharp";import ie from"open";import ae from"@opentelemetry/sdk-node";import le from"@opentelemetry/exporter-trace-otlp-http";import ce from"@opentelemetry/resources";import ue from"@opentelemetry/semantic-conventions";import de from"@opentelemetry/sdk-trace-node";import{trace as me,SpanStatusCode as pe,context as ge}from"@opentelemetry/api";import{v4 as he}from"uuid";import*as fe from"http";import*as ye from"net";import we from"net";import Se from"ink-spinner";import be from"figures";import*as Ee from"@clack/prompts";import{cancel as Ce,select as ve,isCancel as Te,note as ke,confirm as _e,password as Pe}from"@clack/prompts";import{Command as Ae,Option as xe}from"commander";import Ie from"ora";import Ne from"@sindresorhus/slugify";import{EventEmitter as Re}from"events";import $e from"gray-matter";import{minimatch as Le}from"minimatch";import{glob as Me}from"glob";import{quote as Oe}from"shell-quote";import De from"tls";import qe from"stream";import{performance as Fe}from"perf_hooks";import{MessageStream as je}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import"dotenv/config";import ze from"dedent";import Be from"chalk";import Ue from"log-symbols";import We from"readline/promises";import Qe from"@crosscopy/clipboard";import*as Ge from"readline";import He from"strip-json-comments";import{promisify as Ve}from"util";import Ke from"ink-select-input";import*as Ye from"diff";import{Marked as Je}from"marked";import Xe from"marked-terminal";import Ze from"ink-gradient";import et from"open-editor";import tt from"semver";import nt from"ignore";import rt from"is-unicode-supported";import{wrapAnsi as st}from"fast-wrap-ansi";import ot from"terminal-link";import*as it from"process";var at,lt,ct,ut,dt,mt,pt,gt,ht,ft,yt,wt,St,bt,Et,Ct,vt,Tt,kt,_t,Pt,At,xt=Object.defineProperty,It=Object.getOwnPropertyNames,__name=(e,t)=>xt(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[It(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)xt(e,n,{get:t[n],enumerable:!0})},Nt=__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"(){}}),Rt=__esm({"../shared/src/constants/tracing.ts"(){Nt(),at="command_code_cli_tracing"}}),$t=__esm({"src/utils/telemetry/constants.ts"(){Nt(),Rt(),lt="https://api.axiom.co/v1/traces",ct="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",ut="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",dt="xaat-add69148-8f73-4833-921d-bc843285c95f",mt="command-code-cli",pt=["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"],gt=["content","body"],ht=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 Lt,Mt,Ot=__esm({"../shared/src/constants.ts"(){Nt(),yt="--xco",wt={INTERNAL_TEAM_FLAG_HEADER:`x-${(ft="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage",CLI_ENVIRONMENT:"x-cli-environment"},St={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"}}}},bt={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(bt.ALPHA.TASTE),Object.values(bt.BETA.TASTE_PACKAGES),St.ALPHA.GENERATE,St.ALPHA.AGENT.GENERATE,St.ALPHA.WHOAMI,St.ALPHA.NAMESPACES,St.ALPHA.SHARE.CREATE,St.ALPHA.SHARE.DELETE,St.ALPHA.SHARE.APPEND,St.ALPHA.DEVREL_THREAD.CREATE,St.ALPHA.DEVREL_THREAD.DELETE,St.ALPHA.DEVREL_THREAD.UPDATE,St.ALPHA.TASTE.LEARN,St.ALPHA.TASTE.DELETE,St.ALPHA.TASTE.GET,St.ALPHA.TASTE.UPDATE,Object.values(St.BETA.TASTE.PACKAGES),St.INTERNAL.ADMIN.USERS,St.INTERNAL.ADMIN.ORGS,St.INTERNAL.ADMIN.ENTITY_TYPE,St.INTERNAL.USER.AVATAR,St.INTERNAL.USER.SETTINGS,St.INTERNAL.API_KEYS.LIST,St.INTERNAL.API_KEYS.CREATE,St.INTERNAL.API_KEYS.DELETE,St.INTERNAL.USAGE.LIST,St.INTERNAL.USAGE.SUMMARY,St.INTERNAL.ADMIN.GRANT_CREDITS,St.INTERNAL.ADMIN.GRANT_ORG_CREDITS,St.INTERNAL.BILLING.CREDITS.GET,St.INTERNAL.BILLING.CUSTOMERS.GET,St.INTERNAL.BILLING.CUSTOMERS.UPSERT,St.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,St.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,St.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,St.INTERNAL.BILLING.CUSTOMERS.INVOICES,St.INTERNAL.BILLING.SUBSCRIPTIONS.GET,St.INTERNAL.ORGS.LIST,St.INTERNAL.ORGS.GET,St.INTERNAL.ORGS.CREATE,St.INTERNAL.ORGS.UPDATE,St.INTERNAL.ORGS.DELETE,St.INTERNAL.ORGS.MEMBERS.LIST,St.INTERNAL.ORGS.MEMBERS.ADD,St.INTERNAL.ORGS.MEMBERS.UPDATE,St.INTERNAL.ORGS.MEMBERS.REMOVE,St.INTERNAL.ORGS.INVITATIONS.LIST,St.INTERNAL.ORGS.INVITATIONS.SEND,St.INTERNAL.ORGS.INVITATIONS.ACCEPT,St.INTERNAL.ORGS.INVITATIONS.CANCEL,St.INTERNAL.TASTE.PACKAGES.LIST,Object.values(bt.INTERNAL.ORGS),Object.values(bt.INTERNAL.USER),Object.values(bt.INTERNAL.TASTE.PACKAGES),Et={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(Et.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl"),Ct={ANTHROPIC:"anthropic"},vt="anthropic:claude-haiku-4-5-20251001",p.enum(["owner","admin","member"]),Tt={LEARN_TASTE:"learn-taste",TASTE:"taste",TERMINAL_SETUP:"terminal-setup"},(kt={SONNET_4_6:{id:"claude-sonnet-4-6",label:"Sonnet 4.6 (default)",name:"Sonnet 4.6",description:"best combo of speed & intelligence (recommended)"},OPUS_4_6:{id:"claude-opus-4-6",label:"Opus 4.6",name:"Opus 4.6",description:"most capable for complex work"},SONNET_4_5:{id:"claude-sonnet-4-5-20250929",label:"Sonnet 4.5",name:"Sonnet 4.5",description:"previous generation, balanced speed & quality"},OPUS_4_5:{id:"claude-opus-4-5-20251101",label:"Opus 4.5",name:"Opus 4.5",description:"previous generation, highly capable"}}).SONNET_4_6.id,kt.SONNET_4_5.id,kt.OPUS_4_5.id,kt.OPUS_4_6.id,_t=kt.SONNET_4_6.id,new Set([].map(e=>e.toLowerCase())),Pt=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],At={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}}}),Dt=__esm({"src/utils/env.ts"(){Nt(),Lt=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),Mt=__name(()=>{const e=Lt();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag")}});function getAuthDir(){return t.join(f.homedir(),".commandcode")}function getAuthFile(e){const n=e??Lt(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??Lt(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var qt,Ft,jt=__esm({"src/utils/auth/auth-paths.ts"(){Nt(),Ot(),Dt(),__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 S.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(;!S.existsSync(n);){const s=t.dirname(n);if(s===n)return t.normalize(e);r.unshift(t.basename(n)),n=s}return t.join(getCanonicalPath(n),...r)}catch{return t.normalize(e)}}function formatDirectoryForDisplay(e){const n=canonicalizeForLookup(t.normalize(e)),r=getCanonicalPath(process.cwd()),s=f.homedir();if(isPathInDirectory(n,r)){const e=t.relative(r,n);return e?`./${e}`:"."}if(s&&isPathInDirectory(n,s)){const e=t.relative(s,n);return e?`~/${e}`:"~"}return n}function isPathInDirectory(e,n){const r=normalizePathForComparison(e),s=normalizePathForComparison(n),o=s.endsWith(t.sep)?s:s+t.sep;return r===s||r.startsWith(o)}function findSensitiveDirectoryConflict(e){const n=[t.normalize(e),getCanonicalPath(e)];for(const e of qt){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(f.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,s=formatDirectoryForDisplay(n);return{status:"skipped",inputPath:t,absolutePath:n,displayPath:s,code:r,message:"ALREADY_IN_WORKSPACE"===r?`${s} is already accessible from the current workspace`:`${s} 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,s;try{r=S.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{S.accessSync(n,S.constants.R_OK),s=getCanonicalPath(n)}catch{return createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}const o=findSensitiveDirectoryConflict(s);if(o)return createErrorResult({inputPath:e,code:"SENSITIVE_DIRECTORY",message:`Cannot add ${formatDirectoryForDisplay(s)} because it overlaps sensitive path ${formatDirectoryForDisplay(o)}`});const i=getCanonicalPath(process.cwd());return isPathInDirectory(s,i)?createSkippedResult({inputPath:e,absolutePath:s,code:"ALREADY_IN_WORKSPACE"}):Ft.some(e=>isPathInDirectory(s,e)||isPathInDirectory(e,s))?createSkippedResult({inputPath:e,absolutePath:s,code:"ALREADY_ADDED"}):(Ft.push(s),{status:"added",inputPath:e,absolutePath:s,displayPath:formatDirectoryForDisplay(s)})}function getAdditionalDirectories(){return[...Ft]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Ft.findIndex(e=>areSamePath(t,e));return-1!==n&&(Ft.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Ft.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t)}var zt=__esm({"src/utils/additional-dirs.ts"(){Nt(),qt=new Set(["/etc","/root","/proc","/sys","/dev",t.join(f.homedir(),".ssh"),t.join(f.homedir(),".gnupg"),t.join(f.homedir(),".aws")]),Ft=[],__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`${f.platform()}-${f.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 S.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 I("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return I("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){try{const e=I("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=I("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,s=t.filter(e=>e.startsWith(" D")).length,o=t.filter(e=>e.startsWith("??")).length,i=[];return n>0&&i.push(`M ${n}`),r>0&&i.push(`A ${r}`),s>0&&i.push(`D ${s}`),o>0&&i.push(`?? ${o}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=I("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 Bt,Ut,Wt,Qt,Gt,Ht,Vt,Kt,Yt,Jt,Xt,Zt,en=__esm({"src/utils/environment.ts"(){Nt(),zt(),__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")}});function isWordLeftSequence(e){return!!Bt.has(e)||!!Jt.test(e)}function isWordRightSequence(e){return!!Ut.has(e)||!!Xt.test(e)}function isHomeSequence(e){return Wt.has(e)}function isEndSequence(e){return Qt.has(e)}function isForwardDeleteSequence(e){return Gt.has(e)}function isDeleteWordSequence(e){return Ht.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===Vt.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===Vt.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===Vt.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===Vt.CTRL_U}function isAltP(e){return Yt.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}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)||Zt.includes(t))}var tn,nn,rn,sn,on,an,ln=__esm({"src/utils/keyboard-sequences.ts"(){Nt(),Bt=new Set(["","b","","",""]),Ut=new Set(["","f","","",""]),Wt=new Set(["","[1~","[7~","OH"]),Qt=new Set(["","[4~","[8~","OF"]),Gt=new Set(["[3~"]),Ht=new Set(["",""]),Vt={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},Kt={ALT_P:112,ALT_P_NO_META:960},Yt=new Set([String.fromCharCode(27,Kt.ALT_P),String.fromCharCode(Kt.ALT_P_NO_META),""]),Jt=/^\x1b\[1;[359]D$/,Xt=/^\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"),Zt=["\n","\r","","[27;2;13~","[27;2;13~","[13;2u"],__name(isNewlineShortcutKey,"isNewlineShortcutKey")}}),cn=__esm({"src/auth/index.ts"(){Nt(),Ot(),Dt(),(e=>{e.OAuth=g.object({type:g.literal("oauth"),refresh:g.string(),access:g.string(),expires:g.number()}),e.ApiKey=g.object({type:g.literal("api"),key:g.string()}),e.Info=g.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const n=__name(()=>t.join(f.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=Lt(),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 L.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const s=n(),o=r();await L.mkdir(s,{recursive:!0});let i={};try{const e=await L.readFile(o,"utf-8");i=JSON.parse(e)}catch{}i[e]=t,await L.writeFile(o,JSON.stringify(i,null,2)),await L.chmod(o,384)}async function remove(e){const t=r();try{const n=await L.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await L.unlink(t):(await L.writeFile(t,JSON.stringify(r,null,2)),await L.chmod(t,384))}catch{}}async function list2(){try{const e=await L.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")})(tn||(tn={}))}}),un=__esm({"src/utils/constants.ts"(){Nt(),Ot(),nn="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing",rn='OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.',sn=">"}}),dn=__esm({"src/auth/anthropic.ts"(){Nt(),cn(),un(),Vr(),(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 j.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return j.createHash("sha256").update(e).digest("base64url")}function generateState(){return j.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),s=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:s}).toString()}`,verifier:e,state:s}}async function exchangeCodeForTokens2(e,s,o){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:s,state:o})});if(!i.ok){const e=await i.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:Br.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const a=await i.json();await tn.set("anthropic",{type:"oauth",refresh:a.refresh_token,access:a.access_token,expires:Date.now()+1e3*a.expires_in})}async function refreshAccessToken2(){const e=await tn.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:Br.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await tn.remove("anthropic");const s=await r.json();return await tn.set("anthropic",{type:"oauth",refresh:s.refresh_token,access:s.access_token,expires:Date.now()+1e3*s.expires_in}),s.access_token}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:Br.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await tn.remove("anthropic")}}}async function getValidAccessToken2(){const e=await tn.get("anthropic");if(e)return"api"===e.type?e.key:"oauth"===e.type?await refreshAccessToken2():void 0}__name(generateCodeVerifier,"generateCodeVerifier"),__name(generateCodeChallenge,"generateCodeChallenge"),__name(generateState,"generateState"),e.createAuthorizationUrl=createAuthorizationUrl,__name(createAuthorizationUrl,"createAuthorizationUrl"),e.exchangeCodeForTokens=exchangeCodeForTokens2,__name(exchangeCodeForTokens2,"exchangeCodeForTokens"),e.refreshAccessToken=refreshAccessToken2,__name(refreshAccessToken2,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken2,__name(getValidAccessToken2,"getValidAccessToken")})(on||(on={}))}});function isWordBoundary(e){return!e||0===e.length||an.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,s=n-1,o=findLineStart(e,s),i=s-o;return o+Math.min(r,i)}function moveCursorDown(e,t){if(!e)return 0;const n=findLineStart(e,t),r=findLineEnd(e,t);if(r===e.length)return t;const s=t-n,o=r+1,i=findLineEnd(e,o)-o;return o+Math.min(s,i)}function insertTextAt(e,t,n){const r=e||"",s=clampCursor(t,r.length);return{text:r.slice(0,s)+n+r.slice(s),cursor:s+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 mn,pn,gn=__esm({"src/utils/text-navigation.ts"(){Nt(),an=/\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 stripBracketedPaste(e){return e.includes(mn)||e.includes(pn)?e.replaceAll(mn,"").replaceAll(pn,""):null}function processBracketedPasteInput({input:e,value:t,cursor:n}){const r=stripBracketedPaste(e);if(null===r)return{value:t,cursor:n,handled:!1};if(0===r.length)return{value:t,cursor:n,handled:!0};const s=insertTextAt(t,n,r);return{value:s.text,cursor:s.cursor,handled:!0}}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 s=insertTextAt(e,t,r);return{value:s.text,cursor:s.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,s){const o=t;return o.meta&&t.leftArrow?processLineStart(n,r):o.meta&&t.rightArrow?processLineEnd(n,r):o.meta&&"b"===e?processWordLeft(n,r):o.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,s):t.rightArrow?processCursorRight(n,r,s):t.upArrow?processCursorUp(n,r,s):t.downArrow?processCursorDown(n,r,s):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!o.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}var hn,fn,yn,wn=__esm({"src/tui/text/input-handlers.ts"(){Nt(),gn(),ln(),mn="[200~",pn="[201~",__name(stripBracketedPaste,"stripBracketedPaste"),__name(processBracketedPasteInput,"processBracketedPasteInput"),__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(){hn||(hn=!0,fn=[],yn=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&fn.push(t)},"earlyInputHandler"),process.stdin.on("data",yn))}function stopEarlyInputCapture(){hn&&yn&&(process.stdin.off("data",yn),yn=null,hn=!1)}function consumeBufferedInput(){const e=fn.join("");return fn=[],e}function hasBufferedInput(){return fn.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("")||e.startsWith(""))}var Sn=__esm({"src/utils/early-input-buffer.ts"(){Nt(),hn=!1,fn=[],yn=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,s]=W((e||"").length),o=Q(r),i=Q(e);G(()=>{o.current=r},[r]),G(()=>{const a=i.current;if(i.current=e,e===a)return;if(!t)return;if(!n)return;const l=(e||"").length;r>l&&(s(l),o.current=l)},[e,t,n,r]);const a=V(e=>{s(e),o.current=e},[]);return{cursor:r,setCursor:a,cursorRef:o}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:s,stripBracketedPaste:o=!1}){const i=Q(!1);G(()=>{if(!e)return;const a=process.stdin,l=__name(e=>{s(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>s(!1),0)},"emitStdinResult"),u=__name(e=>{const r=e.toString();if(o){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current});if(e.handled)return void l(e)}const s=processRawInput(r,t.current,n.current);s.handled&&l(s)},"handleRawInput");if(a.on("data",u),!i.current&&hasBufferedInput()){i.current=!0;const e=consumeBufferedInput();e&&u(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",u)}},[e,t,n,r,s,o])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:s,onUpdate:o,onSubmit:i}){Z((e,a)=>{if(s())return;if(isIgnoredKey(e,a))return;if(a.return)return void i?.(n.current);const l=processInkInput(e,a,n.current,r.current,t);if(!l.handled)return;const u=clampCursor(l.cursor,l.value.length);o(l.value,u)},{isActive:e})}function useSyncedRef(e){const t=Q(e);return t.current=e,t}var bn=__esm({"src/tui/text/hooks.ts"(){Nt(),gn(),wn(),Sn(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef")}});function renderPlaceholder(e,t){return t?0===e.length?re.inverse(" "):re.inverse(e[0])+re.gray(e.slice(1)):re.gray(e)}function renderValue(e,t,n){if(!n)return e;if(0===e.length)return re.inverse(" ");let r="";for(let n=0;n<e.length;n++)n===t?"\n"===e[n]?r+=re.inverse(" ")+"\n":r+=re.inverse(e[n]):r+=e[n];return t===e.length&&(r+=re.inverse(" ")),r}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),s=t-n,o=t;if(se(e).length<=o)return e;const i=e.split(/(\s+)/);let a="",l=0,u=!0;for(const e of i){const t=se(e).length;if(l+t>(u?o:s)&&l>0&&(a+="\n"+r,l=n,u=!1),a+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=se(t).length,u=!0}}return a}function getDisplayValue(e,t,n,r,s){const o=r&&s;return t&&0===e.length?renderPlaceholder(t,o):renderValue(e,n,o)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}var En,Cn=__esm({"src/tui/text/render-utils.ts"(){Nt(),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue")}});function createStdinUpdateHandler(e,t,n){return(r,s)=>{e(s),r!==t.current&&(n.current(r),t.current=r)}}function createInkUpdateHandler(e,t,n){return(r,s)=>{e(s),r!==t.current&&(n.current(r),t.current=r)}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:s=!0,onChange:o,onSubmit:i,onCursorChange:a,prefix:l="",prefixColor:u,stripBracketedPaste:d=!1}){const m=Q(!1),p=useSyncedRef(e),g=useSyncedRef(o),{cursor:h,setCursor:f,cursorRef:y}=useCursorState({value:e,focus:n,showCursor:s});B.useEffect(()=>{a?.(h)},[h,a]);const w=V(createStdinUpdateHandler(f,p,g),[f,p,g]),S=V(createInkUpdateHandler(f,p,g),[f,p,g]),b=V(e=>{m.current=e},[]),E=V(()=>m.current,[]);useRawStdinHandler({focus:n,valueRef:p,cursorRef:y,onUpdate:w,setHandled:b,stripBracketedPaste:d}),useInkInputHandler({focus:n,showCursor:s,valueRef:p,cursorRef:y,isHandledByStdin:E,onUpdate:S,onSubmit:i});const{stdout:C}=X(),v=C?.columns??80,T=getMaskedValue(e,r),k=u?En[u]:void 0,_=wrapWithIndent((l?k?k(l):l:"")+getDisplayValue(T,t,h,s,n),v,l?.length??0);return B.createElement(Y,{wrap:"wrap"},_)}var vn=__esm({"src/tui/text/text-input.tsx"(){Nt(),bn(),Cn(),gn(),En={white:re.white,green:re.green,red:re.red,blue:re.blue,yellow:re.yellow,cyan:re.cyan,magenta:re.magenta,gray:re.gray,grey:re.gray},__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,s=oe(n),o=await s.metadata();if(!o.width||!o.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const i=1200;let a,l,{width:u,height:d}=o;(u>i||d>i)&&(u>d?(d=Math.round(d*i/u),u=i):(u=Math.round(u*i/d),d=i)),t.includes("png")&&o.hasAlpha?(a=await s.resize(u,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),l="image/png"):(a=await s.resize(u,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),l="image/jpeg");const m=a.length;return{compressedBase64:a.toString("base64"),mediaType:l,originalSizeBytes:r,compressedSizeBytes:m,compressionRatio:r/m}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}var Tn,kn=__esm({"src/utils/image-compression.ts"(){Nt(),__name(compressImageForSharing,"compressImageForSharing")}});async function detectDroppedImageFile(e){try{if(!e||0===e.trim().length)return null;let t=e.trim();if((t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),t=t.replace(/\\(.)/g,"$1"),t.includes("\n")||t.includes("\r"))return null;const n=i(t).toLowerCase(),r=Tn[n];if(!r)return null;const s=o(t);if(!E(s))return null;const a=b(s).toString("base64");if(!a||0===a.length)return null;if(a.length>32e6)return null;const l=await compressImageForSharing(a,r);return l?{data:l.compressedBase64,mediaType:l.mediaType}:null}catch(e){return null}}async function detectClipboardImage(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasImage())return null;let t=null;try{if(t=await e.default.getImageBase64(),!t){const n=e.default.getImageBase64();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}if(!t||0===t.length)return null;if(t.length>32e6)return console.log("Image too large:",t.length,"bytes"),null;try{const e=await compressImageForSharing(t,"image/png");return e?{data:e.compressedBase64,mediaType:e.mediaType}:(console.log("Failed to compress clipboard image"),null)}catch(e){return console.log("Failed to process clipboard image:",e),null}}catch(e){return null}}async function detectClipboardText(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasText())return null;let t=null;try{if(t=await e.default.getText(),!t){const n=e.default.getText();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}return t&&0!==t.length?t:null}catch(e){return null}}var _n=__esm({"src/utils/clipboard-image.ts"(){Nt(),kn(),Tn={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/png",".tiff":"image/png"},__name(detectDroppedImageFile,"detectDroppedImageFile"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText")}});function stripBracketedPasteMarkers(e){return e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"").replace(/\x1B\[201~/g,"").replace(/\[201~/g,"")}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};const r=stripBracketedPasteMarkers(e);let s,o;if(t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){s=e.slice(0,t.index);const r=e.slice(t.index+t[0].length);if(n){const e=r.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(o=r.slice(0,e.index))}else o=r}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:r,textBeforePaste:s,pastedContent:o}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}var Pn,An,xn,In,Nn=__esm({"src/utils/bracketed-paste.ts"(){Nt(),__name(stripBracketedPasteMarkers,"stripBracketedPasteMarkers"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode")}});function getIcon(e){if(xn[e])return xn[e];const t=e.split(":")[0];return xn[t]?xn[t]:xn.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(!In){In=!0;try{w.mkdirSync(Pn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${An}\n════════════════════════════════════════════════════════════════\n\n`;w.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:s}=parseMessage(e);let o;if(r){o=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${s}`}else o=`${n} ${xn.default} ${e}`;if(t){o+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}o+="\n",w.appendFileSync(An,o,"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`;w.appendFileSync(An,t,"utf-8")}catch{}}}var Rn,$n=__esm({"src/utils/dlog.ts"(){Nt(),Pn=e.join(h.homedir(),".commandcode","logs"),An=e.join(Pn,"command.log"),xn={Startup:">",CLI:"$",Config:"#",Auth:"@",Onboarding:"*",LearningAgent:"&",Import:"<",API:"~",Sessions:"+",Observer:"!",Flow:"^",Handler:">",Helper:"-",Codex:"+",UI:"|",Hook:"%",ObserverAPI:"~",ContextEngine:"~",Updater:"^",MCP:"&",default:"-"},__name(getIcon,"getIcon"),__name(formatTime,"formatTime"),__name(parseMessage,"parseMessage"),In=!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 $.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();w.writeFileSync(t,JSON.stringify(e,null,2)),w.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!==Rn)return Rn;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),Rn=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),Rn=!0,!0;const e=await loadUserConfig();return(Rn=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),Rn}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error(rn)}function getConfiguredModel(){try{const e=getConfigFile();return(parseJSON(w.readFileSync(e,"utf-8"))||{}).model??_t}catch{return _t}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}var Ln,Mn,On,Dn,qn,Fn,jn,zn,Bn,Un,Wn,Qn,Gn,Hn,Vn,Kn,Yn,Jn,Xn,Zn,er,tr,nr=__esm({"src/utils/user-config.ts"(){Nt(),Ot(),jt(),un(),$n(),ir(),ar(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),Rn=null,__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel")}}),rr=__esm({"src/tui/colors.ts"(){Nt(),Ln={CYAN:"#7AD4D6",GREEN:"#2EBD8E",GRAY:"#636D83",WHITE:"#E5E5E5",YELLOW:"#F5B731",RED:"#E84057",BLUE:"#5945B1",MAGENTA:"#F2608A",DIM:"#636D83"},Mn="#E4CCFF",On={BADGE_BG:"#08575B",BADGE_FG:"#f4f4f4",TEXT:"#02888E"},Dn="#E4CCFF",qn="#F5B731",Fn={REMOVED_BG:"#5C0112",ADDED_BG:"#04473A",REMOVED_TEXT:"#D95A6A",ADDED_TEXT:"#4CC88E",REMOVED_HIGHLIGHT_BG:"#7D2233",ADDED_HIGHLIGHT_BG:"#2E6B4A",LINE_NUM:"#636D83"},jn={BG:"#5945B1",FG:"#f4f4f4"},zn={BG:"#6943FF",FG:"#f4f4f4"},Bn={SUCCESS:"#35AD68",ERROR:"#E84057",WARNING:"#F5B731",IN_PROGRESS:"#E4CCFF"},Un="#B1BAF9",Wn="#636D83",Qn={BG:"#2D2B55",POINTER:"#A599E9"},Gn="#F5B731",Hn="#8367F4",Vn={OPEN:"#F5B731",MERGED:"#A78BFA"},Kn="#F49D2A",Yn={CODE:"#B1BAF9",HEADING:"#A599E9"},Jn=["#A599E9","#E4CCFF","#ABA5CE","#CCC7E1","#FFFFFF","#EADAFF","#ABA5CE","#E4CCFF","#A599E9"],Xn="#6E61A3",Zn={START:"#7AD4D6",END:"#5945B1"}}}),sr=__esm({"src/tui/anthropic-auth.tsx"(){Nt(),vn(),dn(),un(),_n(),Nn(),nr(),rr(),er=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,s]=W(""),[o,i]=W(null),[a,l]=W(!1),[u,d]=W(null),[m,p]=W(!0),[g,h]=W(!1),[f,y]=W(!1);G(()=>{const{url:e,verifier:t,state:n}=on.createAuthorizationUrl();i({url:e,verifier:t,state:n})},[]);const w=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||f){if(!f||t.isPasteEnd){if(f&&t.isPasteEnd){y(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void s(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();s(e)}return}s(e)}}else if(y(!0),t.isPasteEnd){y(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void s(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();s(e)}return}},[f]);Z((e,n)=>{if(n.escape&&t(),m&&!g)if(n.return||"y"===e||"Y"===e){if(!o)return;ie(o.url).then(()=>{h(!0),p(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${o.url}`),h(!0),p(!1)})}else"n"!==e&&"N"!==e||t()});const S=__name(async()=>{if(r.trim()&&o&&!a){l(!0),d(null);try{const t=r.split("#")[0].trim();await on.exchangeCodeForTokens(t,o.verifier,o.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),l(!1),n&&n(t)}}},"handleSubmit");return m&&!g?B.createElement(K,{flexDirection:"column"},B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,color:Ln.CYAN},"Anthropic Authentication")),B.createElement(K,{marginBottom:1},B.createElement(Y,null,"Open the Anthropic auth page?",B.createElement(Y,{dimColor:!0}," (Y/n)")))):B.createElement(K,{flexDirection:"column"},B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,color:Ln.CYAN},"Anthropic Authentication")),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"After authorizing, copy the code and paste it below:")),u&&B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.RED},"Error: ",u)),B.createElement(K,null,B.createElement(Y,null,"Authorization code: "),B.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:w,onSubmit:S,placeholder:"Paste code here..."})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function getProviderDisplayName(e){if(!e)return"None";const t=tr[e];return t?.displayName||e}function getProviderConfig(e){return tr[e]}function isInternalTeamFlagPresent(){return process.argv.includes(ft)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(yt)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(w.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(tr).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var ir=__esm({"src/utils/provider-config.ts"(){Nt(),Ot(),dn(),sr(),jt(),ar(),tr={"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:er,checkAuth:__name(async()=>!!await on.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(yt)}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 L.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,s=n.forceOAuth||!1,o=isInternalTeamFlagPresent();return isInternalTeamDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):o||s?(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||!isCtrlKey({inputChar:t,key:e,letter:"o",ctrlCode:15}))}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 ar=__esm({"src/utils/utils.ts"(){Nt(),Ot(),jt(),en(),ln(),ir(),nr(),__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=S.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var lr=__esm({"src/utils/is-local-dev.ts"(){Nt(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":Lt()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return ut;case"local":return dt;default:return ct}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(w.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var cr=__esm({"src/utils/telemetry/config.ts"(){Nt(),jt(),ar(),Dt(),lr(),$t(),$t(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}}),ur={};function getPackageJson(){const e=import.meta.url,t=u(e),s=r(t);return JSON.parse(b(n(s,"./../package.json"),"utf8"))}__export(ur,{getPackageJson:()=>getPackageJson});var dr,mr,pr,gr,hr,fr,yr=__esm({"src/utils/package.ts"(){Nt(),__name(getPackageJson,"getPackageJson")}});function createAxiomExporter(){return new mr({url:lt,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":at}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return pr({[gr]:mt,[hr]: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 dr({resource:t,spanProcessors:[new fr(e)],autoDetectResources:!1})}var wr,Sr,br,Er,Cr,vr=__esm({"src/utils/telemetry/sdk-factory.ts"(){Nt(),$t(),cr(),yr(),({NodeSDK:dr}=ae),({OTLPTraceExporter:mr}=le),({resourceFromAttributes:pr}=ce),({ATTR_SERVICE_NAME:gr,ATTR_SERVICE_VERSION:hr}=ue),({SimpleSpanProcessor:fr}=de),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function generateSessionId(){return`sess_${he().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:s}=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":s,"session.platform":`${h.platform()}-${h.arch()}`,"session.node_version":process.version}}function startSession(){Cr={},Sr=null,br=null,wr=generateSessionId(),Er=Date.now();try{const e=me.getTracer(mt),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),s=buildSessionAttributes({sessionId:wr,projectPath:n,gitBranch:r,cliVersion:t});Sr=e.startSpan("session:cli",{attributes:s}),br=Sr.spanContext(),Sr.end()}catch{Sr=null,br=null}return wr}function getTraceId(){return br?br.traceId:null}function getSessionContext(){return br?me.setSpanContext(ge.active(),br):ge.active()}function endSession(e={}){const{status:t="success"}=e;if(br&&Er){const e=me.getTracer(mt),n=Date.now()-Er,r=me.setSpanContext(ge.active(),br),s=e.startSpan("session:end",{attributes:{"session.id":wr||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Cr}},r);"error"===t?s.setStatus({code:pe.ERROR}):s.setStatus({code:pe.OK}),s.end()}Sr=null,br=null,wr=null,Er=null,Cr={}}var Tr=__esm({"src/utils/telemetry/session.ts"(){Nt(),$t(),yr(),en(),wr=null,Sr=null,br=null,Er=null,Cr={},__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:pe.ERROR}):e.setStatus({code:pe.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=me.getTracer(mt),s=getSessionContext();return r.startSpan(t,{attributes:n},s)}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:pe.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 kr,_r,Pr,Ar,xr,Ir,Nr,Rr,$r,Lr,Mr,Or,Dr,qr,Fr=__esm({"src/utils/telemetry/spans.ts"(){Nt(),$t(),Tr(),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});function dedentText(e){const t=e.split("\n");let n=1/0;for(const e of t){if(0===e.trim().length)continue;const t=e.length-e.trimStart().length;t>0&&t<n&&(n=t)}return n===1/0||0===n?e:t.map(e=>0===e.trim().length?e:e.length-e.trimStart().length>=n?e.slice(n):e).join("\n")}function getEffectiveWidth({padding:e=Ar}={}){let t=80;return process.stdout.columns?t=process.stdout.columns:process.stderr.columns?t=process.stderr.columns:process.env.COLUMNS&&(t=Number(process.env.COLUMNS)),Math.max(40,t-e)}function truncateString({text:e,maxChars:t}){return e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`}function truncateCommand({command:e}){const t=e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~").replace(/C:\\Users\\[^\\]+/g,"~");if(t.length<=xr)return t;if(t.includes(" && ")){const e=t.split(" && ")[0].trim();return e.length<=xr-5?`${e} && ...`:truncateString({text:e,maxChars:xr})}return truncateString({text:t,maxChars:xr})}function truncateToVisualLines({output:e,maxVisualLines:t=kr,padding:n=Ar,maxChars:r}){const s=getEffectiveWidth({padding:n}),o=r??t*s,i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim().split("\n");let a=0,l=i.length;for(let e=0;e<i.length;e++){const n=i[e];if(0===n.trim().length)continue;const r=Math.max(1,Math.ceil(n.length/s));if(!(a+r<=t)){l=Math.max(1,e);break}a+=r}const u=l<i.length,d=i.slice(l).reduce((e,t)=>e+Math.max(1,Math.ceil(t.length/s)),0),m=i.slice(0,l).filter(e=>e.trim().length>0).join("\n");if(m.length>o){const e=m.slice(0,o-3).trimEnd(),t=e.lastIndexOf("\n"),n=t>0?e.slice(0,t):e;return{text:u?n:`${n}...`,isTruncated:!0,remainingLines:d}}return{text:m,isTruncated:u,remainingLines:d}}var jr=__esm({"src/utils/truncation.ts"(){Nt(),kr=2,_r=10,Pr=10,Ar=4,xr=100,Ir=100,Nr=50,Rr=100,$r=60,Lr=80,Mr=1e5,Or=5e4,Dr=25e3,qr=200,__name(dedentText,"dedentText"),__name(getEffectiveWidth,"getEffectiveWidth"),__name(truncateString,"truncateString"),__name(truncateCommand,"truncateCommand"),__name(truncateToVisualLines,"truncateToVisualLines")}});function isSecretKey(e){const t=e.toLowerCase();return pt.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return gt.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString2(e){return e.length<=qr?e:`${e.substring(0,qr-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>qr?truncateString2(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,s]of Object.entries(t))e[n]=sanitizeValue({value:s,key:n,visited:r});return e}return"[Unsupported]"}function sanitizeParams(e){const t=new WeakSet;t.add(e);const n={};for(const[r,s]of Object.entries(e))n[r]=sanitizeValue({value:s,key:r,visited:t});return n}function sanitizeEndpoint(e){return e.split("?")[0]}var zr=__esm({"src/utils/telemetry/sanitization.ts"(){Nt(),$t(),jr(),__name(isSecretKey,"isSecretKey"),__name(isContentKey,"isContentKey"),__name(safeStringify,"safeStringify"),__name(truncateString2,"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:s}=e;return{span:t,end:__name(e=>{const o=Date.now()-n;if(t.setAttribute(r,o),"status"in e)t.setAttribute(s,e.status),e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r,errorBody:s}=e;if(t.setAttribute("http.status_code",n),s){const e="string"==typeof s?s:safeStringify(s);t.setAttribute("http.response_body",e.substring(0,ht))}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:s,heading:o,code:i,...a}=n,l={"error.type":r.name,"error.message":r.message,"error.component":s,"error.heading":o};void 0!==i&&(l["error.code"]=String(i));for(const[e,t]of Object.entries(a))null!=t&&(l[e]="object"==typeof t?safeStringify(t):String(t));const u=createSpan({name:`error:${r.name}`,attributes:l});recordError({span:u,error:r}),u.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:s,nodeVersion:o,platform:i,arch:a}=e,l={"whoami.node_version":o,"whoami.platform":i,"whoami.arch":a,"whoami.os":`${i}-${a}`};t&&(l["whoami.user_name"]=t),n&&(l["whoami.user_id"]=n),r&&(l["whoami.org_login"]=r),s&&(l["whoami.org_id"]=s),endSpan({span:createSpan({name:"whoami",attributes:l}),status:"success"})}var Br,Ur,Wr,Qr=__esm({"src/utils/telemetry/events.ts"(){Nt(),Fr(),Tr(),$t(),zr(),zr(),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(trackError,"trackError"),__name(trackAPICallStart,"trackAPICallStart"),__name(getSupportId,"getSupportId"),__name(systemInfo,"systemInfo")}}),Gr=__esm({"src/utils/telemetry/components.ts"(){Nt(),Br={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(Wr)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(Ur=createTelemetrySDK()).start(),Wr=!0,!0}catch{return Ur=null,Wr=!1,!1}}async function shutdownTelemetry(){if(Ur&&Wr)try{endSession(),await Ur.shutdown()}catch{}finally{Ur=null,Wr=!1}}function shutdownTelemetrySync(){if(Wr)try{endSession()}catch{}}function isTelemetryInitialized(){return Wr}var Hr,Vr=__esm({"src/utils/telemetry/telemetry.ts"(){Nt(),vr(),cr(),Tr(),Fr(),Qr(),Gr(),Ur=null,Wr=!1,__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized")}});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=ye.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}function createAuthServer(e,t){let n,r;const s=new Promise((e,t)=>{n=e,r=t}),o=fe.createServer((e,s)=>{const i=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],a=e.headers.origin||"",l=i.includes(a)?a:i[0];if(s.setHeader("Access-Control-Allow-Origin",l),s.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type"),s.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return s.writeHead(204),void s.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return s.writeHead(404),void s.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return s.writeHead(405),void s.end(JSON.stringify(e))}let u="";e.on("data",t=>{u+=t.toString(),u.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(u);if(e.error){const t=e,n={success:!0};return s.writeHead(200),s.end(JSON.stringify(n)),"access_denied"===t.error?r(new Hr(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void o.close()}const i=e;if(!(i.apiKey&&i.state&&i.userId&&i.userName&&i.keyName)){const e={success:!1,error:"Missing required fields"};return s.writeHead(400),void s.end(JSON.stringify(e))}if(i.state!==t){const e={success:!1,error:"Invalid state token"};return s.writeHead(403),void s.end(JSON.stringify(e))}const a={success:!0};s.writeHead(200),s.end(JSON.stringify(a)),n(i),o.close()}catch{const e={success:!1,error:"Invalid JSON"};s.writeHead(400),s.end(JSON.stringify(e))}}),e.on("error",()=>{s.writeHead(500),s.end(JSON.stringify({success:!1,error:"Request error"}))})});return o.on("error",e=>{r(e)}),o.listen(e,"127.0.0.1"),{server:o,waitForCallback:s}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}var Kr,Yr=__esm({"src/utils/auth/local-server.ts"(){Nt(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable"),Hr=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}},__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer")}});function generateStateToken(){return F.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await ie(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:Br.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(Lt()){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)}`}async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await $.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 $.writeFile(n,r,{mode:384}),await $.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await $.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}}var Jr=__esm({"src/utils/auth/auth-flow.ts"(){Nt(),Yr(),Dt(),jt(),Vr(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl"),Kr=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}},__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials")}});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"}var Xr,Zr,es,ts=__esm({"src/api/utils.ts"(){Nt(),__name(getApiBaseUrl,"getApiBaseUrl")}});async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${St.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:Br.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:s=Xr}=e,[o,i]=W("initializing"),[a,l]=W("Starting authentication..."),[u,d]=W(""),[m,p]=W(null),g=Q(null),h=Q(!1),f=Q(!1),y=Q(null),w=Q(t),S=Q(n),b=Q(r);G(()=>{w.current=t,S.current=n,b.current=r});const E=V(()=>{y.current&&(clearTimeout(y.current),y.current=null),g.current&&(stopServer(g.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),g.current=null)},[]),C=V(()=>{f.current||(f.current=!0,h.current=!0,E(),b.current())},[E]),v=V((e,t)=>{f.current||(f.current=!0,E(),w.current(e,t))},[E]),T=V((e,t)=>{f.current||(f.current=!0,E(),S.current(e,t))},[E]),k=V(async e=>{const t=sanitizeApiKey(e);if(!t)return;i("validating"),l("Validating API key...");const n=await validateApiKey(t);if(h.current)return;if(f.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 i("invalid_key"),l(e),void(y.current=setTimeout(()=>{h.current||f.current||(i("manual_entry"),l("Paste a valid API key below.")),y.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(f.current)return;await storeCredentials(e),i("success"),v(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:Br.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),l("Failed to save API key. Please try again."),i("manual_entry")}},[v]);return G(()=>{let e=!0;return __name(async()=>{if(!h.current)try{const t=await findAvailablePort(Zr,es);if(!e||h.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);p(r);const{server:o,waitForCallback:a}=createAuthServer(t,n);if(g.current=o,!e||h.current)return void await stopServer(o);i("waiting_browser"),l("Complete login in your browser...");const u=await openBrowser(r);if(!e||h.current)return;if(!u)return E(),l("Could not open browser. Paste your API key below."),void i("manual_entry");const d=new Promise((e,t)=>{setTimeout(()=>{t(new Kr("TIMEOUT","Browser authentication timed out"))},s)});try{const t=await Promise.race([a,d]);if(!e||h.current)return;if(f.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(f.current)return;if(await storeCredentials(n),!e||h.current||f.current)return;i("browser_success"),v(n,"browser")}catch(t){if(f.current)return;if(!e||h.current)return;if(t instanceof Hr)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:Br.AUTH_FLOW,heading:"Authorization denied by user"}}),i("denied"),void T("denied","Authorization denied by user.");E(),t instanceof Kr&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:Br.AUTH_FLOW,heading:"Browser auth timed out"}}),l("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:Br.AUTH_FLOW,heading:"Browser auth failed"}}),l("Browser auth failed. Paste your API key below.")),i("manual_entry")}}catch(t){if(f.current)return;if(!e||h.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:Br.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),E(),i("manual_entry"),l("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,E()}},[s,v,T,E]),{authState:o,statusMessage:a,browserUrl:m,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:k,cancel:C,hasCompleted:f.current}}var ns=__esm({"src/tui/hooks/use-auth-flow.ts"(){Nt(),Jr(),Yr(),ts(),Ot(),Vr(),Xr=12e4,Zr=5959,es=10,__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow")}});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:"}var rs,ss,os,as=__esm({"src/utils/auth/auth-status.ts"(){Nt(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel")}}),ls=__esm({"src/tui/auth-flow-ui.tsx"(){Nt(),vn(),Ot(),Dt(),as(),rr(),(rs=B.memo(({authState:e,browserUrl:t,apiKeyInput:n,setApiKeyInput:r,handleApiKeySubmit:s})=>{const o="waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,i=t&&("waiting_browser"===e||"manual_entry"===e);return B.createElement(B.Fragment,null,o&&B.createElement(K,{flexDirection:"column"},B.createElement(K,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?Ln.YELLOW:Ln.GRAY,paddingX:1},B.createElement(Y,{dimColor:!0},"API Key: "),B.createElement(K,{flexGrow:1},B.createElement(TextInput,{value:n,onChange:r,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},getAuthHelpText(e))),i&&B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,{dimColor:!0},getAuthUrlLabel(e)),B.createElement(Y,{color:Ln.CYAN,dimColor:!0},t||getStudioAuthUrl(Lt())))),"validating"===e&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Ctrl+C to cancel")))})).displayName="AuthInputSection",ss=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:s,handleApiKeySubmit:o})=>{const i=__name(()=>{switch(e){case"initializing":case"validating":default:return B.createElement(Se,{type:"dots"});case"waiting_browser":return B.createElement(Y,{color:Ln.CYAN},be.ellipsis);case"browser_success":case"success":return B.createElement(Y,{color:Ln.GREEN},be.tick);case"denied":case"invalid_key":return B.createElement(Y,{color:Ln.RED},be.cross);case"manual_entry":return B.createElement(Y,{color:Ln.YELLOW},be.arrowDown);case"error":return B.createElement(Y,{color:Ln.RED},be.warning)}},"getStatusIcon"),a=__name(()=>getAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:B.createElement(K,{flexDirection:"column",paddingY:1},B.createElement(K,{marginBottom:1},B.createElement(K,{marginRight:1},i()),B.createElement(Y,{color:a()},t)),B.createElement(rs,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:s,handleApiKeySubmit:o}))},"AuthFlowUI")}}),cs=__esm({"src/tui/login-with-api-key.tsx"(){Nt(),ns(),ls(),os=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:s,setApiKeyInput:o,handleApiKeySubmit:i,cancel:a}=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 Z((e,t)=>{t.ctrl&&"c"===e&&a()}),B.createElement(ss,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:s,setApiKeyInput:o,handleApiKeySubmit:i})},"LoginWithApiKey")}});function heading({text:e,sub:t,dim:n,green:r}){const s=t?` ${t}`:"";return r?`${re.bgGreen(re.black(` ${e} `))}${s}`:n?`${re.bgBlack(re.white(` ${e} `))}${s}`:`${re.bold(re.bgCyan(re.black(` ${e} `)))}${s}`}var us=__esm({"src/utils/heading.ts"(){Nt(),__name(heading,"heading")}});async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=on.createAuthorizationUrl(),r=await _e({message:"Open the Anthropic auth page?",initialValue:!0});if(Te(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await ie(e),console.log(),console.log(re.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(re.dim(" Open this URL in your browser:")),console.log(),console.log(re.cyan(` ${e}`)),console.log(),console.log(re.yellow(" Copy your authorization code and paste it below.")),console.log());const s=await Pe({message:"Paste your authorization code:",mask:"*"});if(Te(s))return{success:!1,error:"No API key provided"};if(!s.trim())return{success:!1,error:"No authorization code provided"};const o=s.split("#")[0].trim();return await on.exchangeCodeForTokens(o,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}var ds,ms,ps,gs=__esm({"src/commands/auth/anthropic-auth.ts"(){Nt(),dn(),__name(performAnthropicAuth,"performAnthropicAuth")}}),hs=__esm({"src/commands/auth/errors.ts"(){Nt(),ds=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},ms=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 L.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 getUserName(e){const t=await readAuthFile(e);return t&&t.userName||""}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=Ie("Checking authentication status...").start();try{const t=Lt(),n=await checkAuthStatus(t);n.error&&(e.fail(re.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(re.red("Not authenticated")),console.log(""),console.log(`${re.dim("Run")} ${re.cyan("cmd auth login")} ${re.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${re.green(be.tick)} ${re.bold("Authenticated")} with ${re.cyan("Command Code")}`),n.userName&&console.log(`${re.dim("Logged in as")} ${re.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(re.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}var fs,ys,ws,Ss,bs,Es=__esm({"src/commands/auth/status.ts"(){Nt(),Ot(),jt(),Dt(),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(getUserName,"getUserName"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction"),ps=new Ae("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction)}});function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:s=!0}){const[o,i]=W("loading"),[a,l]=W(null);return G(()=>{n().then(e=>{l(e),i(s?"success":"done")})},[n,s]),G(()=>{if("done"===o&&null!==a&&r(a),"success"===o&&null!==a){const e=setTimeout(()=>r(a),100);return()=>clearTimeout(e)}},[o,a,r]),"done"===o?null:B.createElement(ws,null,"loading"===o?B.createElement(fs,{message:e}):B.createElement(ys,{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 ${re.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${re.green(be.tick)} ${re.bold("Already logged in")}${t}`,"",`${re.dim("Run")} ${re.cyan("cmd")} ${re.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${re.green(be.tick)} ${re.bold("Logged in")}${n}`,"",`${re.dim("API key stored in")} ${re.cyan(`~/.commandcode/${t}`)}`,`${re.dim("Run")} ${re.cyan("cmd")} ${re.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 ms(e.message):isLoginCancelled(e)?new ds(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 ds||e instanceof ms}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),Ee.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await ve({message:"Select provider",options:e});if(Te(t))throw Ce(`${be.cross} No provider selected.`),new ds("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){Ce(`${be.cross} ${e}`)}function showAnthropicAuthNote(){ke("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(s=>{const o=__name(e=>{i(),s(e)},"handleComplete"),{unmount:i}=ee(B.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:o,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=ee(B.createElement(os,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=ee(B.createElement(Ss,{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=Lt(),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(`${be.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}var Cs=__esm({"src/tui/auth/login.tsx"(){Nt(),Ot(),cs(),un(),Dt(),us(),ir(),nr(),gs(),hs(),Es(),rr(),fs=__name(({message:e})=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.CYAN},B.createElement(Se,{type:"dots"})),B.createElement(Y,null," ",e)),"LoadingIndicator"),ys=__name(({message:e})=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.GREEN},be.tick),B.createElement(Y,null," ",e)),"SuccessIndicator"),ws=__name(({children:e})=>B.createElement(K,{flexDirection:"column"},B.createElement(Y,null," "),B.createElement(K,null,e)),"StatusContainer"),__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"),Ss=__name(({env:e,onComplete:t})=>{const[n,r]=W("checking"),[s,o]=W(null);return G(()=>{checkExistingAuth(e).then(e=>{o(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),G(()=>{if("checking"!==n&&null!==s){const e=setTimeout(()=>t(s),100);return()=>clearTimeout(e)}},[n,s,t]),B.createElement(ws,null,"checking"===n&&B.createElement(fs,{message:"Checking authentication status..."}),"logged_in"===n&&B.createElement(ys,{message:"Authenticated"}),"not_logged_in"===n&&B.createElement(ys,{message:"Ready to log in"}))},"AuthCheckSpinner"),__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleAnthropicAuth,"handleAnthropicAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction"),bs=new Ae("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction)}});async function safeRemoveFile(e,t){try{return await L.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"}}}var vs,Ts,ks,_s,Ps,As,xs=__esm({"src/utils/auth/logout.ts"(){Nt(),jt(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout")}});function printWarnings(e){e.length>0&&(console.warn(re.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(re.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=ee(B.createElement(Ps,{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)}var Is,Ns,Rs,$s,Ls,Ms,Os,Ds,qs,Fs,js,zs,Bs,Us,Ws=__esm({"src/tui/auth/logout.tsx"(){Nt(),xs(),rr(),vs=__name(()=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.CYAN},B.createElement(Se,{type:"dots"})),B.createElement(Y,null," Logging out...")),"LoadingIndicator"),Ts=__name(()=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.GREEN},be.tick),B.createElement(Y,null," Logged out")),"SuccessIndicator"),ks=__name(({errorMessage:e})=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.RED},be.cross),B.createElement(Y,{color:Ln.RED}," Logout failed: ",e)),"ErrorIndicator"),_s=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return B.createElement(vs,null);case"success":return B.createElement(Ts,null);case"error":return B.createElement(ks,{errorMessage:t})}},"StatusDisplay"),Ps=__name(({onComplete:e})=>{const[t,n]=W("loading"),[r,s]=W(""),[o,i]=W(null);return G(()=>{performLogout().then(e=>{i(e),e.success?n("success"):(s(e.error||"Unknown error"),n("error"))})},[]),G(()=>{if(("success"===t||"error"===t)&&o){const t=setTimeout(()=>e(o),100);return()=>clearTimeout(t)}},[t,o,e]),B.createElement(K,{flexDirection:"column"},B.createElement(Y,null," "),B.createElement(K,null,B.createElement(_s,{status:t,errorMessage:r})))},"LogoutSpinner"),__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction"),As=new Ae("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction)}}),Qs=__esm({"src/commands/auth/index.ts"(){Nt(),Cs(),Ws(),Es(),hs(),Es(),Ws(),Cs(),gs(),Dt(),jt(),new Ae("auth").description("Manage authentication with Command Code").addCommand(bs).addCommand(As).addCommand(ps)}}),Gs=__esm({"../shared/src/constants/tools.ts"(){Nt(),Is={READ_FILE:"read_file",EDIT_FILE:"edit_file",WRITE_FILE:"write_file",READ_DIRECTORY:"read_directory",READ_MULTIPLE_FILES:"read_multiple_files",GREP:"grep",SHELL_COMMAND:"shell_command",THINKING:"think",TODO_WRITE:"todo_write",QUESTION:"ask_user_question",EXPLORE:"explore",KILL_SHELL:"kill_shell",ENTER_PLAN_MODE:"enter_plan_mode",EXIT_PLAN_MODE:"exit_plan_mode",GET_DIAGNOSTICS:"get_diagnostics"},Ns={WEB_SEARCH:"web_search",WEB_FETCH:"web_fetch"},Rs=__name(e=>e===Ns.WEB_SEARCH,"isWebSearchTool"),$s=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],Ls=__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 $s.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:Rs(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),Ms=["create_file","delete_file",Is.EDIT_FILE,Is.WRITE_FILE,Is.SHELL_COMMAND],Os=[Is.SHELL_COMMAND]}}),Hs=__esm({"src/mcp/constants.ts"(){Nt(),Ds="2025-03-26",qs={name:"command-code",version:"1.0.0"},Promise.resolve().then(()=>(yr(),ur)).then(({getPackageJson:e})=>{qs.version=e().version??"1.0.0"}).catch(()=>{})}}),Vs=__esm({"src/mcp/types.ts"(){Nt(),Fs=g.object({authorizationUrl:g.string(),tokenUrl:g.string(),clientId:g.string(),clientSecret:g.string().optional(),scopes:g.array(g.string()).optional()}),js=g.object({transport:g.enum(["stdio","http"]),enabled:g.boolean().default(!0),command:g.string().optional(),args:g.array(g.string()).optional(),url:g.string().optional(),headers:g.record(g.string(),g.string()).optional(),oauth:Fs.optional(),env:g.record(g.string(),g.string()).optional()}),zs=g.object({mcpServers:g.record(g.string(),js)})}});function getUserMcpConfigPath(){return e.join(f.homedir(),".commandcode",Bs)}function getLocalMcpConfigPath(t=process.cwd()){const n=Ne(t);return e.join(f.homedir(),".commandcode","projects",n,Bs)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,Us)}function getMcpConfigPath({scope:e,projectPath:t=process.cwd()}){switch(e){case"user":return getUserMcpConfigPath();case"local":return getLocalMcpConfigPath(t);case"project":return getProjectMcpConfigPath(t)}}function getAllMcpConfigPaths(e=process.cwd()){return[{scope:"user",path:getUserMcpConfigPath()},{scope:"project",path:getProjectMcpConfigPath(e)},{scope:"local",path:getLocalMcpConfigPath(e)}]}var Ks,Ys=__esm({"src/mcp/config/scopes.ts"(){Nt(),Ot(),Bs="mcp.json",Us=".mcp.json",__name(getUserMcpConfigPath,"getUserMcpConfigPath"),__name(getLocalMcpConfigPath,"getLocalMcpConfigPath"),__name(getProjectMcpConfigPath,"getProjectMcpConfigPath"),__name(getMcpConfigPath,"getMcpConfigPath"),__name(getAllMcpConfigPaths,"getAllMcpConfigPaths")}});function getTokenFilePath(){return e.join(f.homedir(),".commandcode",Ks)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await $.readFile(e,"utf-8"),n=JSON.parse(t);return 1!==n.version||"object"!=typeof n.tokens?{version:1,tokens:{}}:n}catch(e){return dlog("[MCP] Failed to load token storage",e),{version:1,tokens:{}}}}async function saveTokenStorage(t){const n=getTokenFilePath(),r=e.dirname(n);await $.mkdir(r,{recursive:!0}),await $.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await $.chmod(n,384)}async function storeTokens(e,t){const n=await loadTokenStorage();n.tokens[e]=t,await saveTokenStorage(n)}async function getTokens(e){return(await loadTokenStorage()).tokens[e]||null}async function deleteTokens(e){const t=await loadTokenStorage();return e in t.tokens&&(delete t.tokens[e],await saveTokenStorage(t),!0)}async function hasTokens(e){return e in(await loadTokenStorage()).tokens}function isTokenExpired(e){return!!e.expiresAt&&Date.now()>=e.expiresAt-6e4}async function getValidAccessToken({serverName:e,refreshCallback:t}){const n=await getTokens(e);if(!n)return null;if(!isTokenExpired(n))return n.accessToken;if(n.refreshToken&&t)try{const r=await t(n.refreshToken);return await storeTokens(e,r),r.accessToken}catch(t){return dlog("[MCP] Token refresh failed",t),await deleteTokens(e),null}return await deleteTokens(e),null}async function listServersWithTokens(){const e=await loadTokenStorage();return Object.keys(e.tokens)}async function storeClientSecret(e,t){const n=await loadTokenStorage();n.clientSecrets||(n.clientSecrets={}),n.clientSecrets[e]=t,await saveTokenStorage(n)}async function getClientSecret(e){const t=await loadTokenStorage();return t.clientSecrets?.[e]??null}var Js=__esm({"src/mcp/auth/token-storage.ts"(){Nt(),Ot(),$n(),Ks="mcp-tokens.json",__name(getTokenFilePath,"getTokenFilePath"),__name(loadTokenStorage,"loadTokenStorage"),__name(saveTokenStorage,"saveTokenStorage"),__name(storeTokens,"storeTokens"),__name(getTokens,"getTokens"),__name(deleteTokens,"deleteTokens"),__name(hasTokens,"hasTokens"),__name(isTokenExpired,"isTokenExpired"),__name(getValidAccessToken,"getValidAccessToken"),__name(listServersWithTokens,"listServersWithTokens"),__name(storeClientSecret,"storeClientSecret"),__name(getClientSecret,"getClientSecret")}});async function loadMcpConfig({scope:e,projectPath:t=process.cwd()}){try{const n=getMcpConfigPath({scope:e,projectPath:t}),r=await $.readFile(n,"utf-8"),s=JSON.parse(r),o=zs.safeParse(s);return o.success?o.data:null}catch(e){return dlog("[MCP] Failed to load config",e),null}}async function saveMcpConfig({config:t,scope:n,projectPath:r=process.cwd()}){const s=getMcpConfigPath({scope:n,projectPath:r}),o=e.dirname(s);await $.mkdir(o,{recursive:!0}),await $.writeFile(s,JSON.stringify(t,null,2)+"\n",{mode:384})}async function loadMergedMcpConfig(e=process.cwd()){const t=getAllMcpConfigPaths(e),n={},r=new Map;for(const{scope:s}of t){const t=await loadMcpConfig({scope:s,projectPath:e});if(t?.mcpServers)for(const[e,o]of Object.entries(t.mcpServers))n[e]=o,r.set(e,s)}return{config:{mcpServers:n},serverScopes:r}}async function addMcpServer({name:e,serverConfig:t,scope:n,projectPath:r=process.cwd()}){let s=await loadMcpConfig({scope:n,projectPath:r});s||(s={mcpServers:{}});let o=t;if("project"===n&&t.oauth?.clientSecret){await storeClientSecret(e,t.oauth.clientSecret);const{clientSecret:n,...r}=t.oauth;o={...t,oauth:r}}s.mcpServers[e]=o,await saveMcpConfig({config:s,scope:n,projectPath:r})}async function removeMcpServer({name:e,scope:t,projectPath:n=process.cwd()}){const r=await loadMcpConfig({scope:t,projectPath:n});return!!r?.mcpServers[e]&&(delete r.mcpServers[e],await saveMcpConfig({config:r,scope:t,projectPath:n}),!0)}async function getMcpServer({name:e,projectPath:t=process.cwd()}){const{config:n,serverScopes:r}=await loadMergedMcpConfig(t),s=n.mcpServers[e],o=r.get(e);return s&&o?{config:s,scope:o}:null}async function listMcpServers(e=process.cwd()){const{config:t,serverScopes:n}=await loadMergedMcpConfig(e);return Object.entries(t.mcpServers).map(([e,t])=>({name:e,config:t,scope:n.get(e)}))}var Xs,Zs,eo=__esm({"src/mcp/config/mcp-config.ts"(){Nt(),Vs(),Ys(),$n(),Js(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers")}}),to=__esm({"src/mcp/client/stdio-transport.ts"(){Nt(),Xs=class _StdioTransport extends Re{constructor(e){super(),this.options=e}static{__name(this,"StdioTransport")}process=null;buffer="";pendingRequests=new Map;static REQUEST_TIMEOUT_MS=8e4;nextRequestId=0;isConnected=!1;static fromConfig(e){if("stdio"!==e.transport)throw new Error("Config is not for stdio transport");if(!e.command)throw new Error("Command is required for stdio transport");return new _StdioTransport({command:e.command,args:e.args,env:e.env})}async connect(){if(!this.isConnected)return new Promise((e,t)=>{try{this.process=N(this.options.command,this.options.args||[],{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.options.env}}),this.process.on("error",e=>{this.handleError(e),this.isConnected||t(e)}),this.process.on("exit",(e,t)=>{this.isConnected=!1,this.emit("close",e,t);for(const[,n]of this.pendingRequests){const r=t?`signal ${t}`:`code ${e}`;n.reject(new Error(`Process exited with ${r}`))}this.pendingRequests.clear()}),this.process.stdout?.on("data",e=>{this.handleData(e.toString())}),this.process.stderr?.on("data",e=>{this.emit("stderr",e.toString())}),this.isConnected=!0,e()}catch(e){t(e)}})}async request(e,t){if(!this.isConnected||!this.process?.stdin)throw new Error("Transport is not connected");const n=this.nextRequestId++,r={jsonrpc:"2.0",method:e,id:n,...t&&{params:t}};return new Promise((e,t)=>{const s=setTimeout(()=>{this.pendingRequests.delete(n),t(new Error("Request timed out"))},_StdioTransport.REQUEST_TIMEOUT_MS);this.pendingRequests.set(n,{resolve:__name(t=>{clearTimeout(s),e(t)},"resolve"),reject:__name(e=>{clearTimeout(s),t(e)},"reject")});const o=JSON.stringify(r)+"\n";this.process.stdin.write(o,e=>{e&&(clearTimeout(s),this.pendingRequests.delete(n),t(e))})})}notify(e,t){if(!this.isConnected||!this.process?.stdin)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,...t&&{params:t}},r=JSON.stringify(n)+"\n";this.process.stdin.write(r,e=>{e&&this.handleError(e)})}async close(){this.process&&(this.process.stdin?.end(),this.process.kill(),this.process=null),this.isConnected=!1,this.pendingRequests.clear()}get connected(){return this.isConnected}handleData(e){let t;for(this.buffer+=e;-1!==(t=this.buffer.indexOf("\n"));){const e=this.buffer.substring(0,t);this.buffer=this.buffer.substring(t+1),e.trim()&&this.handleMessage(e)}}handleMessage(e){try{const t=JSON.parse(e);if("id"in t&&void 0!==t.id){const e=t,n=this.pendingRequests.get(e.id);n&&(this.pendingRequests.delete(e.id),n.resolve(e))}else{const e=t;this.emit("notification",e)}}catch(t){this.emit("error",new Error(`Failed to parse message: ${e}`))}}handleError(e){this.isConnected=!1,this.emit("error",e)}}}});function fetchWithTimeout(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),Zs);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var no,ro,so=__esm({"src/mcp/fetch.ts"(){Nt(),Zs=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),oo={};function generateRandomString(e){return F.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:F.createHash("sha256").update(e).digest("base64url")}}function escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function startCallbackServer(e,t){return new Promise((n,r)=>{let s=null,o=null;const i=new Promise((e,t)=>{s=e,o=t}),a=fe.createServer((n,r)=>{const i=new d(n.url||"/",`http://${ro}:${e}`);if("/callback"===i.pathname){const e=i.searchParams.get("code"),n=i.searchParams.get("error"),a=i.searchParams.get("error_description");if(i.searchParams.get("state")!==t)r.writeHead(400,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Failed</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Failed</h1>\n\t\t\t\t\t\t\t<p>Invalid state parameter. Please try again.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),o?.(new Error("OAuth state parameter mismatch"));else if(n){const e=escapeHtml(a||n);r.writeHead(400,{"Content-Type":"text/html"}),r.end(`\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Failed</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Failed</h1>\n\t\t\t\t\t\t\t<p>${e}</p>\n\t\t\t\t\t\t\t<p>You can close this window.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t`),o?.(new Error(a||n))}else e?(r.writeHead(200,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Successful</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Successful</h1>\n\t\t\t\t\t\t\t<p>You can close this window and return to Command Code.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),s?.(e)):(r.writeHead(400,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Invalid Request</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Invalid Request</h1>\n\t\t\t\t\t\t\t<p>No authorization code received.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),o?.(new Error("No authorization code received")))}else r.writeHead(404),r.end("Not Found")});a.on("error",r),a.listen(e,ro,()=>{n({server:a,getCode:__name(()=>i,"getCode")})})})}async function exchangeCodeForTokens(e,t,n,r){const s=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r,client_id:e.clientId,code_verifier:n});e.clientSecret&&s.set("client_secret",e.clientSecret);const o=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()});if(!o.ok){const e=await o.text();throw new Error(`Token exchange failed: ${o.status} ${e}`)}const i=await o.json();return{accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?Date.now()+1e3*i.expires_in:void 0,tokenType:i.token_type,scope:i.scope}}async function refreshAccessToken({config:e,refreshToken:t}){const n=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId});e.clientSecret&&n.set("client_secret",e.clientSecret);const r=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});if(!r.ok){const e=await r.text();throw new Error(`Token refresh failed: ${r.status} ${e}`)}const s=await r.json();return{accessToken:s.access_token,refreshToken:s.refresh_token||t,expiresAt:s.expires_in?Date.now()+1e3*s.expires_in:void 0,tokenType:s.token_type,scope:s.scope}}async function performOAuthFlow(e,t,n){const r=n?.port||no,s=n?.timeout||12e4,o=n?.onStatus||(()=>{});let i=null;try{const n=generatePKCE(),a=generateRandomString(32),l=`http://${ro}:${r}/callback`;o("Starting authentication server...");const{server:u,getCode:m}=await startCallbackServer(r,a);i=u;const p=new d(t.authorizationUrl);if(p.searchParams.set("response_type","code"),p.searchParams.set("client_id",t.clientId),p.searchParams.set("redirect_uri",l),p.searchParams.set("state",a),p.searchParams.set("code_challenge",n.challenge),p.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&p.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))p.searchParams.set(e,n);o("Opening browser for authentication..."),await ie(p.toString()),o("Waiting for authorization...");const g=m();let h;const f=new Promise((e,t)=>{h=setTimeout(()=>t(new Error("Authentication timed out")),s)}),y=await Promise.race([g,f]);clearTimeout(h),o("Exchanging authorization code for tokens...");const w=await exchangeCodeForTokens(t,y,n.verifier,l);return await storeTokens(e,w),o("Authentication successful!"),{success:!0,tokens:w}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{i&&i.close()}}function createRefreshCallback(e){return t=>refreshAccessToken({config:e,refreshToken:t})}__export(oo,{DEFAULT_OAUTH_CALLBACK_PORT:()=>no,LOCALHOST_IP:()=>ro,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var io,ao,lo,co=__esm({"src/mcp/auth/oauth-flow.ts"(){Nt(),Js(),so(),no=8085,ro="127.0.0.1",__name(generateRandomString,"generateRandomString"),__name(generatePKCE,"generatePKCE"),__name(escapeHtml,"escapeHtml"),__name(startCallbackServer,"startCallbackServer"),__name(exchangeCodeForTokens,"exchangeCodeForTokens"),__name(refreshAccessToken,"refreshAccessToken"),__name(performOAuthFlow,"performOAuthFlow"),__name(createRefreshCallback,"createRefreshCallback")}}),uo=__esm({"src/mcp/client/http-transport.ts"(){Nt(),Hs(),Js(),so(),io=class _HttpTransport extends Re{constructor(e){super(),this.options=e}static{__name(this,"HttpTransport")}nextRequestId=0;isConnected=!1;abortController=null;static fromConfig({config:e,serverName:t}){if("http"!==e.transport)throw new Error("Config is not for http transport");if(!e.url)throw new Error("URL is required for http transport");return new _HttpTransport({url:e.url,headers:e.headers,serverName:t,oauth:e.oauth?{authorizationUrl:e.oauth.authorizationUrl,tokenUrl:e.oauth.tokenUrl,clientId:e.oauth.clientId,clientSecret:e.oauth.clientSecret,scopes:e.oauth.scopes}:void 0})}async connect(){this.isConnected||(this.abortController=new AbortController,this.isConnected=!0)}sessionId=null;async getHeaders(){const e={"Content-Type":"application/json",Accept:"application/json, text/event-stream","User-Agent":`${qs.name}/${qs.version}`,...this.options.headers};if(this.sessionId&&(e["Mcp-Session-Id"]=this.sessionId),this.options.serverName&&this.options.oauth){if(!this.options.oauth.clientSecret){const e=await getClientSecret(this.options.serverName);e&&(this.options.oauth.clientSecret=e)}const t=__name(async e=>{const{refreshAccessToken:t}=await Promise.resolve().then(()=>(co(),oo));return t({config:this.options.oauth,refreshToken:e})},"refreshCallback"),n=await getValidAccessToken({serverName:this.options.serverName,refreshCallback:t});n&&(e.Authorization=`Bearer ${n}`)}return e}parseSSEResponse(e){const t=e.split("\n");for(const e of t)if(e.startsWith("data: ")){const t=e.slice(6).trim();if(t&&"[DONE]"!==t)try{return JSON.parse(t)}catch{}}return null}async request(e,t){if(!this.isConnected)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,id:this.nextRequestId++,...t&&{params:t}},r=new AbortController,s=setTimeout(()=>r.abort(),Zs);this.abortController&&this.abortController.signal.addEventListener("abort",()=>r.abort(),{once:!0});try{const e=await this.getHeaders(),t=await fetch(this.options.url,{method:"POST",headers:e,body:JSON.stringify(n),signal:r.signal});if(!t.ok){let e=t.statusText;try{const n=await t.text(),r=JSON.parse(n);r.error?.message?e=r.error.message:r.message&&(e=r.message)}catch{}throw new Error(`MCP connection failed (${t.status}): ${e}`)}const s=t.headers.get("mcp-session-id");s&&(this.sessionId=s);const o=t.headers.get("content-type")||"",i=await t.text();if(o.includes("text/event-stream")||i.startsWith("event:")||i.startsWith("data:")){const e=this.parseSSEResponse(i);if(e)return e;throw new Error("Failed to parse SSE response")}return JSON.parse(i)}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw new Error("Request timed out");throw e}finally{clearTimeout(s)}}async notify(e,t){if(!this.isConnected)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,...t&&{params:t}},r=new AbortController,s=setTimeout(()=>r.abort(),Zs);this.abortController&&this.abortController.signal.addEventListener("abort",()=>r.abort(),{once:!0});try{const e=await this.getHeaders();await fetch(this.options.url,{method:"POST",headers:e,body:JSON.stringify(n),signal:r.signal})}catch(e){e instanceof Error&&"AbortError"!==e.name&&this.emit("error",e)}finally{clearTimeout(s)}}async close(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.isConnected=!1,this.emit("close")}get connected(){return this.isConnected}}}});function getMcpConnectionManager(){return lo||(lo=new ao),lo}var mo=__esm({"src/mcp/client/connection-manager.ts"(){Nt(),Hs(),eo(),to(),uo(),po(),ao=class extends Re{static{__name(this,"McpConnectionManager")}connections=new Map;initialized=!1;initializePromise=null;async initialize(e=process.cwd()){if(!this.initialized){if(this.initializePromise)return this.initializePromise;this.initializePromise=this.doInitialize(e);try{await this.initializePromise}finally{this.initializePromise=null}}}async doInitialize(e){const{config:t,serverScopes:n}=await loadMergedMcpConfig(e),r=[];for(const[e,s]of Object.entries(t.mcpServers)){if(!s.enabled)continue;const t=n.get(e);r.push(this.connectServer(e,s,t))}await Promise.allSettled(r),this.initialized=!0}async connectServer(e,t,n){const r={name:e,config:t,scope:n,transport:this.createTransport(t,e),status:"connecting",tools:[]};this.connections.set(e,r),this.emit("connecting",e);try{await r.transport.connect();const t=await this.initializeProtocol(r);if(r.serverInfo=t.serverInfo,r.capabilities=t.capabilities,r.transport instanceof Xs?r.transport.notify("notifications/initialized"):await r.transport.notify("notifications/initialized"),t.capabilities.tools){const e=await this.fetchTools(r);r.tools=e.tools}r.status="connected",this.emit("connected",e,r.tools.length)}catch(t){r.status="error",r.error=t instanceof Error?t.message:String(t),this.emit("error",e,r.error)}}createTransport(e,t){return"stdio"===e.transport?Xs.fromConfig(e):io.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:Ds,capabilities:{roots:{}},clientInfo:qs});if(t.error)throw new Error(`Initialize failed: ${t.error.message}`);return t.result}async fetchTools(e){const t=await e.transport.request("tools/list");if(t.error)throw new Error(`Tools list failed: ${t.error.message}`);return t.result}getConnectedServers(){return Array.from(this.connections.values()).map(e=>({name:e.name,config:e.config,scope:e.scope,status:e.status,error:e.error,capabilities:e.capabilities,serverInfo:e.serverInfo,tools:e.tools}))}getAllTools(){const e=[];for(const t of this.connections.values())if("connected"===t.status)for(const n of t.tools)e.push({serverName:t.name,tool:n,prefixedName:`mcp__${t.name}__${n.name}`});return e}async callTool(e,t,n){const r=this.connections.get(e);if(!r)throw new Error(`Server '${e}' not found`);if("connected"!==r.status)throw new Error(`Server '${e}' is not connected (status: ${r.status})`);const s=await r.transport.request("tools/call",{name:t,arguments:n});if(s.error)throw new Error(`Tool call failed: ${s.error.message}`);return s.result}async callToolByPrefixedName(e,t){const n=parseMcpToolName(e);if(!n)throw new Error(`Invalid MCP tool name: ${e}`);return this.callTool(n.serverName,n.toolName,t)}async disconnectServer(e){const t=this.connections.get(e);t&&(await t.transport.close(),t.status="disconnected",this.emit("disconnected",e))}async disconnectAll(){const e=[];for(const t of this.connections.values())e.push(t.transport.close());await Promise.allSettled(e),this.connections.clear(),this.initialized=!1}async reconnectServer(e){const t=this.connections.get(e);if(!t)throw new Error(`Server '${e}' not found`);await t.transport.close(),await this.connectServer(e,t.config,t.scope)}get isInitialized(){return this.initialized}},lo=null,__name(getMcpConnectionManager,"getMcpConnectionManager")}});function mcpToolToSchema({serverName:e,tool:t}){return{name:`mcp__${e}__${t.name}`,description:t.description||`MCP tool: ${t.name} (from ${e})`,input_schema:{type:"object",properties:t.inputSchema.properties??{},required:t.inputSchema.required}}}function getAllMcpToolSchemas(){return getMcpConnectionManager().getAllTools().map(({serverName:e,tool:t})=>mcpToolToSchema({serverName:e,tool:t}))}function isMcpTool(e){return e.startsWith("mcp__")}function parseMcpToolName(e){if(!isMcpTool(e))return null;const t=e.split("__");return t.length<3?null:{serverName:t[1],toolName:t.slice(2).join("__")}}async function executeMcpTool({prefixedName:e,args:t}){const n=getMcpConnectionManager();try{const r=await n.callToolByPrefixedName(e,t),s=r.content.map(e=>"text"===e.type?e.text||"":"image"===e.type?`[Image: ${e.mimeType||"unknown type"}]`:"resource"===e.type?`[Resource: ${e.mimeType||"unknown type"}]`:"").join("\n");return{success:!r.isError,result:s,...r.isError&&{error:s}}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}var po=__esm({"src/mcp/client/tool-adapter.ts"(){Nt(),mo(),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool")}});function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",s=e.relative(n,t);return s.startsWith("..")?r&&t.startsWith(r)?t.replace(r,"~"):t:""===s?e.basename(t):s}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}var ho,fo,yo,wo,So,bo,Eo,Co,vo,To,ko,_o,Po,Ao,xo,Io,No,Ro,$o,Lo,Mo,Oo,Do,qo,Fo,jo,zo,Bo,Uo,Wo,Qo,Go,Ho,Vo,Ko=__esm({"src/tools/utils/path-display.ts"(){Nt(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText")}}),Yo={};__export(Yo,{FeedEntrySchema:()=>Po,LLM_STATUS_MESSAGES:()=>Uo,createAgentToolEntry:()=>qo,createAssistantEntry:()=>Io,createBashEntry:()=>Ro,createCommandResultEntry:()=>Oo,createErrorEntry:()=>Lo,createIDEStatusEntry:()=>Do,createInfoEntry:()=>xo,createSystemEntry:()=>$o,createTasteOnboardingEntry:()=>Mo,createToolEntry:()=>No,createUserEntry:()=>Ao,formatError:()=>jo,getRandomLLMStatus:()=>Wo,getToolDisplayName:()=>Qo,getToolInputContent:()=>Ho,isErrorEntry:()=>zo,isPendingEntry:()=>Bo,parseTodosFromOutput:()=>Vo,updateEntryWithOutput:()=>Fo});var Jo=__esm({"src/types/feed.ts"(){Nt(),Gs(),po(),Ko(),jr(),ho=g.object({id:g.string(),timestamp:g.number(),type:g.literal("image"),source:g.object({type:g.enum(["base64","url"]),media_type:g.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:g.string()})}),fo=g.object({id:g.string(),timestamp:g.number(),input:g.string(),output:g.string().optional(),metadata:g.record(g.string(),g.any()).optional(),images:g.array(ho).optional().default([])}),yo=fo.extend({role:g.literal("user")}),wo=fo.extend({role:g.literal("assistant")}),So=fo.extend({role:g.literal("tool"),name:g.string(),description:g.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),bo=fo.extend({role:g.literal("bash"),command:g.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),Eo=fo.extend({role:g.literal("system")}),Co=fo.extend({role:g.literal("error")}),vo=fo.extend({role:g.literal("info")}),To=fo.extend({role:g.literal("taste-onboarding")}),ko=fo.extend({role:g.literal("command-result"),hasError:g.boolean().optional(),details:g.string().optional()}),_o=fo.extend({role:g.literal("ide-status"),status:g.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:g.string().nullable(),details:g.array(g.string()).optional()}),Po=g.discriminatedUnion("role",[yo,wo,So,bo,Eo,Co,vo,To,ko,_o]),Ao=__name((e,t)=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),xo=__name((e,t)=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),Io=__name(e=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),No=__name((e,t,n)=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Ro=__name(e=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),$o=__name(e=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Lo=__name(e=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),Mo=__name(()=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Oo=__name((e,t=!1,n)=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),Do=__name((e,t,n)=>Po.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 Po.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"),Fo=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return Po.parse(n)},"updateEntryWithOutput"),jo=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),zo=__name(e=>/^error:/i.test(e.output??""),"isErrorEntry"),Bo=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),Uo=["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…"],Wo=__name(()=>Uo[Math.floor(Math.random()*Uo.length)],"getRandomLLMStatus"),Qo=__name(e=>{switch(e){case Is.READ_FILE:return"READ";case Is.EDIT_FILE:return"EDIT";case Is.WRITE_FILE:return"WRITE";case Is.READ_DIRECTORY:return"LIST";case Is.READ_MULTIPLE_FILES:return"READ MULTIPLE";case Is.GREP:return"SEARCH";case Is.SHELL_COMMAND:return"SHELL";case Is.TODO_WRITE:return"TODOS";case Is.THINKING:return"thinking…";case Ns.WEB_SEARCH:return"WEB SEARCH";case Ns.WEB_FETCH:return"WEB FETCH";case Is.QUESTION:return"QUESTION";case Is.EXPLORE:return"EXPLORE";case Is.KILL_SHELL:return"KILL SHELL";default:if(isMcpTool(e)){const t=parseMcpToolName(e);if(t){const e=t.toolName.replace(/[-_]/g," ").toUpperCase();return`${t.serverName}: ${e} (MCP)`}}return e.replace(/_/g," ").toUpperCase()}},"getToolDisplayName"),Go=__name(e=>{const t=Object.entries(e);if(0===t.length)return"";const[n,r]=t[0];return`${n}: ${truncateString({text:"string"==typeof r?r:JSON.stringify(r)??"",maxChars:$r})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),Ho=__name((e,t)=>{try{switch(e){case Is.READ_FILE:case Is.WRITE_FILE:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case Is.EDIT_FILE:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Is.READ_DIRECTORY:return toRelativePath(t.path||"directory");case Is.GREP:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Is.SHELL_COMMAND: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 Is.TODO_WRITE:let s;try{s="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=Vo(s);return`${e?e.length:0} items`}catch{return"items"}case Is.THINKING:return t.content||"planning";case Is.READ_MULTIPLE_FILES:const o=t.include||[];return Array.isArray(o)?o.join(", "):"multiple files";case Ns.WEB_SEARCH:return t.query||"search";case Ns.WEB_FETCH:return t.url||"fetch";case Is.QUESTION:return"User answered questions";case Is.KILL_SHELL:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case Is.ENTER_PLAN_MODE:case Is.EXIT_PLAN_MODE:return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return Go(t);let n=t?.messages||[];if("string"==typeof n)try{n=JSON.parse(n)}catch(e){return JSON.stringify(t||{})}if(Array.isArray(n)&&n.length>0&&n[0]&&"object"==typeof n[0]&&"content"in n[0]){const e=n[0].content;if("string"==typeof e){const t=e.trim(),n=t.indexOf(".");return truncateString({text:n>0?t.slice(0,n):t,maxChars:Lr})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),Vo=__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")}});async function resolveEditStartLine({filePath:e,oldContent:t}){const n=await P.readFile(e,"utf-8"),r=n.indexOf(t);if(-1!==r)return n.substring(0,r).split("\n").length}function isDirectoryEmpty(){try{return 0===T(process.cwd()).length}catch{return!1}}var Xo,Zo=__esm({"src/utils/fs.ts"(){Nt(),__name(resolveEditStartLine,"resolveEditStartLine"),__name(isDirectoryEmpty,"isDirectoryEmpty")}}),ei=__esm({"src/tools/skills/types.ts"(){Nt()}}),ti=__esm({"../shared/src/types/skills.ts"(){Nt(),Xo=g.object({name:g.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:g.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:g.string().optional(),compatibility:g.string().max(500,"Skill compatibility must be 500 characters or less").optional(),metadata:g.record(g.string(),g.any()).optional(),"allowed-tools":g.union([g.string(),g.array(g.string())]).optional()}),g.object({name:g.string(),description:g.string(),license:g.string().optional(),compatibility:g.string().max(500).optional(),metadata:g.record(g.string(),g.any()).optional(),"allowed-tools":g.union([g.string(),g.array(g.string())]).optional(),content:g.string(),filePath:g.string()}),g.object({name:g.string(),description:g.string(),filePath:g.string()})}});function getPersonalSkillsDir(){return t.join(f.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return t.join(process.cwd(),".commandcode","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await L.access(r),r}catch{}const s=t.join(n,"skill.md");try{return await L.access(s),s}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await L.access(n);const e=await L.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await L.stat(t.join(n,e.name))).isDirectory()?e:null}catch{return null}return null}))).filter(e=>null!==e);return(await Promise.all(r.map(async e=>{try{const r=await resolveSkillFilePath({skillDir:t.join(n,e.name)});if(!r)return null;const s=await L.readFile(r,"utf-8"),{data:o}=$e(s),i=Xo.parse(o);return i.name!==e.name?null:{name:i.name,description:i.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}}var ni=__esm({"src/tools/skills/loader.ts"(){Nt(),ti(),Ot(),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries")}});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,s=[...n,...r];return 0===s.length?"":`<available_skills>\n${s.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>`}var ri,si,oi,ii,ai,li,ci,ui,di,mi,pi=__esm({"src/tools/skills/xml-generator.ts"(){Nt(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML")}}),gi=__esm({"src/tools/skills/index.ts"(){Nt(),ei(),ni(),pi()}}),hi=__esm({"src/api/errors.ts"(){Nt(),ri=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 s=t;this.error=s,this.code=s?.code,this.status=s?.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 si({cause:t instanceof Error?t:void 0});const s=t?.error;switch(e){case 400:return new oi(e,s,n,r);case 401:return new ii(e,s,n,r);case 403:return new ai(e,s,n,r);case 404:return new li(e,s,n,r);case 409:return new ci(e,s,n,r);case 422:return new ui(e,s,n,r);case 429:return new di(e,s,n,r);default:return e>=500?new mi(e,s,n,r):new _APIError(e,s,n,r)}}},si=class extends ri{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)}},oi=class extends ri{static{__name(this,"BadRequestError")}status=400},ii=class extends ri{static{__name(this,"AuthenticationError")}status=401},ai=class extends ri{static{__name(this,"PermissionDeniedError")}status=403},li=class extends ri{static{__name(this,"NotFoundError")}status=404},ci=class extends ri{static{__name(this,"ConflictError")}status=409},ui=class extends ri{static{__name(this,"UnprocessableEntityError")}status=422},di=class extends ri{static{__name(this,"RateLimitError")}status=429},mi=class extends ri{static{__name(this,"InternalServerError")}}}});function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}var fi,yi,wi,Si=__esm({"src/utils/index.ts"(){Nt(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath")}}),bi=__esm({"src/tools/read-file/types.ts"(){Nt(),fi=g.object({absolutePath:g.string().describe("The absolute path to the file to read"),offset:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional()).describe("Optional line number to start reading from (0-based index)"),limit:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional()).describe("Optional number of lines to read")}),g.object({content:g.union([g.string(),g.instanceof(Buffer)]),contentType:g.enum(["text","binary"]),fileType:g.string(),size:g.number(),linesRead:g.number().optional()}),yi=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:s}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new yi("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=e.normalize(n);try{await $.access(o,w.constants.F_OK|w.constants.R_OK)}catch{throw new yi(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await $.stat(o)).isFile())throw new yi("Path does not point to a file","NOT_A_FILE");const i=getFileType(o),a=isBinaryFile(i);if(void 0!==r&&void 0===s||void 0===r&&void 0!==s)throw new yi("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new yi("Offset must be >= 0","INVALID_OFFSET");if(void 0!==s&&s<=0)throw new yi("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await $.readFile(o);return{fileType:i,content:e,size:e.length,contentType:"binary"}}if(void 0!==r&&void 0!==s){const e=await readTextFileLines(o,r,s);return{fileType:i,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await $.readFile(o,"utf8");return{content:e,fileType:i,contentType:"text",size:e.length}}}catch(e){if(e instanceof yi)throw e;throw new yi(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}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",...wi}[n]||"unknown"}function isBinaryFile(e){return Object.values(wi).includes(e)}async function readTextFileLines(e,t,n){const r=(await $.readFile(e,"utf8")).split(/\r?\n/),s=t,o=Math.min(s+n,r.length),i=r.slice(s,o);return{content:i.join("\n"),linesRead:i.length}}var Ei=__esm({"src/tools/read-file/read-file.ts"(){Nt(),Si(),bi(),__name(readFileContent,"readFileContent"),wi={".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"},__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines")}});async function processFileReferences(t){const n=[];let r=t;const s=[...t.matchAll(/@([^\s@]+)/g)];for(const t of s){const s=t[0],o=t[1];try{const t=e.isAbsolute(o)?o:e.resolve(process.cwd(),o),i=await readFileContent({absolutePath:t});if("binary"===i.contentType)continue;const a=String(i.content),l=e.relative(process.cwd(),t),u=1e5;if(a.length>u){n.push({token:s,resolvedPath:t,content:"",tooLarge:!0});const e=`${l}`;r=r.replace(s,e);continue}n.push({token:s,resolvedPath:t,content:a});const d=`{${l}: ${a}}`;r=r.replace(s,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}var Ci=__esm({"src/utils/file-references.ts"(){Nt(),Ei(),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent")}});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")}var vi,Ti,ki,_i,Pi,Ai=__esm({"src/tools/read-file/formatter.ts"(){Nt(),__name(formatOutput,"formatOutput")}}),xi=__esm({"src/tools/read-file/index.ts"(){Nt(),bi(),Ei(),Ai(),vi={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=fi.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading file"}},"execute")}}}),Ii=__esm({"src/tools/edit-file/types.ts"(){Nt(),Ti=g.object({filePath:g.string().describe("The absolute path to the file to edit"),oldValue:g.string().describe("The text to replace"),newValue:g.string().describe("The new text to insert"),replacementCount:g.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:g.boolean().optional().describe("Whether to replace all occurrences (default: false)")}),g.object({path:g.string(),replacementsCount:g.number(),oldContent:g.string(),newContent:g.string()}),g.object({name:g.string(),message:g.string(),code:g.string().optional()})}}),Ni=__esm({"src/lib/checkpoints/types.ts"(){Nt(),ki=g.object({backupFileName:g.string().nullable(),version:g.number().int().positive(),backupTime:g.string().datetime()}),_i=g.object({messageId:g.string().uuid(),trackedFileBackups:g.record(g.string(),ki),timestamp:g.string().datetime()}),g.object({type:g.literal("file-history-snapshot"),messageId:g.string().uuid(),snapshot:_i,isSnapshotUpdate:g.boolean()}),g.object({maxFileSize:g.number().int().positive().default(10485760),retentionDays:g.number().int().positive().default(30)}),Pi=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`${j.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(f.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 L.statfs(t);return e.bavail*e.bsize}catch{return-1}}async function hasEnoughDiskSpace(e){const{fileSizeBytes:t,targetPath:n}=e,r=2*t,s=await getAvailableDiskSpace({targetPath:n});return-1===s||s>=r}async function ensureDirectoryExists(e){const{dirPath:t}=e;await L.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await L.writeFile(r,n);const e=await L.stat(r),s="string"==typeof n?Buffer.byteLength(n,"utf-8"):n.length;if(e.size!==s)throw new Error(`Write verification failed: expected ${s} bytes, got ${e.size}`);await L.rename(r,t)}catch(e){try{await L.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await L.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await L.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),s=Math.floor(r/60),o=Math.floor(s/60),i=Math.floor(o/24);return i>0?`${i}d ago`:o>0?`${o}h ago`:s>0?`${s}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}var Ri,$i,Li,Mi,Oi=__esm({"src/lib/checkpoints/utils.ts"(){Nt(),Ot(),__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(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod")}}),Di=__esm({"src/lib/checkpoints/file-history.ts"(){Nt(),Ni(),Oi(),Vr(),Ri={maxFileSize:10485760,retentionDays:30},$i=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Ri,...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 L.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,s=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const o=getBackupFilePath({sessionId:this.sessionId,backupFileName:s});await atomicWriteFile({filePath:o,content:e});const i={backupFileName:s,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,i),this.trackedState.versions.set(t,n),{success:!0,backup:i,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:Br.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 L.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new Pi(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:Br.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const s=await L.readFile(r);await atomicWriteFile({filePath:t,content:s})}async verifyRestoreOperation(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName){if(!await fileExists({filePath:t}))return{canRestore:!0};try{return await L.access(t,L.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 L.readdir(n);for(const s of e)if(!s.endsWith(".tmp")&&!t.has(s))try{await L.unlink(`${n}/${s}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await L.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}}}}),qi=__esm({"src/lib/checkpoints/checkpoint-manager.ts"(){Nt(),Di(),Oi(),jr(),Vr(),Li=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new $i({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||{},s={};for(const[e,n]of Object.entries(t)){const t=r[e];(!t||t.version!==n.version||t.backupFileName!==n.backupFileName)&&(s[e]=n)}e.trackedFileBackups=s,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=truncateString({text:t.content,maxChars:100}))}const s=Object.keys(n.trackedFileBackups);let o=null;if(s.length>0){const e=s[0];n.trackedFileBackups[e]&&(o={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:s,codeChanges:o})}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 s=0,o=0,i=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:Br.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?o++:s++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(i=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 a=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&a.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&a.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:a}),{success:!0,filesRestored:s,filesDeleted:o,messagesRemoved:i}}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}}}});function initializeCheckpointService(e){const{sessionId:t}=e;return Mi=new Li({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return Mi?Mi.backupFile({filePath:t}):{success:!0,backup:null}}var Fi=__esm({"src/lib/checkpoints/checkpoint-service.ts"(){Nt(),qi(),Mi=null,__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit")}}),ji=__esm({"src/lib/checkpoints/index.ts"(){Nt(),Ni(),Di(),qi(),Oi(),Fi()}});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:s,replaceAll:o=!1,replacementCount:i=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==s)throw createFileEditError("newValue is required","INVALID_INPUT");if(!o&&i<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await P.access(n,A.F_OK|A.R_OK|A.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${n}`,"FILE_ACCESS_ERROR")}let a;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");a=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const l=(a.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===l)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let u,d;if(o)u=l;else if(u=i,u>l)throw createFileEditError(`Expected ${u} replacements, but only found ${l} occurrences`,"INSUFFICIENT_MATCHES");let m=0;if(o||u===l)d=a.split(r).join(s),m=l;else{d=a;for(let e=0;e<u;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+s+d.substring(e+r.length),m++)}}if(0===m)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await P.writeFile(n,d,"utf-8"),{path:n,replacementsCount:m,oldContent:a,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,"\\$&")}var zi=__esm({"src/tools/edit-file/edit-file.ts"(){Nt(),Ei(),Si(),Ii(),ji(),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp")}});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}var Bi,Ui,Wi,Qi=__esm({"src/tools/edit-file/formatter.ts"(){Nt(),__name(formatOutput2,"formatOutput")}}),Gi=__esm({"src/tools/edit-file/index.ts"(){Nt(),Ii(),zi(),Qi(),Bi={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=Ti.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while editing file"}},"execute")}}}),Hi=__esm({"src/tools/read-directory/types.ts"(){Nt(),Ui=g.object({path:g.string().describe("The absolute path to the directory to read"),exclude:g.array(g.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:g.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")}),g.object({files:g.array(g.string()),directories:g.array(g.string())}),Wi=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:s=!1}=t;if(!e.isAbsolute(n))throw new Wi("Path must be absolute, not relative","INVALID_PATH");try{if(!(await $.stat(n)).isDirectory())throw new Wi("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Wi)throw e;throw new Wi(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await $.readdir(n);let o=[];s&&(o=await loadGitIgnorePatterns(n));const i=[...r,...o],a=[],l=[];for(const r of t){if(shouldIgnoreEntry(r,i))continue;const t=e.join(n,r);try{const e=await $.stat(t);e.isDirectory()?l.push(r):e.isFile()&&a.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:a.sort(),directories:l.sort()}}catch(e){if(e instanceof Wi)throw e;throw new Wi(`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 s=await findGitRoot(t);for(;r&&isWithinGitRoot(r,s);){const t=e.join(r,".gitignore");try{const e=(await $.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch(e){}const s=e.dirname(r);if(s===r)break;r=s}}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 $.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),s=e.resolve(n);return"win32"===process.platform?r.toLowerCase().startsWith(s.toLowerCase()):r.startsWith(s)}function shouldIgnoreEntry(e,t){for(const n of t)if(Le(e,n))return!0;return!1}var Vi=__esm({"src/tools/read-directory/read-directory.ts"(){Nt(),Hi(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry")}});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")}var Ki,Yi,Ji=__esm({"src/tools/read-directory/formatter.ts"(){Nt(),__name(formatOutput3,"formatOutput")}}),Xi=__esm({"src/tools/read-directory/index.ts"(){Nt(),Hi(),Vi(),Ji(),Ki={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=Ui.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading directory"}},"execute")}}}),Zi=__esm({"src/tools/write-file/types.ts"(){Nt(),Yi=g.object({filePath:g.string().describe("The absolute path where the file should be written"),content:g.string().describe("The content to write to the file")}),g.object({success:g.boolean(),message:g.string(),path:g.string().optional()})}});async function writeFile4({filePath:e,content:n}){const s=e.startsWith("~/")?t.join(f.homedir(),e.slice(2)):e;if(!l(s))throw new Error(`Invalid file path: '${s}'. Only absolute paths are supported.`);try{const e=r(s);return E(e)||await q(e,{recursive:!0}),await backupFileBeforeEdit({filePath:s}),await M(s,n,"utf-8"),{path:s,bytesWritten:Buffer.byteLength(n,"utf-8")}}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";throw new Error(`Failed to write file '${s}': ${t}`)}}var ea=__esm({"src/tools/write-file/write-file.ts"(){Nt(),ji(),__name(writeFile4,"writeFile")}});function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}var ta,na,ra,sa,oa,ia=__esm({"src/tools/write-file/formatter.ts"(){Nt(),__name(formatOutput4,"formatOutput")}}),aa=__esm({"src/tools/write-file/index.ts"(){Nt(),Zi(),ea(),ia(),ta={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=Yi.parse(e),n=await writeFile4(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")}}}),la=__esm({"src/tools/read-multiple-files/types.ts"(){Nt(),na=g.object({include:g.array(g.string()).describe("Array of glob patterns to include files"),exclude:g.array(g.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:g.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:g.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:g.string().optional().describe("Base directory for relative paths. Default: current working directory")}),ra=g.object({filePath:g.string(),content:g.string(),fileType:g.string(),size:g.number()}),g.object({content:g.string(),filesRead:g.array(g.string()),errors:g.array(g.object({file:g.string(),error:g.string()})),fileDetails:g.array(ra)}),sa=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}}}});async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const s=new Set;for(const o of e)try{(await Me(o,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>s.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${o}": ${e}`)}return Array.from(s).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:s=!0,defaultExclude:o=!0,targetDirectory:i=process.cwd()}=e;if(!n||0===n.length)throw new sa("At least one include pattern must be provided","NO_PATTERNS");const a=t.resolve(i),l={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];o&&e.push(...oa);const i=await findMatchingFiles({include:n,exclude:e,gitIgnore:s,targetDirectory:a});for(const e of i)try{const n=t.resolve(a,e),r=await readFileContent({absolutePath:n}),s=processFileResult({content:r,filePath:e});l.fileDetails.push(s),l.content+=`\n// File: ${e} (${r.fileType})\n`,l.content+=s.content,l.content+="\n",l.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);l.errors.push({file:e,error:n}),l.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return l}catch(e){if(e instanceof sa)throw e;throw new sa(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}var ca=__esm({"src/tools/read-multiple-files/read-multiple-files.ts"(){Nt(),Ei(),la(),oa=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles")}});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")}var ua,da,ma=__esm({"src/tools/read-multiple-files/formatter.ts"(){Nt(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput")}}),pa=__esm({"src/tools/read-multiple-files/index.ts"(){Nt(),la(),ca(),ma(),ua={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=na.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading multiple files"}},"execute")}}}),ga=__esm({"src/tools/grep/types.ts"(){Nt(),da=g.object({pattern:g.string().min(1,"Pattern is required"),include:g.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},g.array(g.string()).optional()),directory:g.string().optional()})}});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const s=N(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let o="",i="";s.stdout?.on("data",e=>{try{const t=e.toString();if(o.length+t.length>Mr)return i="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",void s.kill("SIGTERM");o+=t}catch(e){i+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,s.kill("SIGTERM")}}),s.stderr?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>Or)return void(i+="\n[Error output truncated: too large]");i+=t}catch(e){i+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),s.on("close",e=>{0===e?n(o):1!==e||i?r(new Error(i||`Command failed with exit code ${e}`)):n("")}),s.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,s]=t;return{file:n,line:parseInt(r,10),column:1,content:s.trim(),match:s.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",s=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)s.splice(-1,0,"--glob",e);s.splice(-1,0,"--glob","!node_modules/**"),s.splice(-1,0,"--glob","!.git/**"),s.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:s,command:"rg"})}catch(o){if(!(o instanceof Error&&o.message.includes("ENOENT")))throw o;if(r="grep",s=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)s.splice(-1,0,"--include",e);s.splice(-1,0,"--exclude-dir=node_modules"),s.splice(-1,0,"--exclude-dir=.git"),s.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:s,command:"grep"})}if(!e.trim())return[];const o=e.trim().split("\n"),i=[];for(const e of o){const t=parseGrepLine(e);t&&i.push(t)}return i}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}var ha=__esm({"src/tools/grep/grep.ts"(){Nt(),jr(),__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory")}});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,s=Object.keys(t).length;n.push(`Found ${r} matches in ${s} 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")}var fa,ya,wa,Sa=__esm({"src/tools/grep/formatter.ts"(){Nt(),__name(formatGrepResults,"formatGrepResults")}}),ba=__esm({"src/tools/grep/index.ts"(){Nt(),ga(),ha(),Sa(),fa={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=da.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while searching files"}},"execute")}}}),Ea=__esm({"src/tools/glob/types.ts"(){Nt(),ya=g.object({pattern:g.string().min(1,"Pattern is required"),path:g.string().optional()}),wa=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 wa("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new wa("Search path must be within the current working directory or an added directory","INVALID_PATH");const s=await Me(n,{cwd:e,ignore:Pt,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),o=await Promise.all(s.map(async n=>{const r=t.join(e,n);try{return{file:n,mtime:(await L.stat(r)).mtimeMs}}catch{return{file:n,mtime:0}}}));return o.sort((e,t)=>t.mtime-e.mtime),{files:o.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof wa)throw e;if(e instanceof Error)throw new wa(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new wa("Unknown error occurred during file search","UNKNOWN_ERROR")}}var Ca=__esm({"src/tools/glob/glob.ts"(){Nt(),Ea(),Ot(),zt(),__name(globSearch,"globSearch")}});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")}var va,Ta,ka,_a=__esm({"src/tools/glob/formatter.ts"(){Nt(),__name(formatGlobResults,"formatGlobResults")}}),Pa=__esm({"src/tools/glob/index.ts"(){Nt(),Ea(),Ca(),_a(),va={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=ya.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while finding files"}},"execute")}}}),Aa=__esm({"src/tools/shell-command/types.ts"(){Nt(),Ta=g.object({command:g.string().min(1,"Command cannot be empty"),args:g.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},g.array(g.string()).optional()),directory:g.string().optional(),timeout:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional())}),ka=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,s,o,i){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=s,this.stderr=o,this.duration=i}}}});async function executeShellCommand(t){const{command:n,args:r=[],directory:s,timeout:o=3e4}=t,i=Date.now();if(!n.trim())throw new ka("Command cannot be empty","EMPTY_COMMAND");let a;if(s){if(e.isAbsolute(s))throw new ka("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");a=e.resolve(process.cwd(),s)}else a=process.cwd();try{if(!(await L.stat(a)).isDirectory())throw new ka(`Path is not a directory: ${s}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof ka)throw e;throw new ka(`Directory does not exist or is not accessible: ${s||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:a,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((t,s)=>{let a="",l="",u=!1;const d=r.length>0?Oe([n,...r]):n,m=setTimeout(()=>{if(!u){p.kill("SIGTERM");const e=Date.now()-i;s(new ka(`Command timed out after ${o}ms`,"TIMEOUT",null,"SIGTERM",a,l,e))}},o),p=N(d,[],e);p.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>Mr)return l="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void p.kill("SIGTERM");a+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,p.kill("SIGTERM")}}),p.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>Or)return void(l+="\n[Error output truncated: too large]");l+=t}catch(e){l+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),p.on("close",(e,n)=>{u=!0,clearTimeout(m);const r=Date.now()-i;0===e?t({stdout:a.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):s(new ka(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,a.trim(),l.trim(),r))}),p.on("error",e=>{u=!0,clearTimeout(m);const t=Date.now()-i;s(new ka(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),l.trim(),t))})})}catch(e){if(e instanceof ka)throw e;throw new ka(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}var xa=__esm({"src/tools/shell-command/shell-command.ts"(){Nt(),Aa(),jr(),__name(executeShellCommand,"executeShellCommand")}});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")}var Ia,Na=__esm({"src/tools/shell-command/formatter.ts"(){Nt(),__name(formatShellCommandResult,"formatShellCommandResult")}}),Ra=__esm({"src/tools/shell-command/index.ts"(){Nt(),Aa(),xa(),Na(),Ia={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=Ta.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`ERROR: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`ERROR: ${e.message}`}return"ERROR: Unknown error occurred while executing command"}},"execute")}}});async function think(e){const{thought:t}=e;return`${t}`}var $a,La=__esm({"src/tools/thinking/thinking.ts"(){Nt(),__name(think,"think")}}),Ma=__esm({"src/tools/thinking/index.ts"(){Nt(),La(),$a={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)}var Oa,Da=__esm({"src/tools/todo-write/todo-write.ts"(){Nt(),__name(todoWrite,"todoWrite")}}),qa=__esm({"src/tools/todo-write/index.ts"(){Nt(),Da(),Oa={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){const n=e.questions;if("string"==typeof n)try{const t=n.replace(/,\s*([}\]])/g,"$1"),r=JSON.parse(t);if(!Array.isArray(r))return JSON.stringify({error:"The questions parameter must be an array of question objects, not a single object."});e.questions=r}catch{return JSON.stringify({error:"The questions parameter could not be parsed. Please provide questions as a valid JSON array."})}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`});n.header.length>20&&(n.header=n.header.slice(0,20).trimEnd())}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"})}}var Fa=__esm({"src/tools/ask-user-question/ask-user-question.ts"(){Nt(),__name(askUserQuestion,"askUserQuestion")}});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 s=[];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(", ");s.push(`${t} → ${r}`)}),s.join("\n")}var ja,za,Ba,Ua=__esm({"src/tools/ask-user-question/formatter.ts"(){Nt(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput")}}),Wa=__esm({"src/tools/ask-user-question/index.ts"(){Nt(),Fa(),Ua(),Ua(),ja={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 20 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")}}}),Qa=__esm({"src/tools/killshell/types.ts"(){Nt(),za=g.object({port:g.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:g.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"}),Ba=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 s=N(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let o="",i="";s.stdout?.on("data",e=>{o+=e.toString()}),s.stderr?.on("data",e=>{i+=e.toString()}),s.on("close",e=>{0===e?n(o.trim()):r(new Error(i.trim()||o.trim()))}),s.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 s=r[1].match(/:(\d+)$/);if(!s)continue;const o=parseInt(s[1],10);if(isNaN(o)||o!==e)continue;const i=parseInt(r[r.length-1],10);if(!isNaN(i))return i}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 Ba(`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 Ba("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 Ba(`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}}var Ga=__esm({"src/tools/killshell/killshell.ts"(){Nt(),Qa(),__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")}});function formatKillshellResult(e){const t=[];return t.push(`${be.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}var Ha,Va,Ka,Ya,Ja,Xa,Za,el,tl,nl,rl,sl,ol,il,al,ll,cl,ul,dl,ml=__esm({"src/tools/killshell/formatter.ts"(){Nt(),__name(formatKillshellResult,"formatKillshellResult")}}),pl=__esm({"src/tools/killshell/index.ts"(){Nt(),Qa(),Ga(),ml(),Ha={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=za.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?"ERROR: Permission denied — Process termination was not approved":formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while killing process"}},"execute")}}}),gl=__esm({"src/tools/exit-plan-mode/index.ts"(){Nt(),Va={name:"exit_plan_mode",description:'Call this tool when your plan is complete and ready for user approval.\n\nThis will:\n1. Ask the user if they want to exit plan mode and begin implementation\n2. If user says "Yes": Exit plan mode and begin implementation\n3. If user says "No": Stay in plan mode for further refinement\n\nUsage:\n- Call this AFTER writing the plan file\n- Call this AFTER asking any clarifying questions\n- This is the FINAL step in plan mode\n\nIMPORTANT: Call this tool ALONE — do not combine it with other tool calls in the same message. It switches your mode and system prompt.\n\nDO NOT:\n- Call this before the plan is written\n- Call this multiple times\n- Ask "Ready to implement?" yourself - this tool does that',acceptsCallbacks:!0,input_schema:{type:"object",properties:{},required:[]},execute:__name(async(e,t)=>{if(!t?.onQuestionRequest)return JSON.stringify({error:"Question callback not available"});const n=await t.onQuestionRequest({questions:[{question:"Exit plan mode and begin implementation?",header:"Exit Plan",options:[{label:"Yes, auto-accept",description:"Exit plan mode and implement with auto-accept (no permission prompts)"},{label:"Yes, exit",description:"Exit plan mode and implement with manual approval for each change"},{label:"Cancel",description:"Stay in plan mode to refine the plan further"}],multiSelect:!1}],hideCustomInput:!0,exitPlanMode:!0}),r=n?.answers?.[0]?.selectedOptions?.[0]||"";return r.startsWith("Yes, auto-accept")?"Exited plan mode. Now in auto-accept mode.":r.startsWith("Yes, exit")?"Exited plan mode. Now in standard mode.":"Staying in plan mode. Continue refining the plan."},"execute")}}}),hl=__esm({"src/tools/enter-plan-mode/index.ts"(){Nt(),Ka={name:"enter_plan_mode",description:'Call this tool to enter plan mode for read-only exploration and structured planning.\n\nThis will:\n1. Ask the user if they want to enter plan mode\n2. If user says "Yes": Switch to plan mode (read-only exploration and planning)\n3. If user says "No": Stay in current mode\n\nWHEN TO CALL:\n- User explicitly asks to "plan", "design", or "explore"\n- Task requires understanding multiple files/systems you haven\'t read yet\n- Task involves architectural decisions or spans 3+ files\n- You need to research the codebase before you can implement effectively\n- You\'re unsure about the right approach\n\nIMPORTANT: Call this tool ALONE — do not combine it with other tool calls in the same message. It switches your mode and system prompt, so other tools in the same message would run under the wrong mode.\n\nDO NOT:\n- Call this if already in plan mode\n- Call this for simple, well-defined tasks where you know exactly what to do',acceptsCallbacks:!0,input_schema:{type:"object",properties:{},required:[]},execute:__name(async(e,t)=>{if(!t?.onQuestionRequest)return JSON.stringify({error:"Question callback not available"});const n=await t.onQuestionRequest({questions:[{question:"Enter plan mode for read-only exploration and planning?",header:"Plan Mode",options:[{label:"Yes (Recommended)",description:"Switch to plan mode — explore codebase and create an implementation plan"},{label:"No, stay in current mode",description:"Continue without entering plan mode"}],multiSelect:!1}],hideCustomInput:!0,enterPlanMode:!0});return(n?.answers?.[0]?.selectedOptions?.[0]||"").startsWith("Yes")?"User approved. Entered plan mode. Begin exploring the codebase to understand the task.":"User chose to stay in current mode. Proceed normally."},"execute")}}}),fl=__esm({"src/tools/web-search/index.ts"(){Nt(),Ya={type:"web_search_20250305",name:"web_search",max_uses:5}}}),yl=__esm({"src/tools/web-fetch/index.ts"(){Nt(),Ja={type:"web_fetch_20250910",name:"web_fetch"}}}),wl=__esm({"src/tools/get-diagnostics/types.ts"(){Nt(),Xa=g.preprocess(e=>{if("string"==typeof e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{return[e]}return e},g.array(g.string()).optional()),Za=g.object({filePaths:Xa.describe('Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.')})}}),Sl=__esm({"src/tui/vscode-context/ipc-client.ts"(){Nt(),$n(),el=t.join(f.homedir(),".commandcode","ide"),tl=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),nl=__name(e=>{if("win32"===process.platform)return null;try{const t=I(`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"),rl=__name((e,t,n=nl)=>{const r=new Map;for(const t of e)r.set(t.session.pid,t);let s=t;for(let e=0;e<10&&null!==s;e++){const e=r.get(s);if(e)return e;s=n(s)}return null},"findAncestorSession"),sl=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),ol=__name((e,n)=>{try{S.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{S.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),il=__name((e,n={})=>{const{sessionDir:r=el,parentPidFn:s=nl,startPid:o=process.ppid}=n;try{if(!S.existsSync(r))return null;const n=`${e}-`,i=S.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),a=[];for(const e of i)try{const n=t.join(r,e),s=JSON.parse(S.readFileSync(n,"utf-8"));if(!tl(s.pid)){ol(n,r);continue}a.push({session:s,file:e})}catch{continue}if(0===a.length)return null;const l=rl(a,o,s);if(l)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:l.session.socketPath,ideName:l.session.ideName}),l.session.socketPath;const u=process.cwd();let d=null,m=0;for(const{session:e}of a)for(const n of e.workspaceFolders)(u===n||u.startsWith(n+t.sep))&&n.length>m&&(d=e,m=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"),al=__name(()=>{const e=sl();return e?il(e):null},"resolveSocketPath"),ll=__name(()=>({type:"request",id:z(),payload:{action:"getContext"}}),"createContextRequest"),cl=__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"),ul=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!cl(n))return dlog("[VSCode:IPC] Invalid message structure"),null;if("response"!==n.type)return null;if(n.id!==t)return null;const r=n.payload;return"object"!=typeof r||null===r?null:r}catch{return null}},"parseResponse"),dl=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??al()}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;dlog("[VSCode:IPC] Connecting to socket",{path:t,timeout:e});try{return await new Promise(n=>{try{const r=we.connect(t);this.socket=r;const s=__name(()=>{r.off("error",o)},"cleanup"),o=__name(e=>{clearTimeout(i),s(),this.connected=!1,dlog("[VSCode:IPC] Connection error",{error:e.message}),n(!1)},"handleError"),i=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),s(),r.destroy(),n(!1)},e);r.on("connect",()=>{try{if(clearTimeout(i),s(),this.socket!==r)return r.destroy(),void n(!1);this.connected=!0,dlog("[VSCode:IPC] Connected successfully"),r.on("close",()=>{this.connected=!1}),r.on("error",()=>{this.connected=!1}),n(!0)}catch(e){dlog("[VSCode:IPC] Error in connect handler",{error:e}),r.destroy(),n(!1)}}),r.on("error",o)}catch(e){dlog("[VSCode:IPC] Connection exception",{error:e}),n(!1)}})}catch{return!1}}async getContext(e=5e3){try{const t=this.socket;if(!t||!this.connected)return dlog("[VSCode:IPC] Cannot get context - not connected"),null;const n=ll();return await new Promise(r=>{const s=__name(()=>{t.off("data",a),t.off("error",l)},"cleanup"),o=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),s(),r(null)},e);let i="";const a=__name(e=>{try{i+=e.toString();const t=i.indexOf("\n");if(-1===t)return;clearTimeout(o),s();const a=i.slice(0,t),l=ul(Buffer.from(a),n.id);l||dlog("[VSCode:IPC] Invalid response received"),r(l)}catch(e){clearTimeout(o),s(),dlog("[VSCode:IPC] Error processing response",{error:e}),r(null)}},"handleData"),l=__name(e=>{clearTimeout(o),s(),dlog("[VSCode:IPC] Socket error during request",{error:e.message}),r(null)},"handleError");t.on("data",a),t.on("error",l);try{t.write(JSON.stringify(n)+"\n")}catch(e){clearTimeout(o),s(),dlog("[VSCode:IPC] Failed to send request",{error:e}),r(null)}})}catch{return null}}async getDiagnostics(e={}){const{filePaths:t,timeout:n=5e3}=e,r=this.socket;if(!r||!this.connected)return dlog("[VSCode:IPC] Cannot get diagnostics - not connected"),null;const s={type:"request",id:z(),payload:{action:"getDiagnostics",filePaths:t}};return new Promise(e=>{const t=__name(()=>{r.off("data",a),r.off("error",l)},"cleanup"),o=setTimeout(()=>{dlog("[VSCode:IPC] Diagnostics request timeout"),t(),e(null)},n);let i="";const a=__name(n=>{for(i+=n.toString();;){const n=i.indexOf("\n");if(-1===n)return;const r=i.slice(0,n);if(i=i.slice(n+1),r.trim())try{const n=JSON.parse(r);if(n.id!==s.id){dlog("[VSCode:IPC] Ignoring diagnostics response for different request id");continue}return clearTimeout(o),t(),void("response"===n.type&&n.payload?.diagnostics?e(n.payload.diagnostics):"error"===n.type?(dlog("[VSCode:IPC] Diagnostics error response",{message:n.payload?.message,code:n.payload?.code}),e(null)):(dlog("[VSCode:IPC] Invalid diagnostics response"),e(null)))}catch(e){dlog("[VSCode:IPC] Failed to parse diagnostics response line",{error:e})}}},"handleData"),l=__name(n=>{clearTimeout(o),t(),dlog("[VSCode:IPC] Socket error during diagnostics request",{error:n.message}),e(null)},"handleError");r.on("data",a),r.on("error",l);try{r.write(JSON.stringify(s)+"\n")}catch(n){clearTimeout(o),t(),dlog("[VSCode:IPC] Failed to send diagnostics request",{error:n}),e(null)}})}disconnect(){if(this.socket){dlog("[VSCode:IPC] Disconnecting");try{this.socket.end()}catch{}this.socket=null,this.connected=!1}}static async isAvailable(e=1e3){try{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}catch{return!1}}}}});async function fetchDiagnostics(e){if(!sl())throw new Error("Not running inside an IDE terminal. The get_diagnostics tool requires the Command Code VS Code extension.");const n=e?.map(e=>t.resolve(e)),r=new dl;try{if(!await r.connect())throw new Error("Could not connect to IDE extension. Make sure the Command Code extension is installed and active.");const e=await r.getDiagnostics({filePaths:n,timeout:5e3});if(null===e)throw new Error("Failed to get diagnostics from IDE.");return dlog("[get_diagnostics] Fetched diagnostics",{fileCount:e.length,total:e.reduce((e,t)=>e+t.diagnostics.length,0)}),e}finally{r.disconnect()}}var bl=__esm({"src/tools/get-diagnostics/get-diagnostics.ts"(){Nt(),Sl(),$n(),__name(fetchDiagnostics,"fetchDiagnostics")}});function formatDiagnostics(e){if(0===e.length)return"No diagnostics found. All files are clean.";const t=[];let n=0,r=0,s=0,o=0;for(const i of e){t.push(`${i.relativePath}:`);for(const e of i.diagnostics){const i=`L${e.range.startLine}:${e.range.startCol}`,a=e.code?` ${e.code}`:"",l=e.source?` [${e.source}]`:"";switch(t.push(` ${i} ${e.severity}${a}: ${e.message}${l}`),e.severity){case"error":n++;break;case"warning":r++;break;case"information":s++;break;case"hint":o++}}t.push("")}const i=[];n>0&&i.push(`${n} error${1!==n?"s":""}`),r>0&&i.push(`${r} warning${1!==r?"s":""}`),s>0&&i.push(`${s} info`),o>0&&i.push(`${o} hint${1!==o?"s":""}`);const a=`${e.length} file${1!==e.length?"s":""}`;return t.push(`Summary: ${i.join(", ")} across ${a}`),t.join("\n")}var El,Cl,vl,Tl=__esm({"src/tools/get-diagnostics/formatter.ts"(){Nt(),__name(formatDiagnostics,"formatDiagnostics")}}),kl=__esm({"src/tools/get-diagnostics/index.ts"(){Nt(),wl(),bl(),Tl(),El={name:"get_diagnostics",description:"Get LSP diagnostics (errors, warnings, hints) from the IDE. Returns type errors, lint warnings, and other language server diagnostics reported by all active language servers (TypeScript, ESLint, Python, etc.). Only available when connected to an IDE with the Command Code extension. Pass specific file paths when you know which files are relevant. Only omit filePaths to scan the entire workspace when the user explicitly asks for all workspace diagnostics.",input_schema:{type:"object",properties:{filePaths:{type:"array",items:{type:"string"},description:'Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.'}},required:[]},execute:__name(async e=>{const t=Za.parse(e);return formatDiagnostics(await fetchDiagnostics(t.filePaths))},"execute")}}}),_l=__esm({"src/tools/agents/defaults.ts"(){Nt(),Cl=["explore","plan","review","general"],vl=[{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__"},{name:"plan",description:"Use this to design implementation approaches by synthesizing exploration findings and considering architectural trade-offs",tools:"read_file, read_multiple_files, think",systemPrompt:"You are an implementation planner and software architect. You receive findings from exploration and design the implementation approach.\n\nTOOLS AVAILABLE:\n- read_file: Read specific files for detailed analysis\n- read_multiple_files: Read many files efficiently\n- think: Reason through design decisions\n\nYOUR ROLE:\n1. Synthesize findings from exploration agents\n2. Identify possible implementation approaches\n3. Consider architectural trade-offs and implications\n4. Determine what clarifications are needed from the user\n5. Design the optimal approach based on existing patterns\n\nDESIGN PROCESS:\n1. Review exploration findings to understand current architecture\n2. Identify 2-4 possible approaches for the task\n3. For each approach, consider:\n - How well it fits existing patterns\n - Complexity vs benefits\n - Risks and potential issues\n - What needs to be modified\n4. Determine if user clarification is needed (approach choice, scope, preferences)\n5. Recommend an approach with clear rationale\n\nOUTPUT FORMAT:\nProvide a structured analysis:\n- **Current Architecture**: Summary of relevant findings\n- **Possible Approaches**: 2-4 options with pros/cons\n- **Recommended Approach**: Your suggestion with rationale\n- **Clarifications Needed**: Questions for the user (if any)\n- **Implementation Outline**: High-level steps for the recommended approach\n\nBe concise but thorough. Focus on actionable design decisions.",location:"personal",filePath:"__builtin__"}]}});function isReservedAgentName(e){return!!e&&Cl.includes(e.toLowerCase())}var Pl=__esm({"src/tools/agents/utils.ts"(){Nt(),_l(),__name(isReservedAgentName,"isReservedAgentName")}});function getRootAgentDir(){return t.join(f.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await L.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await L.readFile(s,"utf-8"),{data:i,content:a}=$e(o),l=i.name||r.replace(".md","");if(isReservedAgentName(l))return null;let u=i.tools||"";return"*"!==u&&'"*"'!==u||(u="*"),{name:l,description:i.description||"",tools:u,systemPrompt:a.trim(),location:n,filePath:s}}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}}var Al,xl,Il,Nl,Rl,$l,Ll,Ml,Ol,Dl,ql,Fl=__esm({"src/tools/agents/loader.ts"(){Nt(),Ot(),Pl(),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents")}}),jl=__esm({"../shared/src/types/share.ts"(){Nt(),Al=g.object({messageId:g.string().optional(),timestamp:g.string(),model:g.string().optional(),duration:g.number().optional(),usage:g.object({inputTokens:g.number(),outputTokens:g.number(),totalTokens:g.number(),cacheReadTokens:g.number().optional(),cacheWriteTokens:g.number().optional(),estimatedCost:g.number().optional()}).optional(),source:g.string().optional(),context:g.object({sessionId:g.string().optional(),threadId:g.string().optional(),userId:g.string().optional()}).optional(),highlight:g.boolean().optional(),isSummary:g.boolean().optional()}),g.object({message:g.any(),meta:Al}),g.object({sessionId:g.string(),messages:g.array(g.any()).optional()}),g.object({secret:g.string(),url:g.string()}),g.object({sessionId:g.string(),secret:g.string()}),g.object({sessionId:g.string(),secret:g.string(),key:g.string(),content:g.any()}),g.object({sessionId:g.string(),secret:g.string(),message:g.any()}),g.object({shortId:g.string()}),g.object({info:g.any().optional(),messages:g.array(g.any())})}}),zl=__esm({"../shared/src/types/whoami.ts"(){Nt()}}),Bl=__esm({"../shared/src/types/email.ts"(){Nt(),g.object({to:g.union([g.email(),g.array(g.email())]),subject:g.string(),html:g.string().optional(),text:g.string().optional(),template:g.string().optional(),templateData:g.record(g.any(),g.any()).optional(),cc:g.array(g.email()).optional(),bcc:g.array(g.email()).optional(),replyTo:g.array(g.email()).optional(),tags:g.array(g.object({name:g.string(),value:g.string()})).optional()}),g.object({success:g.boolean(),messageId:g.string().optional(),error:g.string().optional()})}}),Ul=__esm({"../shared/src/types/billing.ts"(){Nt(),xl=g.enum(["active","canceled","incomplete","incomplete_expired","past_due","trialing","unpaid"]),Il=g.enum(["admin_grant","signup_credits","purchased_credits","subscription_credits"]),Nl=g.enum(["agent","learning","custom-agent","custom-agent-create"]),Rl=g.enum(["free","monthly","purchased"]),g.enum(["team","individual","enterprise"]),g.object({type:g.enum(["api","oauth"]).default("api"),orgId:g.string().nullable().optional(),model:g.string().min(1),userId:g.string().min(1),traceId:g.string(),provider:g.enum(["openai","anthropic","azure"]).default("anthropic"),tokensIn:g.number().min(0),tokensOut:g.number().min(0),inputCost:g.number().min(0),totalCost:g.number().min(0),outputCost:g.number().min(0),ownerLogin:g.string(),tokensTotal:g.number().min(0),creditsTotal:g.number().min(0),durationTotal:g.number().min(0),mode:Nl.nullable().optional(),cacheCost:g.number().min(0).optional(),cacheSavings:g.number().optional(),cacheCreation:g.object({ephemeral_5m_input_tokens:g.number().optional(),ephemeral_1h_input_tokens:g.number().optional()}).nullable().optional(),cacheCreationInputTokens:g.number().min(0).nullable().optional(),cacheReadInputTokens:g.number().min(0).nullable().optional(),threadId:g.string().nullable().optional(),messageInId:g.string().nullable().optional(),messageOutId:g.string().nullable().optional()}),g.object({success:g.boolean(),instanceId:g.string().optional(),error:g.string().optional()}),g.object({userId:g.string().min(1),orgId:g.string().nullable()}),g.object({credits:g.object({freeCredits:g.number(),belowThreshold:g.boolean(),monthlyCredits:g.number(),creditThreshold:g.number(),availableCredits:g.number(),purchasedCredits:g.number()})}),g.object({userId:g.string().min(1),orgId:g.string().nullable().optional()}),g.object({success:g.boolean(),data:g.object({id:g.string(),userId:g.uuid(),orgId:g.string().nullable(),stripeCustomerId:g.string(),autoCharge:g.boolean(),creditThreshold:g.string(),rechargeAmount:g.string(),monthlyCreditThreshold:g.string()}).optional(),error:g.string().optional()}),g.object({userId:g.string().min(1),orgId:g.string().nullable().optional(),autoCharge:g.boolean().optional(),rechargeAmount:g.number().min(0).optional(),creditThreshold:g.number().min(0).optional(),monthlyCreditThreshold:g.number().min(0).optional(),stripeCustomerId:g.string().optional()}),g.object({success:g.boolean(),data:g.object({id:g.string(),userId:g.uuid(),orgId:g.string().nullable(),stripeCustomerId:g.string(),autoCharge:g.boolean(),creditThreshold:g.string(),rechargeAmount:g.string()}).optional(),error:g.string().optional()}),g.object({userId:g.string().min(1),userEmail:g.email(),orgId:g.string().nullable().optional()}),g.object({success:g.boolean(),data:g.object({clientSecret:g.string(),customerId:g.string()}).optional(),error:g.string().optional(),message:g.string().optional()}),g.object({userId:g.string().min(1),orgId:g.string().nullable().optional()}),g.object({success:g.boolean(),data:g.object({hasPaymentMethod:g.boolean(),paymentMethods:g.array(g.object({id:g.string(),brand:g.string().optional(),last4:g.string().optional(),expMonth:g.number().optional(),expYear:g.number().optional(),default:g.boolean()})),customerId:g.string().optional()}).optional(),error:g.string().optional()}),g.object({userId:g.string().min(1),paymentMethodId:g.string().min(1),orgId:g.string().nullable().optional()}),g.object({success:g.boolean(),error:g.string().optional()}),g.object({userId:g.string().min(1),orgId:g.string().nullable().optional(),customerId:g.string().min(1),paymentMethodId:g.string().min(1)}),g.object({success:g.boolean(),message:g.string().optional(),error:g.string().optional()}),g.object({body:g.string(),signature:g.string()}),g.object({success:g.boolean(),received:g.boolean().optional(),error:g.string().optional()}),g.object({orgId:g.string().nullable().optional(),amount:g.number().min(0),credits:g.number().min(0),userEmail:g.email(),creditType:Rl.optional(),invoiceType:Il}),g.object({success:g.boolean(),message:g.string().optional(),error:g.string().optional()}),g.object({orgId:g.string().nullable(),limit:g.number().min(1).max(100).default(10),userId:g.string().min(1),startingAfter:g.string().optional()}),g.object({success:g.boolean(),data:g.object({invoices:g.array(g.object({id:g.string(),status:g.enum(["paid"]),invoicePdf:g.url().nullable(),amountPaid:g.number(),currency:g.string(),credits:g.string(),autoCharged:g.boolean(),createdAt:g.string(),invoiceType:Il})),hasMore:g.boolean()}).optional(),error:g.string().optional()}),g.object({userId:g.uuid(),orgId:g.uuid().nullable().optional()}),g.object({success:g.boolean(),data:g.object({id:g.string(),orgId:g.string().nullable(),userId:g.string().nullable(),status:xl,planId:g.string(),priceId:g.string(),quantity:g.number(),currentPeriodEnd:g.string(),cancelAtPeriodEnd:g.boolean(),currentPeriodStart:g.string()}).nullable(),error:g.string().optional()}),g.object({success:g.boolean(),data:g.object({totalGiven:g.number(),limit:g.number(),remaining:g.number()}).optional(),error:g.string().optional()}),g.object({amount:g.number().min(0)}),g.object({success:g.boolean(),totalGiven:g.number().optional(),exceeded:g.boolean().optional(),error:g.string().optional()})}}),Wl=__esm({"../shared/src/types/templates.ts"(){Nt()}}),Ql=__esm({"../shared/src/types/auth.types.ts"(){Nt()}}),Gl=__esm({"../shared/src/types/keys.types.ts"(){Nt()}}),Hl=__esm({"../shared/src/types/orgs.types.ts"(){Nt()}}),Vl=__esm({"../shared/src/types/usage.ts"(){Nt()}}),Kl=__esm({"../shared/src/types/cli-auth.types.ts"(){Nt()}}),Yl=__esm({"../shared/src/types/index.ts"(){Nt(),jl(),Bl(),Ul(),Wl(),Ql(),Gl(),Hl(),Vl(),ti(),Kl()}}),Jl=__esm({"../shared/src/utils/path-sanitizer.ts"(){Nt(),$l=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))}}}}),Xl=__esm({"../shared/src/utils/calculate-cost.ts"(){Nt(),Ot()}});function cachedError(e){if(Ll.has(e))return Ll.get(e);const t=Error.stackTraceLimit;return Error.stackTraceLimit=4,Ll.set(e,new Error),Error.stackTraceLimit=t,Ll.get(e)}var Zl,ec,tc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/query.js"(){Nt(),Ll=new Map,Ml=new Map,Ol=Symbol("OriginError"),Dl={},ql=class extends Promise{static{__name(this,"Query")}constructor(e,t,n,r,s={}){let o,i;super((e,t)=>{o=e,i=t}),this.tagged=Array.isArray(e.raw),this.strings=e,this.args=t,this.handler=n,this.canceller=r,this.options=s,this.state=null,this.statement=null,this.resolve=e=>(this.active=!1,o(e)),this.reject=e=>(this.active=!1,i(e)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[Ol]=this.handler.debug?new Error:this.tagged&&cachedError(this.strings)}get origin(){return(this.handler.debug?this[Ol].stack:this.tagged&&Ml.has(this.strings)?Ml.get(this.strings):Ml.set(this.strings,this[Ol].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(e=1,t){if(this.options.simple=!1,"function"==typeof e&&(t=e,e=1),this.cursorRows=e,"function"==typeof t)return this.cursorFn=t,this;let n;return{[Symbol.asyncIterator]:()=>({next:__name(()=>{if(this.executed&&!this.active)return{done:!0};n&&n();const e=new Promise((e,t)=>{this.cursorFn=t=>(e({value:t,done:!1}),new Promise(e=>n=e)),this.resolve=()=>(this.active=!1,e({done:!0})),this.reject=e=>(this.active=!1,t(e))});return this.execute(),e},"next"),return:()=>(n&&n(Dl),{done:!0})})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(e){return this.forEachFn=e,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}},__name(cachedError,"cachedError")}});function connection(e,t,n){const{host:r,port:s}=n||t,o=Object.assign(new Error("write "+e+" "+(t.path||r+":"+s)),{code:e,errno:e,address:t.path||r},t.path?{}:{port:s});return Error.captureStackTrace(o,connection),o}function postgres(e){const t=new Zl(e);return Error.captureStackTrace(t,postgres),t}function generic(e,t){const n=Object.assign(new Error(e+": "+t),{code:e});return Error.captureStackTrace(n,generic),n}function notSupported(e){const t=Object.assign(new Error(e+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:e});return Error.captureStackTrace(t,notSupported),t}var nc,rc,sc,oc,ic,ac,lc,cc,uc,dc,mc,pc,gc,hc,fc,yc,wc,Sc,bc,Ec,Cc,vc,Tc,kc,_c,Pc,Ac=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/errors.js"(){Nt(),Zl=class extends Error{static{__name(this,"PostgresError")}constructor(e){super(e.message),this.name=this.constructor.name,Object.assign(this,e)}},ec={connection:connection,postgres:postgres,generic:generic,notSupported:notSupported},__name(connection,"connection"),__name(postgres,"postgres"),__name(generic,"generic"),__name(notSupported,"notSupported")}});function handleValue(e,t,n,r){let s=e instanceof oc?e.value:e;if(void 0===s&&(e instanceof oc?e.value=r.transform.undefined:s=e=r.transform.undefined,void 0===s))throw ec.generic("UNDEFINED_VALUE","Undefined values are not allowed");return"$"+n.push(e instanceof oc?(t.push(e.value),e.array?e.array[e.type||pc(e.value)]||e.type||firstIsString(e.value):e.type):(t.push(e),pc(e)))}function stringify(e,t,n,r,s,o){for(let i=1;i<e.strings.length;i++)t+=stringifyValue(t,n,r,s,o)+e.strings[i],n=e.args[i];return t}function stringifyValue(e,t,n,r,s){return t instanceof ic?t.build(e,n,r,s):t instanceof ql?fragment(t,n,r,s):t instanceof sc?t.value:t&&t[0]instanceof ql?t.reduce((e,t)=>e+" "+fragment(t,n,r,s),""):handleValue(t,n,r,s)}function fragment(e,t,n,r){return e.fragment=!0,stringify(e,e.strings[0],e.args[0],t,n,r)}function valuesBuilder(e,t,n,r,s){return e.map(e=>"("+r.map(r=>stringifyValue("values",e[r],t,n,s)).join(",")+")").join(",")}function values(e,t,n,r,s){const o=Array.isArray(e[0]);return valuesBuilder(o?e:[e],n,r,t.length?t.flat():Object.keys(o?e[0]:e),s)}function select2(e,t,n,r,s){if("string"==typeof e&&(e=[e].concat(t)),Array.isArray(e))return escapeIdentifiers(e,s);let o;return(t.length?t.flat():Object.keys(e)).map(t=>(o=e[t],(o instanceof ql?fragment(o,n,r,s):o instanceof sc?o.value:handleValue(o,n,r,s))+" as "+mc(s.transform.column.to?s.transform.column.to(t):t))).join(",")}function notTagged(){throw ec.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function firstIsString(e){return Array.isArray(e)?firstIsString(e[0]):"string"==typeof e?1009:0}function typeHandlers(e){return Object.keys(e).reduce((t,n)=>(e[n].from&&[].concat(e[n].from).forEach(r=>t.parsers[r]=e[n].parse),e[n].serialize&&(t.serializers[e[n].to]=e[n].serialize,e[n].from&&[].concat(e[n].from).forEach(r=>t.serializers[r]=e[n].serialize)),t),{parsers:{},serializers:{}})}function escapeIdentifiers(e,{transform:{column:t}}){return e.map(e=>mc(t.to?t.to(e):e)).join(",")}function arrayEscape(e){return e.replace(gc,"\\\\").replace(hc,'\\"')}function arrayParserLoop(e,t,n,r){const s=[],o=1020===r?";":",";for(;e.i<t.length;e.i++){if(e.char=t[e.i],e.quoted)"\\"===e.char?e.str+=t[++e.i]:'"'===e.char?(s.push(n?n(e.str):e.str),e.str="",e.quoted='"'===t[e.i+1],e.last=e.i+2):e.str+=e.char;else if('"'===e.char)e.quoted=!0;else if("{"===e.char)e.last=++e.i,s.push(arrayParserLoop(e,t,n,r));else{if("}"===e.char){e.quoted=!1,e.last<e.i&&s.push(n?n(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1;break}e.char===o&&"}"!==e.p&&'"'!==e.p&&(s.push(n?n(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1)}e.p=e.char}return e.last<e.i&&s.push(n?n(t.slice(e.last,e.i+1)):t.slice(e.last,e.i+1)),s}function createJsonTransform(e){return __name(function jsonTransform(t,n){return"object"!=typeof t||null===t||114!==n.type&&3802!==n.type?t:Array.isArray(t)?t.map(e=>jsonTransform(e,n)):Object.entries(t).reduce((t,[r,s])=>Object.assign(t,{[e(r)]:jsonTransform(s,n)}),{})},"jsonTransform")}var xc,Ic,Nc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/types.js"(){Nt(),tc(),Ac(),nc={string:{to:25,from:null,serialize:__name(e=>""+e,"serialize")},number:{to:0,from:[21,23,26,700,701],serialize:__name(e=>""+e,"serialize"),parse:__name(e=>+e,"parse")},json:{to:114,from:[114,3802],serialize:__name(e=>JSON.stringify(e),"serialize"),parse:__name(e=>JSON.parse(e),"parse")},boolean:{to:16,from:16,serialize:__name(e=>!0===e?"t":"f","serialize"),parse:__name(e=>"t"===e,"parse")},date:{to:1184,from:[1082,1114,1184],serialize:__name(e=>(e instanceof Date?e:new Date(e)).toISOString(),"serialize"),parse:__name(e=>new Date(e),"parse")},bytea:{to:17,from:17,serialize:__name(e=>"\\x"+Buffer.from(e).toString("hex"),"serialize"),parse:__name(e=>Buffer.from(e.slice(2),"hex"),"parse")}},rc=class{static{__name(this,"NotTagged")}then(){notTagged()}catch(){notTagged()}finally(){notTagged()}},sc=class extends rc{static{__name(this,"Identifier")}constructor(e){super(),this.value=mc(e)}},oc=class extends rc{static{__name(this,"Parameter")}constructor(e,t,n){super(),this.value=e,this.type=t,this.array=n}},ic=class extends rc{static{__name(this,"Builder")}constructor(e,t){super(),this.first=e,this.rest=t}build(e,t,n,r){const s=lc.map(([t,n])=>({fn:n,i:e.search(t)})).sort((e,t)=>e.i-t.i).pop();return-1===s.i?escapeIdentifiers(this.first,r):s.fn(this.first,this.rest,t,n,r)}},__name(handleValue,"handleValue"),ac=typeHandlers(nc),__name(stringify,"stringify"),__name(stringifyValue,"stringifyValue"),__name(fragment,"fragment"),__name(valuesBuilder,"valuesBuilder"),__name(values,"values"),__name(select2,"select"),lc=Object.entries({values:values,in:__name((...e)=>{const t=values(...e);return"()"===t?"(null)":t},"in"),select:select2,as:select2,returning:select2,"\\(":select2,update:(e,t,n,r,s)=>(t.length?t.flat():Object.keys(e)).map(t=>mc(s.transform.column.to?s.transform.column.to(t):t)+"="+stringifyValue("values",e[t],n,r,s)),insert(e,t,n,r,s){const o=t.length?t.flat():Object.keys(Array.isArray(e)?e[0]:e);return"("+escapeIdentifiers(o,s)+")values"+valuesBuilder(Array.isArray(e)?e:[e],n,r,o,s)}}).map(([e,t])=>[new RegExp("((?:^|[\\s(])"+e+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),t]),__name(notTagged,"notTagged"),cc=ac.serializers,uc=ac.parsers,__name(firstIsString,"firstIsString"),dc=__name(function(e){const t=typeHandlers(e||{});return{serializers:Object.assign({},cc,t.serializers),parsers:Object.assign({},uc,t.parsers)}},"mergeUserTypes"),__name(typeHandlers,"typeHandlers"),__name(escapeIdentifiers,"escapeIdentifiers"),mc=__name(function escape(e){return'"'+e.replace(/"/g,'""').replace(/\./g,'"."')+'"'},"escape"),pc=__name(function inferType2(e){return e instanceof oc?e.type:e instanceof Date?1184:e instanceof Uint8Array?17:!0===e||!1===e?16:"bigint"==typeof e?20:Array.isArray(e)?inferType2(e[0]):0},"inferType"),gc=/\\/g,hc=/"/g,__name(arrayEscape,"arrayEscape"),fc=__name(function arraySerializer2(e,t,n,r){if(!1===Array.isArray(e))return e;if(!e.length)return"{}";const s=e[0],o=1020===r?";":",";return Array.isArray(s)&&!s.type?"{"+e.map(e=>arraySerializer2(e,t,n,r)).join(o)+"}":"{"+e.map(e=>{if(void 0===e&&void 0===(e=n.transform.undefined))throw ec.generic("UNDEFINED_VALUE","Undefined values are not allowed");return null===e?"null":'"'+arrayEscape(t?t(e.type?e.value:e):""+e)+'"'}).join(o)+"}"},"arraySerializer"),yc={i:0,char:null,str:"",quoted:!1,last:0},wc=__name(function arrayParser2(e,t,n){return yc.i=yc.last=0,arrayParserLoop(yc,e,t,n)},"arrayParser"),__name(arrayParserLoop,"arrayParserLoop"),Sc=__name(e=>{let t=e[0];for(let n=1;n<e.length;n++)t+="_"===e[n]?e[++n].toUpperCase():e[n];return t},"toCamel"),bc=__name(e=>{let t=e[0].toUpperCase();for(let n=1;n<e.length;n++)t+="_"===e[n]?e[++n].toUpperCase():e[n];return t},"toPascal"),Ec=__name(e=>e.replace(/_/g,"-"),"toKebab"),Cc=__name(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase(),"fromCamel"),vc=__name(e=>(e.slice(0,1)+e.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),"fromPascal"),Tc=__name(e=>e.replace(/-/g,"_"),"fromKebab"),__name(createJsonTransform,"createJsonTransform"),Sc.column={from:Sc},Sc.value={from:createJsonTransform(Sc)},Cc.column={to:Cc},(kc={...Sc}).column.to=Cc,bc.column={from:bc},bc.value={from:createJsonTransform(bc)},vc.column={to:vc},(_c={...bc}).column.to=vc,Ec.column={from:Ec},Ec.value={from:createJsonTransform(Ec)},Tc.column={to:Tc},(Pc={...Ec}).column.to=Tc}}),Rc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/result.js"(){Nt(),xc=class extends Array{static{__name(this,"Result")}constructor(){super(),Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}}});function Queue(e=[]){let t=e.slice(),n=0;return{get length(){return t.length-n},remove:__name(e=>{const n=t.indexOf(e);return-1===n?null:(t.splice(n,1),e)},"remove"),push:__name(e=>(t.push(e),e),"push"),shift:__name(()=>{const e=t[n++];return n===t.length?(n=0,t=[]):t[n-1]=void 0,e},"shift")}}var $c,Lc,Mc,Oc,Dc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/queue.js"(){Nt(),Ic=Queue,__name(Queue,"Queue")}});function fit(e){if($c.length-Mc.i<e){const t=$c,n=t.length;$c=Buffer.allocUnsafe(n+(n>>1)+e),t.copy($c)}}function reset(){return Mc.i=0,Mc}var qc,Fc,jc,zc,Bc,Uc,Wc,Qc,Gc,Hc,Vc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/bytes.js"(){Nt(),$c=Buffer.allocUnsafe(256),Lc="BCcDdEFfHPpQSX".split("").reduce((e,t)=>{const n=t.charCodeAt(0);return e[t]=()=>($c[0]=n,Mc.i=5,Mc),e},{}),Mc=Object.assign(reset,Lc,{N:String.fromCharCode(0),i:0,inc:e=>(Mc.i+=e,Mc),str(e){const t=Buffer.byteLength(e);return fit(t),Mc.i+=$c.write(e,Mc.i,t,"utf8"),Mc},i16:e=>(fit(2),$c.writeUInt16BE(e,Mc.i),Mc.i+=2,Mc),i32:(e,t)=>t||0===t?($c.writeUInt32BE(e,t),Mc):(fit(4),$c.writeUInt32BE(e,Mc.i),Mc.i+=4,Mc),z:e=>(fit(e),$c.fill(0,Mc.i,Mc.i+e),Mc.i+=e,Mc),raw:e=>($c=Buffer.concat([$c.subarray(0,Mc.i),e]),Mc.i=$c.length,Mc),end(e=1){$c.writeUInt32BE(Mc.i-e,e);const t=$c.subarray(0,Mc.i);return Mc.i=0,$c=Buffer.allocUnsafe(256),t}}),Oc=Mc,__name(fit,"fit"),__name(reset,"reset")}});function Connection(e,t={},{onopen:n=Qc,onend:r=Qc,onclose:s=Qc}={}){const{sslnegotiation:o,ssl:i,max:a,user:l,host:u,port:d,database:m,parsers:p,transform:g,onnotice:h,onnotify:f,onparameter:y,max_pipeline:w,keep_alive:S,backoff:b,target_session_attrs:E}=e,C=Ic(),v=Fc++,T={pid:null,secret:null},k=timer(end,e.idle_timeout),_=timer(end,e.max_lifetime),P=timer(function connectTimedOut(){errored(ec.connection("CONNECT_TIMEOUT",e,x)),x.destroy()},e.connect_timeout);let A,x=null,I=null,N=new xc,R=Buffer.alloc(0),$=e.fetch_types,L={},M={},O=Math.random().toString(36).slice(2),D=1,q=0,F=0,z=0,B=0,U=0,W=0,Q=0,G=null,H=null,V=!1,K=null,Y=null,J=null,X=null,Z=null,ee=null,te=null,ne=null,re=null,se=null;const oe={queue:t.closed,idleTimer:k,connect(e){J=e,reconnect()},terminate:terminate,execute:execute,cancel:async function cancel5({pid:e,secret:t},n,r){try{A=Oc().i32(16).i32(80877102).i32(e).i32(t).end(16),await connect(),x.once("error",r),x.once("close",n)}catch(e){r(e)}},end:end,count:0,id:v};return t.closed&&t.closed.push(oe),oe;function execute(t){if(V)return queryError(t,ec.connection("CONNECTION_DESTROYED",e));if(Z)return queryError(t,ec.generic("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(!t.cancelled)try{return t.state=T,re?C.push(t):(re=t,re.active=!0),function build(t){const n=[],r=[],s=stringify(t,t.strings[0],t.args[0],n,r,e);!t.tagged&&t.args.forEach(t=>handleValue(t,n,r,e)),t.prepare=e.prepare&&(!("prepare"in t.options)||t.options.prepare),t.string=s,t.signature=t.prepare&&r+s,t.onlyDescribe&&delete M[t.signature],t.parameters=t.parameters||n,t.prepared=t.prepare&&t.signature in M,t.describeFirst=t.onlyDescribe||n.length&&!t.prepared,t.statement=t.prepared?M[t.signature]:{string:s,types:r,name:t.prepare?O+D++:""},"function"==typeof e.debug&&e.debug(v,s,n,r)}(t),write(function toBuffer(e){if(e.parameters.length>=65534)throw ec.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return e.options.simple?Oc().Q().str(e.statement.string+Oc.N).end():e.describeFirst?Buffer.concat([describe(e),zc]):e.prepare?e.prepared?prepared(e):Buffer.concat([describe(e),prepared(e)]):function unnamed(e){return Buffer.concat([Parse(e.statement.string,e.parameters,e.statement.types),Wc,prepared(e)])}(e)}(t))&&!t.describeFirst&&!t.cursorFn&&C.length<w&&(!t.options.onexecute||t.options.onexecute(oe))}catch(e){return 0===C.length&&write(jc),errored(e),!0}}function describe(e){return Buffer.concat([Parse(e.statement.string,e.parameters,e.statement.types,e.statement.name),Describe("S",e.statement.name)])}function prepared(e){return Buffer.concat([Bind(e.parameters,e.statement.types,e.statement.name,e.cursorName),e.cursorFn?Execute("",e.cursorRows):Uc])}function write(e,t){return ee=ee?Buffer.concat([ee,e]):Buffer.from(e),ee.length>=1024?nextWrite(t):(null===H&&(H=setImmediate(nextWrite)),!0)}function nextWrite(e){const t=x.write(ee,e);return null!==H&&clearImmediate(H),ee=H=null,t}async function secure(){if("direct"!==o&&(write(Bc),!await new Promise(e=>x.once("data",t=>e(83===t[0])))&&"prefer"===i))return connected();const e={socket:x,servername:we.isIP(x.host)?void 0:x.host};"direct"===o&&(e.ALPNProtocols=["postgresql"]),"require"===i||"allow"===i||"prefer"===i?e.rejectUnauthorized=!1:"object"==typeof i&&Object.assign(e,i),x.removeAllListeners(),x=De.connect(e),x.on("secureConnect",connected),x.on("error",error),x.on("close",closed),x.on("drain",drain)}function drain(){!re&&n(oe)}function data(e){if(!(K&&(K.push(e),F-=e.length,F>0)))for(R=K?Buffer.concat(K,U-F):0===R.length?e:Buffer.concat([R,e],R.length+e.length);R.length>4;){if(U=R.readUInt32BE(1),U>=R.length){F=U-R.length,K=[R];break}try{handle(R.subarray(0,U+1))}catch(e){re&&(re.cursorFn||re.describeFirst)&&write(jc),errored(e)}R=R.subarray(U+1),F=0,K=null}}async function connect(){if(V=!1,L={},x||(x=await async function createSocket(){let t;try{t=e.socket?await Promise.resolve(e.socket(e)):new we.Socket}catch(e){return void error(e)}return t.on("error",error),t.on("close",closed),t.on("drain",drain),t}()),x){if(P.start(),e.socket)return i?secure():connected();if(x.on("connect",i?secure:connected),e.path)return x.connect(e.path);x.ssl=i,x.connect(d[z],u[z]),x.host=u[z],x.port=d[z],z=(z+1)%d.length}}function reconnect(){setTimeout(connect,q?Math.max(0,q+W-Fe.now()):0)}function connected(){try{M={},$=e.fetch_types,O=Math.random().toString(36).slice(2),D=1,_.start(),x.on("data",data),S&&x.setKeepAlive&&x.setKeepAlive(!0,1e3*S),write(function StartupMessage(){return A||Oc().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:l,database:m,client_encoding:"UTF8"},e.connection)).filter(([,e])=>e).map(([e,t])=>e+Oc.N+t).join(Oc.N)).z(2).end(0)}())}catch(e){error(e)}}function error(n){if(oe.queue!==t.connecting||!e.host[B+1])for(errored(n);C.length;)queryError(C.shift(),n)}function errored(e){Z&&(Z.destroy(e),Z=null),re&&queryError(re,e),J&&(queryError(J,e),J=null)}function queryError(t,n){if(t.reserve)return t.reject(n);n&&"object"==typeof n||(n=new Error(n)),"query"in n||"parameters"in n||Object.defineProperties(n,{stack:{value:n.stack+t.origin.replace(/.*\n/,"\n"),enumerable:e.debug},query:{value:t.string,enumerable:e.debug},parameters:{value:t.parameters,enumerable:e.debug},args:{value:t.args,enumerable:e.debug},types:{value:t.statement&&t.statement.types,enumerable:e.debug}}),t.reject(n)}function end(){return X||(!oe.reserved&&r(oe),oe.reserved||J||re||0!==C.length?X=new Promise(e=>te=e):(terminate(),new Promise(e=>x&&"closed"!==x.readyState?x.once("close",e):e())))}function terminate(){V=!0,(Z||re||J||C.length)&&error(ec.connection("CONNECTION_DESTROYED",e)),clearImmediate(H),x&&(x.removeListener("data",data),x.removeListener("connect",connected),"open"===x.readyState&&x.end(Oc().X().end())),te&&(te(),X=te=null)}async function closed(t){if(R=Buffer.alloc(0),F=0,K=null,clearImmediate(H),x.removeListener("data",data),x.removeListener("connect",connected),k.cancel(),_.cancel(),P.cancel(),x.removeAllListeners(),x=null,J)return reconnect();!t&&(re||C.length)&&error(ec.connection("CONNECTION_CLOSED",e,x)),q=Fe.now(),t&&e.shared.retries++,W=1e3*("function"==typeof b?b(e.shared.retries):b),s(oe,ec.connection("CONNECTION_CLOSED",e,x))}function handle(e,t=e[0]){(68===t?DataRow:100===t?CopyData:65===t?NotificationResponse:83===t?ParameterStatus:90===t?ReadyForQuery:67===t?CommandComplete:50===t?BindComplete:49===t?ParseComplete:116===t?ParameterDescription:84===t?RowDescription:82===t?Authentication:110===t?NoData:75===t?BackendKeyData:69===t?ErrorResponse:115===t?PortalSuspended:51===t?CloseComplete:71===t?CopyInResponse:78===t?NoticeResponse:72===t?CopyOutResponse:99===t?CopyDone:73===t?EmptyQueryResponse:86===t?FunctionCallResponse:118===t?NegotiateProtocolVersion:87===t?CopyBothResponse:UnknownMessage)(e)}function DataRow(e){let t,n,r,s=7;const o=re.isRaw?new Array(re.statement.columns.length):{};for(let i=0;i<re.statement.columns.length;i++)n=re.statement.columns[i],t=e.readInt32BE(s),s+=4,r=-1===t?null:!0===re.isRaw?e.subarray(s,s+=t):void 0===n.parser?e.toString("utf8",s,s+=t):!0===n.parser.array?n.parser(e.toString("utf8",s+1,s+=t)):n.parser(e.toString("utf8",s,s+=t)),re.isRaw?o[i]=!0===re.isRaw?r:g.value.from?g.value.from(r,n):r:o[n.name]=g.value.from?g.value.from(r,n):r;re.forEachFn?re.forEachFn(g.row.from?g.row.from(o):o,N):N[Q++]=g.row.from?g.row.from(o):o}function ParameterStatus(t){const[n,r]=t.toString("utf8",5,t.length-1).split(Oc.N);L[n]=r,e.parameters[n]!==r&&(e.parameters[n]=r,y&&y(n,r))}function ReadyForQuery(t){if(re?I?re.retried?errored(re.retried):re.prepared&&Gc.has(I.routine)?function retry(e,t){delete M[e.signature],e.retried=t,execute(e)}(re,I):errored(I):re.resolve(Y||N):I&&errored(I),re=Y=I=null,N=new xc,P.cancel(),J){if(E){if(!L.in_hot_standby||!L.default_transaction_read_only)return function fetchState(){const e=new ql(["\n show transaction_read_only;\n select pg_catalog.pg_is_in_recovery()\n "],[],execute,null,{simple:!0});e.resolve=([[e],[t]])=>{L.default_transaction_read_only=e.transaction_read_only,L.in_hot_standby=t.pg_is_in_recovery?"on":"off"},e.execute()}();if(function tryNext(t,n){return"read-write"===t&&"on"===n.default_transaction_read_only||"read-only"===t&&"off"===n.default_transaction_read_only||"primary"===t&&"on"===n.in_hot_standby||"standby"===t&&"off"===n.in_hot_standby||"prefer-standby"===t&&"off"===n.in_hot_standby&&e.host[B]}(E,L))return terminate()}return $?(J.reserve&&(J=null),async function fetchArrayTypes(){$=!1,(await new ql(["\n select b.oid, b.typarray\n from pg_catalog.pg_type a\n left join pg_catalog.pg_type b on b.oid = a.typelem\n where a.typcategory = 'A'\n group by b.oid, b.typarray\n order by b.oid\n "],[],execute)).forEach(({oid:t,typarray:n})=>function addArrayType(t,n){if(e.parsers[n]&&e.serializers[n])return;const r=e.parsers[t];e.shared.typeArrayMap[t]=n,e.parsers[n]=e=>wc(e,r,n),e.parsers[n].array=!0,e.serializers[n]=r=>fc(r,e.serializers[t],e,n)}(t,n))}()):(J&&!J.reserve&&execute(J),e.shared.retries=B=0,void(J=null))}for(;C.length&&(re=C.shift())&&(re.active=!0,re.cancelled);)Connection(e).cancel(re.state,re.cancelled.resolve,re.cancelled.reject);re||(oe.reserved?oe.reserved.release||73!==t[5]?oe.reserved():X?terminate():(oe.reserved=null,n(oe)):X?terminate():n(oe))}function CommandComplete(e){Q=0;for(let t=e.length-1;t>0;t--)if(32===e[t]&&e[t+1]<58&&null===N.count&&(N.count=+e.toString("utf8",t+1,e.length-1)),e[t-1]>=65){N.command=e.toString("utf8",5,t),N.state=T;break}return se&&(se(),se=null),"BEGIN"!==N.command||1===a||oe.reserved?re.options.simple?BindComplete():void(re.cursorFn&&(N.count&&re.cursorFn(N),write(jc))):errored(ec.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"))}function ParseComplete(){re.parsing=!1}function BindComplete(){!N.statement&&(N.statement=re.statement),N.columns=re.statement.columns}function ParameterDescription(e){const t=e.readUInt16BE(5);for(let n=0;n<t;++n)!re.statement.types[n]&&(re.statement.types[n]=e.readUInt32BE(7+4*n));re.prepare&&(M[re.signature]=re.statement),re.describeFirst&&!re.onlyDescribe&&(write(prepared(re)),re.describeFirst=!1)}function RowDescription(e){N.command&&(Y=Y||[N],Y.push(N=new xc),N.count=null,re.statement.columns=null);const t=e.readUInt16BE(5);let n,r=7;re.statement.columns=Array(t);for(let s=0;s<t;++s){for(n=r;0!==e[r++];);const t=e.readUInt32BE(r),o=e.readUInt16BE(r+4),i=e.readUInt32BE(r+6);re.statement.columns[s]={name:g.column.from?g.column.from(e.toString("utf8",n,r-1)):e.toString("utf8",n,r-1),parser:p[i],table:t,number:o,type:i},r+=18}if(N.statement=re.statement,re.onlyDescribe)return re.resolve(re.statement),write(jc)}async function Authentication(e,t=e.readUInt32BE(5)){(3===t?AuthenticationCleartextPassword:5===t?AuthenticationMD5Password:10===t?SASL:11===t?SASLContinue:12===t?SASLFinal:0!==t?UnknownAuth:Qc)(e,t)}async function AuthenticationCleartextPassword(){const e=await Pass();write(Oc().p().str(e).z(1).end())}async function AuthenticationMD5Password(e){const t="md5"+await md5(Buffer.concat([Buffer.from(await md5(await Pass()+l)),e.subarray(9)]));write(Oc().p().str(t).z(1).end())}async function SASL(){ne=(await j.randomBytes(18)).toString("base64"),Oc().p().str("SCRAM-SHA-256"+Oc.N);const e=Oc.i;write(Oc.inc(4).str("n,,n=*,r="+ne).i32(Oc.i-e-4,e).end())}async function SASLContinue(e){const t=e.toString("utf8",9).split(",").reduce((e,t)=>(e[t[0]]=t.slice(2),e),{}),n=await j.pbkdf2Sync(await Pass(),Buffer.from(t.s,"base64"),parseInt(t.i),32,"sha256"),r=await hmac(n,"Client Key"),s="n=*,r="+ne+",r="+t.r+",s="+t.s+",i="+t.i+",c=biws,r="+t.r;G=(await hmac(await hmac(n,"Server Key"),s)).toString("base64");const o="c=biws,r="+t.r+",p="+xor(r,Buffer.from(await hmac(await sha256(r),s))).toString("base64");write(Oc().p().str(o).end())}function SASLFinal(e){e.toString("utf8",9).split(Oc.N,1)[0].slice(2)!==G&&(errored(ec.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),x.destroy())}function Pass(){return Promise.resolve("function"==typeof e.pass?e.pass():e.pass)}function NoData(){if(N.statement=re.statement,N.statement.columns=[],re.onlyDescribe)return re.resolve(re.statement),write(jc)}function BackendKeyData(e){T.pid=e.readUInt32BE(5),T.secret=e.readUInt32BE(9)}function ErrorResponse(e){re?((re.cursorFn||re.describeFirst)&&write(jc),I=ec.postgres(parseError(e))):errored(ec.postgres(parseError(e)))}function NotificationResponse(e){if(!f)return;let t=9;for(;0!==e[t++];);f(e.toString("utf8",9,t-1),e.toString("utf8",t,e.length-1))}async function PortalSuspended(){try{const e=await Promise.resolve(re.cursorFn(N));Q=0,e===Dl?write(function Close(e=""){return Buffer.concat([Oc().C().str("P").str(e+Oc.N).end(),Oc().S().end()])}(re.portal)):(N=new xc,write(Execute("",re.cursorRows)))}catch(e){write(jc),re.reject(e)}}function CloseComplete(){N.count&&re.cursorFn(N),re.resolve(N)}function CopyInResponse(){Z=new qe.Writable({autoDestroy:!0,write(e,t,n){x.write(Oc().d().raw(e).end(),n)},destroy(e,t){t(e),x.write(Oc().f().str(e+Oc.N).end()),Z=null},final(e){x.write(Oc().c().end()),se=e,Z=null}}),re.resolve(Z)}function CopyOutResponse(){Z=new qe.Readable({read(){x.resume()}}),re.resolve(Z)}function CopyBothResponse(){Z=new qe.Duplex({autoDestroy:!0,read(){x.resume()},write(e,t,n){x.write(Oc().d().raw(e).end(),n)},destroy(e,t){t(e),x.write(Oc().f().str(e+Oc.N).end()),Z=null},final(e){x.write(Oc().c().end()),se=e}}),re.resolve(Z)}function CopyData(e){Z&&(Z.push(e.subarray(5))||x.pause())}function CopyDone(){Z&&Z.push(null),Z=null}function NoticeResponse(e){h?h(parseError(e)):console.log(parseError(e))}function EmptyQueryResponse(){}function FunctionCallResponse(){errored(ec.notSupported("FunctionCallResponse"))}function NegotiateProtocolVersion(){errored(ec.notSupported("NegotiateProtocolVersion"))}function UnknownMessage(e){console.error("Postgres.js : Unknown Message:",e[0])}function UnknownAuth(e,t){console.error("Postgres.js : Unknown Auth:",t)}function Bind(t,n,r="",s=""){let o,i;return Oc().B().str(s+Oc.N).str(r+Oc.N).i16(0).i16(t.length),t.forEach((r,s)=>{if(null===r)return Oc.i32(4294967295);i=n[s],t[s]=r=i in e.serializers?e.serializers[i](r):""+r,o=Oc.i,Oc.inc(4).str(r).i32(Oc.i-o-4,o)}),Oc.i16(0),Oc.end()}function Parse(e,t,n,r=""){return Oc().P().str(r+Oc.N).str(e+Oc.N).i16(t.length),t.forEach((e,t)=>Oc.i32(n[t]||0)),Oc.end()}function Describe(e,t=""){return Oc().D().str(e).str(t+Oc.N).end()}function Execute(e="",t=0){return Buffer.concat([Oc().E().str(e+Oc.N).i32(t).end(),zc])}}function parseError(e){const t={};let n=5;for(let r=5;r<e.length-1;r++)0===e[r]&&(t[Hc[e[n]]]=e.toString("utf8",n+1,r),n=r+1);return t}function md5(e){return j.createHash("md5").update(e).digest("hex")}function hmac(e,t){return j.createHmac("sha256",e).update(t).digest()}function sha256(e){return j.createHash("sha256").update(e).digest()}function xor(e,t){const n=Math.max(e.length,t.length),r=Buffer.allocUnsafe(n);for(let s=0;s<n;s++)r[s]=e[s]^t[s];return r}function timer(e,t){if(!(t="function"==typeof t?t():t))return{cancel:Qc,start:Qc};let n;return{cancel(){n&&(clearTimeout(n),n=null)},start(){n&&clearTimeout(n),n=setTimeout(done,1e3*t,arguments)}};function done(t){e.apply(null,t),n=null}}var Kc,Yc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/connection.js"(){Nt(),Nc(),Ac(),Rc(),Dc(),tc(),Vc(),qc=Connection,Fc=1,jc=Oc().S().end(),zc=Oc().H().end(),Bc=Oc().i32(8).i32(80877103).end(8),Uc=Buffer.concat([Oc().E().str(Oc.N).i32(0).end(),jc]),Wc=Oc().D().str("S").str(Oc.N).end(),Qc=__name(()=>{},"noop"),Gc=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Hc={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"},__name(Connection,"Connection"),__name(parseError,"parseError"),__name(md5,"md5"),__name(hmac,"hmac"),__name(sha256,"sha256"),__name(xor,"xor"),__name(timer,"timer")}});function Subscribe(e,t){const n=new Map,r="postgresjs_"+Math.random().toString(36).slice(2),s={};let o,i,a=!1;const l=subscribe.sql=e({...t,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...t.connection,replication:"database"},onclose:__name(async function(){a||(i=null,s.pid=s.secret=void 0,connected(await init(l,r,t.publications)),n.forEach(e=>e.forEach(({onsubscribe:e})=>e())))},"onclose"),no_subscribe:!0}),u=l.end,d=l.close;return l.end=async()=>(a=!0,i&&await new Promise(e=>(i.once("close",e),i.end())),u()),l.close=async()=>(i&&await new Promise(e=>(i.once("close",e),i.end())),d()),subscribe;async function subscribe(e,a,u=Kc,d=Kc){e=parseEvent(e),o||(o=init(l,r,t.publications));const m={fn:a,onsubscribe:u},p=n.has(e)?n.get(e).add(m):n.set(e,new Set([m])).get(e),g=__name(()=>{p.delete(m),0===p.size&&n.delete(e)},"unsubscribe");return o.then(e=>(connected(e),u(),i&&i.on("error",d),{unsubscribe:g,state:s,sql:l}))}function connected(e){i=e.stream,s.pid=e.state.pid,s.secret=e.state.secret}async function init(e,n,r){if(!r)throw new Error("Missing publication names");const s=await e.unsafe(`CREATE_REPLICATION_SLOT ${n} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[o]=s,i=await e.unsafe(`START_REPLICATION SLOT ${n} LOGICAL ${o.consistent_point} (proto_version '1', publication_names '${r}')`).writable(),a={lsn:Buffer.concat(o.consistent_point.split("/").map(e=>Buffer.from(("00000000"+e).slice(-8),"hex")))};return i.on("data",function data(n){119===n[0]?parse(n.subarray(25),a,e.options.parsers,handle,t.transform):107===n[0]&&n[17]&&(a.lsn=n.subarray(1,9),function pong(){const e=Buffer.alloc(34);e[0]="r".charCodeAt(0),e.fill(a.lsn,1),e.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2e3,0,1))*BigInt(1e3),25),i.write(e)}())}),i.on("error",function error(e){console.error("Unexpected error during logical streaming - reconnecting",e)}),i.on("close",e.close),{stream:i,state:s.state};function handle(e,t){const n=t.relation.schema+"."+t.relation.table;call("*",e,t),call("*:"+n,e,t),t.relation.keys.length&&call("*:"+n+"="+t.relation.keys.map(t=>e[t.name]),e,t),call(t.command,e,t),call(t.command+":"+n,e,t),t.relation.keys.length&&call(t.command+":"+n+"="+t.relation.keys.map(t=>e[t.name]),e,t)}}function call(e,t,r){n.has(e)&&n.get(e).forEach(({fn:n})=>n(t,r,e))}}function Time(e){return new Date(Date.UTC(2e3,0,1)+Number(e/BigInt(1e3)))}function parse(e,t,n,r,s){const o=__name((e,[t,n])=>(e[t.charCodeAt(0)]=n,e),"char");Object.entries({R:__name(e=>{let r=1;const o=t[e.readUInt32BE(r)]={schema:e.toString("utf8",r+=4,r=e.indexOf(0,r))||"pg_catalog",table:e.toString("utf8",r+1,r=e.indexOf(0,r+1)),columns:Array(e.readUInt16BE(r+=2)),keys:[]};r+=2;let i,a=0;for(;r<e.length;)i=o.columns[a++]={key:e[r++],name:s.column.from?s.column.from(e.toString("utf8",r,r=e.indexOf(0,r))):e.toString("utf8",r,r=e.indexOf(0,r)),type:e.readUInt32BE(r+=1),parser:n[e.readUInt32BE(r)],atttypmod:e.readUInt32BE(r+=4)},i.key&&o.keys.push(i),r+=4},"R"),Y:__name(()=>{},"Y"),O:__name(()=>{},"O"),B:__name(e=>{t.date=Time(e.readBigInt64BE(9)),t.lsn=e.subarray(1,9)},"B"),I:__name(e=>{let n=1;const o=t[e.readUInt32BE(n)],{row:i}=tuples(e,o.columns,n+=7,s);r(i,{command:"insert",relation:o})},"I"),D:__name(e=>{let n=1;const o=t[e.readUInt32BE(n)];n+=4;const i=75===e[n];r(i||79===e[n]?tuples(e,o.columns,n+=3,s).row:null,{command:"delete",relation:o,key:i})},"D"),U:__name(e=>{let n=1;const o=t[e.readUInt32BE(n)];n+=4;const i=75===e[n],a=i||79===e[n]?tuples(e,o.columns,n+=3,s):null;a&&(n=a.i);const{row:l}=tuples(e,o.columns,n+3,s);r(l,{command:"update",relation:o,key:i,old:a&&a.row})},"U"),T:__name(()=>{},"T"),C:__name(()=>{},"C")}).reduce(o,{})[e[0]](e)}function tuples(e,t,n,r){let s,o,i;const a=r.raw?new Array(t.length):{};for(let l=0;l<t.length;l++)s=e[n++],o=t[l],i=110===s?null:117===s?void 0:void 0===o.parser?e.toString("utf8",n+4,n+=4+e.readUInt32BE(n)):!0===o.parser.array?o.parser(e.toString("utf8",n+5,n+=4+e.readUInt32BE(n))):o.parser(e.toString("utf8",n+4,n+=4+e.readUInt32BE(n))),r.raw?a[l]=!0===r.raw?i:r.value.from?r.value.from(i,o):i:a[o.name]=r.value.from?r.value.from(i,o):i;return{i:n,row:r.row.from?r.row.from(a):a}}function parseEvent(e){const t=e.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!t)throw new Error("Malformed subscribe pattern: "+e);const[,n,r,s]=t;return(n||"*")+(r?":"+(-1===r.indexOf(".")?"public."+r:r):"")+(s?"="+s:"")}var Jc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/subscribe.js"(){Nt(),Kc=__name(()=>{},"noop"),__name(Subscribe,"Subscribe"),__name(Time,"Time"),__name(parse,"parse"),__name(tuples,"tuples"),__name(parseEvent,"parseEvent")}});function largeObject(e,t,n=393216){return new Promise(async(r,s)=>{await e.begin(async e=>{let s;!t&&([{oid:t}]=await(e`select lo_creat(-1) as oid`));const[{fd:o}]=await(e`select lo_open(${t}, ${n}) as fd`),i={writable:async function writable({highWaterMark:e=16384,start:t=0}={}){return t&&await i.seek(t),new qe.Writable({highWaterMark:e,write(e,t,n){i.write(e).then(()=>n(),n)}})},readable:async function readable({highWaterMark:e=16384,start:t=0,end:n=1/0}={}){let r=n-t;return t&&await i.seek(t),new qe.Readable({highWaterMark:e,async read(e){const t=e>r?e-r:e;r-=e;const[{data:n}]=await i.read(t);this.push(n),n.length<e&&this.push(null)}})},close:__name(()=>e`select lo_close(${o})`.then(s),"close"),tell:__name(()=>e`select lo_tell64(${o})`,"tell"),read:__name(t=>e`select loread(${o}, ${t}) as data`,"read"),write:__name(t=>e`select lowrite(${o}, ${t})`,"write"),truncate:__name(t=>e`select lo_truncate64(${o}, ${t})`,"truncate"),seek:__name((t,n=0)=>e`select lo_lseek64(${o}, ${t}, ${n})`,"seek"),size:__name(()=>e`
2
+ import*as e from"path";import t,{join as n,dirname as r,relative as s,resolve as o,extname as i,basename as a,isAbsolute as l}from"path";import{fileURLToPath as u,URL as d,pathToFileURL as m}from"url";import p,{z as g}from"zod";import*as h from"os";import f,{tmpdir as y}from"os";import*as w from"fs";import S,{readFileSync as b,existsSync as E,mkdirSync as C,writeFileSync as v,readdirSync as T,statSync as k,createReadStream as _,promises as P,constants as A}from"fs";import{exec as x,execSync as I,spawn as N,execFile as R}from"child_process";import*as $ from"fs/promises";import L,{writeFile as M,readFile as O,unlink as D,mkdir as q}from"fs/promises";import*as F from"crypto";import j,{randomUUID as z}from"crypto";import B,{memo as U,useState as W,useRef as Q,useEffect as G,useMemo as H,useCallback as V}from"react";import{Box as K,Text as Y,Static as J,useStdout as X,useInput as Z,render as ee,useApp as te,Newline as ne}from"ink";import re from"picocolors";import se from"strip-ansi";import oe from"sharp";import ie from"open";import ae from"@opentelemetry/sdk-node";import le from"@opentelemetry/exporter-trace-otlp-http";import ce from"@opentelemetry/resources";import ue from"@opentelemetry/semantic-conventions";import de from"@opentelemetry/sdk-trace-node";import{trace as me,SpanStatusCode as pe,context as ge}from"@opentelemetry/api";import{v4 as he}from"uuid";import*as fe from"http";import*as ye from"net";import we from"net";import Se from"ink-spinner";import be from"figures";import*as Ee from"@clack/prompts";import{cancel as Ce,select as ve,isCancel as Te,note as ke,confirm as _e,password as Pe}from"@clack/prompts";import{Command as Ae,Option as xe}from"commander";import Ie from"ora";import Ne from"@sindresorhus/slugify";import{EventEmitter as Re}from"events";import $e from"gray-matter";import{minimatch as Le}from"minimatch";import{glob as Me}from"glob";import{quote as Oe}from"shell-quote";import De from"tls";import qe from"stream";import{performance as Fe}from"perf_hooks";import{MessageStream as je}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import"dotenv/config";import ze from"dedent";import Be from"chalk";import Ue from"log-symbols";import We from"readline/promises";import Qe from"@crosscopy/clipboard";import*as Ge from"readline";import He from"strip-json-comments";import{promisify as Ve}from"util";import Ke from"ink-select-input";import*as Ye from"diff";import{Marked as Je}from"marked";import Xe from"marked-terminal";import Ze from"ink-gradient";import et from"open-editor";import tt from"semver";import nt from"ignore";import rt from"is-unicode-supported";import{wrapAnsi as st}from"fast-wrap-ansi";import ot from"terminal-link";import*as it from"process";var at,lt,ct,ut,dt,mt,pt,gt,ht,ft,yt,wt,St,bt,Et,Ct,vt,Tt,kt,_t,Pt,At,xt=Object.defineProperty,It=Object.getOwnPropertyNames,__name=(e,t)=>xt(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[It(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)xt(e,n,{get:t[n],enumerable:!0})},Nt=__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"(){}}),Rt=__esm({"../shared/src/constants/tracing.ts"(){Nt(),at="command_code_cli_tracing"}}),$t=__esm({"src/utils/telemetry/constants.ts"(){Nt(),Rt(),lt="https://api.axiom.co/v1/traces",ct="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",ut="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",dt="xaat-add69148-8f73-4833-921d-bc843285c95f",mt="command-code-cli",pt=["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"],gt=["content","body"],ht=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 Lt,Mt,Ot=__esm({"../shared/src/constants.ts"(){Nt(),yt="--xco",wt={INTERNAL_TEAM_FLAG_HEADER:`x-${(ft="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage",CLI_ENVIRONMENT:"x-cli-environment"},St={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"}}}},bt={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(bt.ALPHA.TASTE),Object.values(bt.BETA.TASTE_PACKAGES),St.ALPHA.GENERATE,St.ALPHA.AGENT.GENERATE,St.ALPHA.WHOAMI,St.ALPHA.NAMESPACES,St.ALPHA.SHARE.CREATE,St.ALPHA.SHARE.DELETE,St.ALPHA.SHARE.APPEND,St.ALPHA.DEVREL_THREAD.CREATE,St.ALPHA.DEVREL_THREAD.DELETE,St.ALPHA.DEVREL_THREAD.UPDATE,St.ALPHA.TASTE.LEARN,St.ALPHA.TASTE.DELETE,St.ALPHA.TASTE.GET,St.ALPHA.TASTE.UPDATE,Object.values(St.BETA.TASTE.PACKAGES),St.INTERNAL.ADMIN.USERS,St.INTERNAL.ADMIN.ORGS,St.INTERNAL.ADMIN.ENTITY_TYPE,St.INTERNAL.USER.AVATAR,St.INTERNAL.USER.SETTINGS,St.INTERNAL.API_KEYS.LIST,St.INTERNAL.API_KEYS.CREATE,St.INTERNAL.API_KEYS.DELETE,St.INTERNAL.USAGE.LIST,St.INTERNAL.USAGE.SUMMARY,St.INTERNAL.ADMIN.GRANT_CREDITS,St.INTERNAL.ADMIN.GRANT_ORG_CREDITS,St.INTERNAL.BILLING.CREDITS.GET,St.INTERNAL.BILLING.CUSTOMERS.GET,St.INTERNAL.BILLING.CUSTOMERS.UPSERT,St.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,St.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,St.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,St.INTERNAL.BILLING.CUSTOMERS.INVOICES,St.INTERNAL.BILLING.SUBSCRIPTIONS.GET,St.INTERNAL.ORGS.LIST,St.INTERNAL.ORGS.GET,St.INTERNAL.ORGS.CREATE,St.INTERNAL.ORGS.UPDATE,St.INTERNAL.ORGS.DELETE,St.INTERNAL.ORGS.MEMBERS.LIST,St.INTERNAL.ORGS.MEMBERS.ADD,St.INTERNAL.ORGS.MEMBERS.UPDATE,St.INTERNAL.ORGS.MEMBERS.REMOVE,St.INTERNAL.ORGS.INVITATIONS.LIST,St.INTERNAL.ORGS.INVITATIONS.SEND,St.INTERNAL.ORGS.INVITATIONS.ACCEPT,St.INTERNAL.ORGS.INVITATIONS.CANCEL,St.INTERNAL.TASTE.PACKAGES.LIST,Object.values(bt.INTERNAL.ORGS),Object.values(bt.INTERNAL.USER),Object.values(bt.INTERNAL.TASTE.PACKAGES),Et={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(Et.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl"),Ct={ANTHROPIC:"anthropic"},vt="anthropic:claude-haiku-4-5-20251001",p.enum(["owner","admin","member"]),Tt={LEARN_TASTE:"learn-taste",TASTE:"taste",TERMINAL_SETUP:"terminal-setup"},(kt={SONNET_4_6:{id:"claude-sonnet-4-6",label:"Sonnet 4.6 (default)",name:"Sonnet 4.6",description:"best combo of speed & intelligence (recommended)"},OPUS_4_6:{id:"claude-opus-4-6",label:"Opus 4.6",name:"Opus 4.6",description:"most capable for complex work"},SONNET_4_5:{id:"claude-sonnet-4-5-20250929",label:"Sonnet 4.5",name:"Sonnet 4.5",description:"previous generation, balanced speed & quality"},OPUS_4_5:{id:"claude-opus-4-5-20251101",label:"Opus 4.5",name:"Opus 4.5",description:"previous generation, highly capable"},HAIKU_4_5:{id:"claude-haiku-4-5-20251001",label:"Haiku 4.5",name:"Haiku 4.5",description:"fastest & most compact, great for quick tasks"}}).SONNET_4_6.id,kt.SONNET_4_5.id,kt.OPUS_4_5.id,kt.OPUS_4_6.id,kt.HAIKU_4_5.id,_t=kt.SONNET_4_6.id,new Set([].map(e=>e.toLowerCase())),Pt=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],At={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}}}),Dt=__esm({"src/utils/env.ts"(){Nt(),Lt=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),Mt=__name(()=>{const e=Lt();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag")}});function getAuthDir(){return t.join(f.homedir(),".commandcode")}function getAuthFile(e){const n=e??Lt(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??Lt(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var qt,Ft,jt=__esm({"src/utils/auth/auth-paths.ts"(){Nt(),Ot(),Dt(),__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 S.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(;!S.existsSync(n);){const s=t.dirname(n);if(s===n)return t.normalize(e);r.unshift(t.basename(n)),n=s}return t.join(getCanonicalPath(n),...r)}catch{return t.normalize(e)}}function formatDirectoryForDisplay(e){const n=canonicalizeForLookup(t.normalize(e)),r=getCanonicalPath(process.cwd()),s=f.homedir();if(isPathInDirectory(n,r)){const e=t.relative(r,n);return e?`./${e}`:"."}if(s&&isPathInDirectory(n,s)){const e=t.relative(s,n);return e?`~/${e}`:"~"}return n}function isPathInDirectory(e,n){const r=normalizePathForComparison(e),s=normalizePathForComparison(n),o=s.endsWith(t.sep)?s:s+t.sep;return r===s||r.startsWith(o)}function findSensitiveDirectoryConflict(e){const n=[t.normalize(e),getCanonicalPath(e)];for(const e of qt){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(f.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,s=formatDirectoryForDisplay(n);return{status:"skipped",inputPath:t,absolutePath:n,displayPath:s,code:r,message:"ALREADY_IN_WORKSPACE"===r?`${s} is already accessible from the current workspace`:`${s} 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,s;try{r=S.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{S.accessSync(n,S.constants.R_OK),s=getCanonicalPath(n)}catch{return createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}const o=findSensitiveDirectoryConflict(s);if(o)return createErrorResult({inputPath:e,code:"SENSITIVE_DIRECTORY",message:`Cannot add ${formatDirectoryForDisplay(s)} because it overlaps sensitive path ${formatDirectoryForDisplay(o)}`});const i=getCanonicalPath(process.cwd());return isPathInDirectory(s,i)?createSkippedResult({inputPath:e,absolutePath:s,code:"ALREADY_IN_WORKSPACE"}):Ft.some(e=>isPathInDirectory(s,e)||isPathInDirectory(e,s))?createSkippedResult({inputPath:e,absolutePath:s,code:"ALREADY_ADDED"}):(Ft.push(s),{status:"added",inputPath:e,absolutePath:s,displayPath:formatDirectoryForDisplay(s)})}function getAdditionalDirectories(){return[...Ft]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Ft.findIndex(e=>areSamePath(t,e));return-1!==n&&(Ft.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Ft.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t)}var zt=__esm({"src/utils/additional-dirs.ts"(){Nt(),qt=new Set(["/etc","/root","/proc","/sys","/dev",t.join(f.homedir(),".ssh"),t.join(f.homedir(),".gnupg"),t.join(f.homedir(),".aws")]),Ft=[],__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`${f.platform()}-${f.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 S.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 I("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return I("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){try{const e=I("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=I("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,s=t.filter(e=>e.startsWith(" D")).length,o=t.filter(e=>e.startsWith("??")).length,i=[];return n>0&&i.push(`M ${n}`),r>0&&i.push(`A ${r}`),s>0&&i.push(`D ${s}`),o>0&&i.push(`?? ${o}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=I("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 Bt,Ut,Wt,Qt,Gt,Ht,Vt,Kt,Yt,Jt,Xt,Zt,en=__esm({"src/utils/environment.ts"(){Nt(),zt(),__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")}});function isWordLeftSequence(e){return!!Bt.has(e)||!!Jt.test(e)}function isWordRightSequence(e){return!!Ut.has(e)||!!Xt.test(e)}function isHomeSequence(e){return Wt.has(e)}function isEndSequence(e){return Qt.has(e)}function isForwardDeleteSequence(e){return Gt.has(e)}function isDeleteWordSequence(e){return Ht.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===Vt.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===Vt.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===Vt.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===Vt.CTRL_U}function isAltP(e){return Yt.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}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)||Zt.includes(t))}var tn,nn,rn,sn,on,an,ln=__esm({"src/utils/keyboard-sequences.ts"(){Nt(),Bt=new Set(["","b","","",""]),Ut=new Set(["","f","","",""]),Wt=new Set(["","[1~","[7~","OH"]),Qt=new Set(["","[4~","[8~","OF"]),Gt=new Set(["[3~"]),Ht=new Set(["",""]),Vt={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},Kt={ALT_P:112,ALT_P_NO_META:960},Yt=new Set([String.fromCharCode(27,Kt.ALT_P),String.fromCharCode(Kt.ALT_P_NO_META),""]),Jt=/^\x1b\[1;[359]D$/,Xt=/^\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"),Zt=["\n","\r","","[27;2;13~","[27;2;13~","[13;2u"],__name(isNewlineShortcutKey,"isNewlineShortcutKey")}}),cn=__esm({"src/auth/index.ts"(){Nt(),Ot(),Dt(),(e=>{e.OAuth=g.object({type:g.literal("oauth"),refresh:g.string(),access:g.string(),expires:g.number()}),e.ApiKey=g.object({type:g.literal("api"),key:g.string()}),e.Info=g.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const n=__name(()=>t.join(f.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=Lt(),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 L.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const s=n(),o=r();await L.mkdir(s,{recursive:!0});let i={};try{const e=await L.readFile(o,"utf-8");i=JSON.parse(e)}catch{}i[e]=t,await L.writeFile(o,JSON.stringify(i,null,2)),await L.chmod(o,384)}async function remove(e){const t=r();try{const n=await L.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await L.unlink(t):(await L.writeFile(t,JSON.stringify(r,null,2)),await L.chmod(t,384))}catch{}}async function list2(){try{const e=await L.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")})(tn||(tn={}))}}),un=__esm({"src/utils/constants.ts"(){Nt(),Ot(),nn="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing",rn='OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.',sn=">"}}),dn=__esm({"src/auth/anthropic.ts"(){Nt(),cn(),un(),Vr(),(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 j.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return j.createHash("sha256").update(e).digest("base64url")}function generateState(){return j.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),s=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:s}).toString()}`,verifier:e,state:s}}async function exchangeCodeForTokens2(e,s,o){const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:s,state:o})});if(!i.ok){const e=await i.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:Br.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const a=await i.json();await tn.set("anthropic",{type:"oauth",refresh:a.refresh_token,access:a.access_token,expires:Date.now()+1e3*a.expires_in})}async function refreshAccessToken2(){const e=await tn.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:Br.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await tn.remove("anthropic");const s=await r.json();return await tn.set("anthropic",{type:"oauth",refresh:s.refresh_token,access:s.access_token,expires:Date.now()+1e3*s.expires_in}),s.access_token}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:Br.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await tn.remove("anthropic")}}}async function getValidAccessToken2(){const e=await tn.get("anthropic");if(e)return"api"===e.type?e.key:"oauth"===e.type?await refreshAccessToken2():void 0}__name(generateCodeVerifier,"generateCodeVerifier"),__name(generateCodeChallenge,"generateCodeChallenge"),__name(generateState,"generateState"),e.createAuthorizationUrl=createAuthorizationUrl,__name(createAuthorizationUrl,"createAuthorizationUrl"),e.exchangeCodeForTokens=exchangeCodeForTokens2,__name(exchangeCodeForTokens2,"exchangeCodeForTokens"),e.refreshAccessToken=refreshAccessToken2,__name(refreshAccessToken2,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken2,__name(getValidAccessToken2,"getValidAccessToken")})(on||(on={}))}});function isWordBoundary(e){return!e||0===e.length||an.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,s=n-1,o=findLineStart(e,s),i=s-o;return o+Math.min(r,i)}function moveCursorDown(e,t){if(!e)return 0;const n=findLineStart(e,t),r=findLineEnd(e,t);if(r===e.length)return t;const s=t-n,o=r+1,i=findLineEnd(e,o)-o;return o+Math.min(s,i)}function insertTextAt(e,t,n){const r=e||"",s=clampCursor(t,r.length);return{text:r.slice(0,s)+n+r.slice(s),cursor:s+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 mn,pn,gn=__esm({"src/utils/text-navigation.ts"(){Nt(),an=/\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 stripBracketedPaste(e){return e.includes(mn)||e.includes(pn)?e.replaceAll(mn,"").replaceAll(pn,""):null}function processBracketedPasteInput({input:e,value:t,cursor:n}){const r=stripBracketedPaste(e);if(null===r)return{value:t,cursor:n,handled:!1};if(0===r.length)return{value:t,cursor:n,handled:!0};const s=insertTextAt(t,n,r);return{value:s.text,cursor:s.cursor,handled:!0}}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 s=insertTextAt(e,t,r);return{value:s.text,cursor:s.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,s){const o=t;return o.meta&&t.leftArrow?processLineStart(n,r):o.meta&&t.rightArrow?processLineEnd(n,r):o.meta&&"b"===e?processWordLeft(n,r):o.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,s):t.rightArrow?processCursorRight(n,r,s):t.upArrow?processCursorUp(n,r,s):t.downArrow?processCursorDown(n,r,s):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!o.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}var hn,fn,yn,wn=__esm({"src/tui/text/input-handlers.ts"(){Nt(),gn(),ln(),mn="[200~",pn="[201~",__name(stripBracketedPaste,"stripBracketedPaste"),__name(processBracketedPasteInput,"processBracketedPasteInput"),__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(){hn||(hn=!0,fn=[],yn=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&fn.push(t)},"earlyInputHandler"),process.stdin.on("data",yn))}function stopEarlyInputCapture(){hn&&yn&&(process.stdin.off("data",yn),yn=null,hn=!1)}function consumeBufferedInput(){const e=fn.join("");return fn=[],e}function hasBufferedInput(){return fn.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("")||e.startsWith(""))}var Sn=__esm({"src/utils/early-input-buffer.ts"(){Nt(),hn=!1,fn=[],yn=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,s]=W((e||"").length),o=Q(r),i=Q(e);G(()=>{o.current=r},[r]),G(()=>{const a=i.current;if(i.current=e,e===a)return;if(!t)return;if(!n)return;const l=(e||"").length;r>l&&(s(l),o.current=l)},[e,t,n,r]);const a=V(e=>{s(e),o.current=e},[]);return{cursor:r,setCursor:a,cursorRef:o}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:s,stripBracketedPaste:o=!1}){const i=Q(!1);G(()=>{if(!e)return;const a=process.stdin,l=__name(e=>{s(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>s(!1),0)},"emitStdinResult"),u=__name(e=>{const r=e.toString();if(o){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current});if(e.handled)return void l(e)}const s=processRawInput(r,t.current,n.current);s.handled&&l(s)},"handleRawInput");if(a.on("data",u),!i.current&&hasBufferedInput()){i.current=!0;const e=consumeBufferedInput();e&&u(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",u)}},[e,t,n,r,s,o])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:s,onUpdate:o,onSubmit:i}){Z((e,a)=>{if(s())return;if(isIgnoredKey(e,a))return;if(a.return)return void i?.(n.current);const l=processInkInput(e,a,n.current,r.current,t);if(!l.handled)return;const u=clampCursor(l.cursor,l.value.length);o(l.value,u)},{isActive:e})}function useSyncedRef(e){const t=Q(e);return t.current=e,t}var bn=__esm({"src/tui/text/hooks.ts"(){Nt(),gn(),wn(),Sn(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef")}});function renderPlaceholder(e,t){return t?0===e.length?re.inverse(" "):re.inverse(e[0])+re.gray(e.slice(1)):re.gray(e)}function renderValue(e,t,n){if(!n)return e;if(0===e.length)return re.inverse(" ");let r="";for(let n=0;n<e.length;n++)n===t?"\n"===e[n]?r+=re.inverse(" ")+"\n":r+=re.inverse(e[n]):r+=e[n];return t===e.length&&(r+=re.inverse(" ")),r}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),s=t-n,o=t;if(se(e).length<=o)return e;const i=e.split(/(\s+)/);let a="",l=0,u=!0;for(const e of i){const t=se(e).length;if(l+t>(u?o:s)&&l>0&&(a+="\n"+r,l=n,u=!1),a+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=se(t).length,u=!0}}return a}function getDisplayValue(e,t,n,r,s){const o=r&&s;return t&&0===e.length?renderPlaceholder(t,o):renderValue(e,n,o)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}var En,Cn=__esm({"src/tui/text/render-utils.ts"(){Nt(),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue")}});function createStdinUpdateHandler(e,t,n){return(r,s)=>{e(s),r!==t.current&&(n.current(r),t.current=r)}}function createInkUpdateHandler(e,t,n){return(r,s)=>{e(s),r!==t.current&&(n.current(r),t.current=r)}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:s=!0,onChange:o,onSubmit:i,onCursorChange:a,prefix:l="",prefixColor:u,stripBracketedPaste:d=!1}){const m=Q(!1),p=useSyncedRef(e),g=useSyncedRef(o),{cursor:h,setCursor:f,cursorRef:y}=useCursorState({value:e,focus:n,showCursor:s});B.useEffect(()=>{a?.(h)},[h,a]);const w=V(createStdinUpdateHandler(f,p,g),[f,p,g]),S=V(createInkUpdateHandler(f,p,g),[f,p,g]),b=V(e=>{m.current=e},[]),E=V(()=>m.current,[]);useRawStdinHandler({focus:n,valueRef:p,cursorRef:y,onUpdate:w,setHandled:b,stripBracketedPaste:d}),useInkInputHandler({focus:n,showCursor:s,valueRef:p,cursorRef:y,isHandledByStdin:E,onUpdate:S,onSubmit:i});const{stdout:C}=X(),v=C?.columns??80,T=getMaskedValue(e,r),k=u?En[u]:void 0,_=wrapWithIndent((l?k?k(l):l:"")+getDisplayValue(T,t,h,s,n),v,l?.length??0);return B.createElement(Y,{wrap:"wrap"},_)}var vn=__esm({"src/tui/text/text-input.tsx"(){Nt(),bn(),Cn(),gn(),En={white:re.white,green:re.green,red:re.red,blue:re.blue,yellow:re.yellow,cyan:re.cyan,magenta:re.magenta,gray:re.gray,grey:re.gray},__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,s=oe(n),o=await s.metadata();if(!o.width||!o.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const i=1200;let a,l,{width:u,height:d}=o;(u>i||d>i)&&(u>d?(d=Math.round(d*i/u),u=i):(u=Math.round(u*i/d),d=i)),t.includes("png")&&o.hasAlpha?(a=await s.resize(u,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),l="image/png"):(a=await s.resize(u,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),l="image/jpeg");const m=a.length;return{compressedBase64:a.toString("base64"),mediaType:l,originalSizeBytes:r,compressedSizeBytes:m,compressionRatio:r/m}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}var Tn,kn=__esm({"src/utils/image-compression.ts"(){Nt(),__name(compressImageForSharing,"compressImageForSharing")}});async function detectDroppedImageFile(e){try{if(!e||0===e.trim().length)return null;let t=e.trim();if((t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),t=t.replace(/\\(.)/g,"$1"),t.includes("\n")||t.includes("\r"))return null;const n=i(t).toLowerCase(),r=Tn[n];if(!r)return null;const s=o(t);if(!E(s))return null;const a=b(s).toString("base64");if(!a||0===a.length)return null;if(a.length>32e6)return null;const l=await compressImageForSharing(a,r);return l?{data:l.compressedBase64,mediaType:l.mediaType}:null}catch(e){return null}}async function detectClipboardImage(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasImage())return null;let t=null;try{if(t=await e.default.getImageBase64(),!t){const n=e.default.getImageBase64();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}if(!t||0===t.length)return null;if(t.length>32e6)return console.log("Image too large:",t.length,"bytes"),null;try{const e=await compressImageForSharing(t,"image/png");return e?{data:e.compressedBase64,mediaType:e.mediaType}:(console.log("Failed to compress clipboard image"),null)}catch(e){return console.log("Failed to process clipboard image:",e),null}}catch(e){return null}}async function detectClipboardText(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasText())return null;let t=null;try{if(t=await e.default.getText(),!t){const n=e.default.getText();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}return t&&0!==t.length?t:null}catch(e){return null}}var _n=__esm({"src/utils/clipboard-image.ts"(){Nt(),kn(),Tn={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/png",".tiff":"image/png"},__name(detectDroppedImageFile,"detectDroppedImageFile"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText")}});function stripBracketedPasteMarkers(e){return e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"").replace(/\x1B\[201~/g,"").replace(/\[201~/g,"")}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};const r=stripBracketedPasteMarkers(e);let s,o;if(t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){s=e.slice(0,t.index);const r=e.slice(t.index+t[0].length);if(n){const e=r.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(o=r.slice(0,e.index))}else o=r}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:r,textBeforePaste:s,pastedContent:o}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}var Pn,An,xn,In,Nn=__esm({"src/utils/bracketed-paste.ts"(){Nt(),__name(stripBracketedPasteMarkers,"stripBracketedPasteMarkers"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode")}});function getIcon(e){if(xn[e])return xn[e];const t=e.split(":")[0];return xn[t]?xn[t]:xn.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(!In){In=!0;try{w.mkdirSync(Pn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${An}\n════════════════════════════════════════════════════════════════\n\n`;w.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:s}=parseMessage(e);let o;if(r){o=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${s}`}else o=`${n} ${xn.default} ${e}`;if(t){o+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}o+="\n",w.appendFileSync(An,o,"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`;w.appendFileSync(An,t,"utf-8")}catch{}}}var Rn,$n=__esm({"src/utils/dlog.ts"(){Nt(),Pn=e.join(h.homedir(),".commandcode","logs"),An=e.join(Pn,"command.log"),xn={Startup:">",CLI:"$",Config:"#",Auth:"@",Onboarding:"*",LearningAgent:"&",Import:"<",API:"~",Sessions:"+",Observer:"!",Flow:"^",Handler:">",Helper:"-",Codex:"+",UI:"|",Hook:"%",ObserverAPI:"~",ContextEngine:"~",Updater:"^",MCP:"&",default:"-"},__name(getIcon,"getIcon"),__name(formatTime,"formatTime"),__name(parseMessage,"parseMessage"),In=!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 $.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();w.writeFileSync(t,JSON.stringify(e,null,2)),w.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!==Rn)return Rn;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),Rn=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),Rn=!0,!0;const e=await loadUserConfig();return(Rn=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),Rn}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error(rn)}function getConfiguredModel(){try{const e=getConfigFile();return(parseJSON(w.readFileSync(e,"utf-8"))||{}).model??_t}catch{return _t}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}var Ln,Mn,On,Dn,qn,Fn,jn,zn,Bn,Un,Wn,Qn,Gn,Hn,Vn,Kn,Yn,Jn,Xn,Zn,er,tr,nr=__esm({"src/utils/user-config.ts"(){Nt(),Ot(),jt(),un(),$n(),ir(),ar(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),Rn=null,__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel")}}),rr=__esm({"src/tui/colors.ts"(){Nt(),Ln={CYAN:"#7AD4D6",GREEN:"#2EBD8E",GRAY:"#636D83",WHITE:"#E5E5E5",YELLOW:"#F5B731",RED:"#E84057",BLUE:"#5945B1",MAGENTA:"#F2608A",DIM:"#636D83"},Mn="#E4CCFF",On={BADGE_BG:"#08575B",BADGE_FG:"#f4f4f4",TEXT:"#02888E"},Dn="#E4CCFF",qn="#F5B731",Fn={REMOVED_BG:"#5C0112",ADDED_BG:"#04473A",REMOVED_TEXT:"#D95A6A",ADDED_TEXT:"#4CC88E",REMOVED_HIGHLIGHT_BG:"#7D2233",ADDED_HIGHLIGHT_BG:"#2E6B4A",LINE_NUM:"#636D83"},jn={BG:"#5945B1",FG:"#f4f4f4"},zn={BG:"#6943FF",FG:"#f4f4f4"},Bn={SUCCESS:"#35AD68",ERROR:"#E84057",WARNING:"#F5B731",IN_PROGRESS:"#E4CCFF"},Un="#B1BAF9",Wn="#636D83",Qn={BG:"#2D2B55",POINTER:"#A599E9"},Gn="#F5B731",Hn="#8367F4",Vn={OPEN:"#F5B731",MERGED:"#A78BFA"},Kn="#F49D2A",Yn={CODE:"#B1BAF9",HEADING:"#A599E9"},Jn=["#A599E9","#E4CCFF","#ABA5CE","#CCC7E1","#FFFFFF","#EADAFF","#ABA5CE","#E4CCFF","#A599E9"],Xn="#6E61A3",Zn={START:"#7AD4D6",END:"#5945B1"}}}),sr=__esm({"src/tui/anthropic-auth.tsx"(){Nt(),vn(),dn(),un(),_n(),Nn(),nr(),rr(),er=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,s]=W(""),[o,i]=W(null),[a,l]=W(!1),[u,d]=W(null),[m,p]=W(!0),[g,h]=W(!1),[f,y]=W(!1);G(()=>{const{url:e,verifier:t,state:n}=on.createAuthorizationUrl();i({url:e,verifier:t,state:n})},[]);const w=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||f){if(!f||t.isPasteEnd){if(f&&t.isPasteEnd){y(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void s(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();s(e)}return}s(e)}}else if(y(!0),t.isPasteEnd){y(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void s(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();s(e)}return}},[f]);Z((e,n)=>{if(n.escape&&t(),m&&!g)if(n.return||"y"===e||"Y"===e){if(!o)return;ie(o.url).then(()=>{h(!0),p(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${o.url}`),h(!0),p(!1)})}else"n"!==e&&"N"!==e||t()});const S=__name(async()=>{if(r.trim()&&o&&!a){l(!0),d(null);try{const t=r.split("#")[0].trim();await on.exchangeCodeForTokens(t,o.verifier,o.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),l(!1),n&&n(t)}}},"handleSubmit");return m&&!g?B.createElement(K,{flexDirection:"column"},B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,color:Ln.CYAN},"Anthropic Authentication")),B.createElement(K,{marginBottom:1},B.createElement(Y,null,"Open the Anthropic auth page?",B.createElement(Y,{dimColor:!0}," (Y/n)")))):B.createElement(K,{flexDirection:"column"},B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,color:Ln.CYAN},"Anthropic Authentication")),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"After authorizing, copy the code and paste it below:")),u&&B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.RED},"Error: ",u)),B.createElement(K,null,B.createElement(Y,null,"Authorization code: "),B.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:w,onSubmit:S,placeholder:"Paste code here..."})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function getProviderDisplayName(e){if(!e)return"None";const t=tr[e];return t?.displayName||e}function getProviderConfig(e){return tr[e]}function isInternalTeamFlagPresent(){return process.argv.includes(ft)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(yt)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(w.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(tr).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var ir=__esm({"src/utils/provider-config.ts"(){Nt(),Ot(),dn(),sr(),jt(),ar(),tr={"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:er,checkAuth:__name(async()=>!!await on.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(yt)}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 L.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,s=n.forceOAuth||!1,o=isInternalTeamFlagPresent();return isInternalTeamDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):o||s?(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||!isCtrlKey({inputChar:t,key:e,letter:"o",ctrlCode:15}))}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 ar=__esm({"src/utils/utils.ts"(){Nt(),Ot(),jt(),en(),ln(),ir(),nr(),__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=S.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var lr=__esm({"src/utils/is-local-dev.ts"(){Nt(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":Lt()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return ut;case"local":return dt;default:return ct}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(w.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var cr=__esm({"src/utils/telemetry/config.ts"(){Nt(),jt(),ar(),Dt(),lr(),$t(),$t(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}}),ur={};function getPackageJson(){const e=import.meta.url,t=u(e),s=r(t);return JSON.parse(b(n(s,"./../package.json"),"utf8"))}__export(ur,{getPackageJson:()=>getPackageJson});var dr,mr,pr,gr,hr,fr,yr=__esm({"src/utils/package.ts"(){Nt(),__name(getPackageJson,"getPackageJson")}});function createAxiomExporter(){return new mr({url:lt,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":at}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return pr({[gr]:mt,[hr]: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 dr({resource:t,spanProcessors:[new fr(e)],autoDetectResources:!1})}var wr,Sr,br,Er,Cr,vr=__esm({"src/utils/telemetry/sdk-factory.ts"(){Nt(),$t(),cr(),yr(),({NodeSDK:dr}=ae),({OTLPTraceExporter:mr}=le),({resourceFromAttributes:pr}=ce),({ATTR_SERVICE_NAME:gr,ATTR_SERVICE_VERSION:hr}=ue),({SimpleSpanProcessor:fr}=de),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function generateSessionId(){return`sess_${he().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:s}=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":s,"session.platform":`${h.platform()}-${h.arch()}`,"session.node_version":process.version}}function startSession(){Cr={},Sr=null,br=null,wr=generateSessionId(),Er=Date.now();try{const e=me.getTracer(mt),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),s=buildSessionAttributes({sessionId:wr,projectPath:n,gitBranch:r,cliVersion:t});Sr=e.startSpan("session:cli",{attributes:s}),br=Sr.spanContext(),Sr.end()}catch{Sr=null,br=null}return wr}function getTraceId(){return br?br.traceId:null}function getSessionContext(){return br?me.setSpanContext(ge.active(),br):ge.active()}function endSession(e={}){const{status:t="success"}=e;if(br&&Er){const e=me.getTracer(mt),n=Date.now()-Er,r=me.setSpanContext(ge.active(),br),s=e.startSpan("session:end",{attributes:{"session.id":wr||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Cr}},r);"error"===t?s.setStatus({code:pe.ERROR}):s.setStatus({code:pe.OK}),s.end()}Sr=null,br=null,wr=null,Er=null,Cr={}}var Tr=__esm({"src/utils/telemetry/session.ts"(){Nt(),$t(),yr(),en(),wr=null,Sr=null,br=null,Er=null,Cr={},__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:pe.ERROR}):e.setStatus({code:pe.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=me.getTracer(mt),s=getSessionContext();return r.startSpan(t,{attributes:n},s)}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:pe.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 kr,_r,Pr,Ar,xr,Ir,Nr,Rr,$r,Lr,Mr,Or,Dr,qr,Fr=__esm({"src/utils/telemetry/spans.ts"(){Nt(),$t(),Tr(),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});function dedentText(e){const t=e.split("\n");let n=1/0;for(const e of t){if(0===e.trim().length)continue;const t=e.length-e.trimStart().length;t>0&&t<n&&(n=t)}return n===1/0||0===n?e:t.map(e=>0===e.trim().length?e:e.length-e.trimStart().length>=n?e.slice(n):e).join("\n")}function getEffectiveWidth({padding:e=Ar}={}){let t=80;return process.stdout.columns?t=process.stdout.columns:process.stderr.columns?t=process.stderr.columns:process.env.COLUMNS&&(t=Number(process.env.COLUMNS)),Math.max(40,t-e)}function truncateString({text:e,maxChars:t}){return e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`}function truncateCommand({command:e}){const t=e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~").replace(/C:\\Users\\[^\\]+/g,"~");if(t.length<=xr)return t;if(t.includes(" && ")){const e=t.split(" && ")[0].trim();return e.length<=xr-5?`${e} && ...`:truncateString({text:e,maxChars:xr})}return truncateString({text:t,maxChars:xr})}function truncateToVisualLines({output:e,maxVisualLines:t=kr,padding:n=Ar,maxChars:r}){const s=getEffectiveWidth({padding:n}),o=r??t*s,i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim().split("\n");let a=0,l=i.length;for(let e=0;e<i.length;e++){const n=i[e];if(0===n.trim().length)continue;const r=Math.max(1,Math.ceil(n.length/s));if(!(a+r<=t)){l=Math.max(1,e);break}a+=r}const u=l<i.length,d=i.slice(l).reduce((e,t)=>e+Math.max(1,Math.ceil(t.length/s)),0),m=i.slice(0,l).filter(e=>e.trim().length>0).join("\n");if(m.length>o){const e=m.slice(0,o-3).trimEnd(),t=e.lastIndexOf("\n"),n=t>0?e.slice(0,t):e;return{text:u?n:`${n}...`,isTruncated:!0,remainingLines:d}}return{text:m,isTruncated:u,remainingLines:d}}var jr=__esm({"src/utils/truncation.ts"(){Nt(),kr=2,_r=10,Pr=10,Ar=4,xr=100,Ir=100,Nr=50,Rr=100,$r=60,Lr=80,Mr=1e5,Or=5e4,Dr=25e3,qr=200,__name(dedentText,"dedentText"),__name(getEffectiveWidth,"getEffectiveWidth"),__name(truncateString,"truncateString"),__name(truncateCommand,"truncateCommand"),__name(truncateToVisualLines,"truncateToVisualLines")}});function isSecretKey(e){const t=e.toLowerCase();return pt.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return gt.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString2(e){return e.length<=qr?e:`${e.substring(0,qr-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>qr?truncateString2(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,s]of Object.entries(t))e[n]=sanitizeValue({value:s,key:n,visited:r});return e}return"[Unsupported]"}function sanitizeParams(e){const t=new WeakSet;t.add(e);const n={};for(const[r,s]of Object.entries(e))n[r]=sanitizeValue({value:s,key:r,visited:t});return n}function sanitizeEndpoint(e){return e.split("?")[0]}var zr=__esm({"src/utils/telemetry/sanitization.ts"(){Nt(),$t(),jr(),__name(isSecretKey,"isSecretKey"),__name(isContentKey,"isContentKey"),__name(safeStringify,"safeStringify"),__name(truncateString2,"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:s}=e;return{span:t,end:__name(e=>{const o=Date.now()-n;if(t.setAttribute(r,o),"status"in e)t.setAttribute(s,e.status),e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r,errorBody:s}=e;if(t.setAttribute("http.status_code",n),s){const e="string"==typeof s?s:safeStringify(s);t.setAttribute("http.response_body",e.substring(0,ht))}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:s,heading:o,code:i,...a}=n,l={"error.type":r.name,"error.message":r.message,"error.component":s,"error.heading":o};void 0!==i&&(l["error.code"]=String(i));for(const[e,t]of Object.entries(a))null!=t&&(l[e]="object"==typeof t?safeStringify(t):String(t));const u=createSpan({name:`error:${r.name}`,attributes:l});recordError({span:u,error:r}),u.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:s,nodeVersion:o,platform:i,arch:a}=e,l={"whoami.node_version":o,"whoami.platform":i,"whoami.arch":a,"whoami.os":`${i}-${a}`};t&&(l["whoami.user_name"]=t),n&&(l["whoami.user_id"]=n),r&&(l["whoami.org_login"]=r),s&&(l["whoami.org_id"]=s),endSpan({span:createSpan({name:"whoami",attributes:l}),status:"success"})}var Br,Ur,Wr,Qr=__esm({"src/utils/telemetry/events.ts"(){Nt(),Fr(),Tr(),$t(),zr(),zr(),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(trackError,"trackError"),__name(trackAPICallStart,"trackAPICallStart"),__name(getSupportId,"getSupportId"),__name(systemInfo,"systemInfo")}}),Gr=__esm({"src/utils/telemetry/components.ts"(){Nt(),Br={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(Wr)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(Ur=createTelemetrySDK()).start(),Wr=!0,!0}catch{return Ur=null,Wr=!1,!1}}async function shutdownTelemetry(){if(Ur&&Wr)try{endSession(),await Ur.shutdown()}catch{}finally{Ur=null,Wr=!1}}function shutdownTelemetrySync(){if(Wr)try{endSession()}catch{}}function isTelemetryInitialized(){return Wr}var Hr,Vr=__esm({"src/utils/telemetry/telemetry.ts"(){Nt(),vr(),cr(),Tr(),Fr(),Qr(),Gr(),Ur=null,Wr=!1,__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized")}});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=ye.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}function createAuthServer(e,t){let n,r;const s=new Promise((e,t)=>{n=e,r=t}),o=fe.createServer((e,s)=>{const i=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],a=e.headers.origin||"",l=i.includes(a)?a:i[0];if(s.setHeader("Access-Control-Allow-Origin",l),s.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type"),s.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return s.writeHead(204),void s.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return s.writeHead(404),void s.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return s.writeHead(405),void s.end(JSON.stringify(e))}let u="";e.on("data",t=>{u+=t.toString(),u.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(u);if(e.error){const t=e,n={success:!0};return s.writeHead(200),s.end(JSON.stringify(n)),"access_denied"===t.error?r(new Hr(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void o.close()}const i=e;if(!(i.apiKey&&i.state&&i.userId&&i.userName&&i.keyName)){const e={success:!1,error:"Missing required fields"};return s.writeHead(400),void s.end(JSON.stringify(e))}if(i.state!==t){const e={success:!1,error:"Invalid state token"};return s.writeHead(403),void s.end(JSON.stringify(e))}const a={success:!0};s.writeHead(200),s.end(JSON.stringify(a)),n(i),o.close()}catch{const e={success:!1,error:"Invalid JSON"};s.writeHead(400),s.end(JSON.stringify(e))}}),e.on("error",()=>{s.writeHead(500),s.end(JSON.stringify({success:!1,error:"Request error"}))})});return o.on("error",e=>{r(e)}),o.listen(e,"127.0.0.1"),{server:o,waitForCallback:s}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}var Kr,Yr=__esm({"src/utils/auth/local-server.ts"(){Nt(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable"),Hr=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}},__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer")}});function generateStateToken(){return F.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await ie(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:Br.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(Lt()){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)}`}async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await $.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 $.writeFile(n,r,{mode:384}),await $.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await $.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}}var Jr=__esm({"src/utils/auth/auth-flow.ts"(){Nt(),Yr(),Dt(),jt(),Vr(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl"),Kr=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}},__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials")}});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"}var Xr,Zr,es,ts=__esm({"src/api/utils.ts"(){Nt(),__name(getApiBaseUrl,"getApiBaseUrl")}});async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${St.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:Br.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:s=Xr}=e,[o,i]=W("initializing"),[a,l]=W("Starting authentication..."),[u,d]=W(""),[m,p]=W(null),g=Q(null),h=Q(!1),f=Q(!1),y=Q(null),w=Q(t),S=Q(n),b=Q(r);G(()=>{w.current=t,S.current=n,b.current=r});const E=V(()=>{y.current&&(clearTimeout(y.current),y.current=null),g.current&&(stopServer(g.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),g.current=null)},[]),C=V(()=>{f.current||(f.current=!0,h.current=!0,E(),b.current())},[E]),v=V((e,t)=>{f.current||(f.current=!0,E(),w.current(e,t))},[E]),T=V((e,t)=>{f.current||(f.current=!0,E(),S.current(e,t))},[E]),k=V(async e=>{const t=sanitizeApiKey(e);if(!t)return;i("validating"),l("Validating API key...");const n=await validateApiKey(t);if(h.current)return;if(f.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 i("invalid_key"),l(e),void(y.current=setTimeout(()=>{h.current||f.current||(i("manual_entry"),l("Paste a valid API key below.")),y.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(f.current)return;await storeCredentials(e),i("success"),v(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:Br.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),l("Failed to save API key. Please try again."),i("manual_entry")}},[v]);return G(()=>{let e=!0;return __name(async()=>{if(!h.current)try{const t=await findAvailablePort(Zr,es);if(!e||h.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);p(r);const{server:o,waitForCallback:a}=createAuthServer(t,n);if(g.current=o,!e||h.current)return void await stopServer(o);i("waiting_browser"),l("Complete login in your browser...");const u=await openBrowser(r);if(!e||h.current)return;if(!u)return E(),l("Could not open browser. Paste your API key below."),void i("manual_entry");const d=new Promise((e,t)=>{setTimeout(()=>{t(new Kr("TIMEOUT","Browser authentication timed out"))},s)});try{const t=await Promise.race([a,d]);if(!e||h.current)return;if(f.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(f.current)return;if(await storeCredentials(n),!e||h.current||f.current)return;i("browser_success"),v(n,"browser")}catch(t){if(f.current)return;if(!e||h.current)return;if(t instanceof Hr)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:Br.AUTH_FLOW,heading:"Authorization denied by user"}}),i("denied"),void T("denied","Authorization denied by user.");E(),t instanceof Kr&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:Br.AUTH_FLOW,heading:"Browser auth timed out"}}),l("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:Br.AUTH_FLOW,heading:"Browser auth failed"}}),l("Browser auth failed. Paste your API key below.")),i("manual_entry")}}catch(t){if(f.current)return;if(!e||h.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:Br.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),E(),i("manual_entry"),l("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,E()}},[s,v,T,E]),{authState:o,statusMessage:a,browserUrl:m,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:k,cancel:C,hasCompleted:f.current}}var ns=__esm({"src/tui/hooks/use-auth-flow.ts"(){Nt(),Jr(),Yr(),ts(),Ot(),Vr(),Xr=12e4,Zr=5959,es=10,__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow")}});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:"}var rs,ss,os,as=__esm({"src/utils/auth/auth-status.ts"(){Nt(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel")}}),ls=__esm({"src/tui/auth-flow-ui.tsx"(){Nt(),vn(),Ot(),Dt(),as(),rr(),(rs=B.memo(({authState:e,browserUrl:t,apiKeyInput:n,setApiKeyInput:r,handleApiKeySubmit:s})=>{const o="waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,i=t&&("waiting_browser"===e||"manual_entry"===e);return B.createElement(B.Fragment,null,o&&B.createElement(K,{flexDirection:"column"},B.createElement(K,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?Ln.YELLOW:Ln.GRAY,paddingX:1},B.createElement(Y,{dimColor:!0},"API Key: "),B.createElement(K,{flexGrow:1},B.createElement(TextInput,{value:n,onChange:r,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},getAuthHelpText(e))),i&&B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,{dimColor:!0},getAuthUrlLabel(e)),B.createElement(Y,{color:Ln.CYAN,dimColor:!0},t||getStudioAuthUrl(Lt())))),"validating"===e&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Ctrl+C to cancel")))})).displayName="AuthInputSection",ss=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:s,handleApiKeySubmit:o})=>{const i=__name(()=>{switch(e){case"initializing":case"validating":default:return B.createElement(Se,{type:"dots"});case"waiting_browser":return B.createElement(Y,{color:Ln.CYAN},be.ellipsis);case"browser_success":case"success":return B.createElement(Y,{color:Ln.GREEN},be.tick);case"denied":case"invalid_key":return B.createElement(Y,{color:Ln.RED},be.cross);case"manual_entry":return B.createElement(Y,{color:Ln.YELLOW},be.arrowDown);case"error":return B.createElement(Y,{color:Ln.RED},be.warning)}},"getStatusIcon"),a=__name(()=>getAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:B.createElement(K,{flexDirection:"column",paddingY:1},B.createElement(K,{marginBottom:1},B.createElement(K,{marginRight:1},i()),B.createElement(Y,{color:a()},t)),B.createElement(rs,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:s,handleApiKeySubmit:o}))},"AuthFlowUI")}}),cs=__esm({"src/tui/login-with-api-key.tsx"(){Nt(),ns(),ls(),os=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:s,setApiKeyInput:o,handleApiKeySubmit:i,cancel:a}=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 Z((e,t)=>{t.ctrl&&"c"===e&&a()}),B.createElement(ss,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:s,setApiKeyInput:o,handleApiKeySubmit:i})},"LoginWithApiKey")}});function heading({text:e,sub:t,dim:n,green:r}){const s=t?` ${t}`:"";return r?`${re.bgGreen(re.black(` ${e} `))}${s}`:n?`${re.bgBlack(re.white(` ${e} `))}${s}`:`${re.bold(re.bgCyan(re.black(` ${e} `)))}${s}`}var us=__esm({"src/utils/heading.ts"(){Nt(),__name(heading,"heading")}});async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=on.createAuthorizationUrl(),r=await _e({message:"Open the Anthropic auth page?",initialValue:!0});if(Te(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await ie(e),console.log(),console.log(re.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(re.dim(" Open this URL in your browser:")),console.log(),console.log(re.cyan(` ${e}`)),console.log(),console.log(re.yellow(" Copy your authorization code and paste it below.")),console.log());const s=await Pe({message:"Paste your authorization code:",mask:"*"});if(Te(s))return{success:!1,error:"No API key provided"};if(!s.trim())return{success:!1,error:"No authorization code provided"};const o=s.split("#")[0].trim();return await on.exchangeCodeForTokens(o,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}var ds,ms,ps,gs=__esm({"src/commands/auth/anthropic-auth.ts"(){Nt(),dn(),__name(performAnthropicAuth,"performAnthropicAuth")}}),hs=__esm({"src/commands/auth/errors.ts"(){Nt(),ds=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},ms=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 L.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 getUserName(e){const t=await readAuthFile(e);return t&&t.userName||""}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=Ie("Checking authentication status...").start();try{const t=Lt(),n=await checkAuthStatus(t);n.error&&(e.fail(re.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(re.red("Not authenticated")),console.log(""),console.log(`${re.dim("Run")} ${re.cyan("cmd auth login")} ${re.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${re.green(be.tick)} ${re.bold("Authenticated")} with ${re.cyan("Command Code")}`),n.userName&&console.log(`${re.dim("Logged in as")} ${re.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(re.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}var fs,ys,ws,Ss,bs,Es=__esm({"src/commands/auth/status.ts"(){Nt(),Ot(),jt(),Dt(),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(getUserName,"getUserName"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction"),ps=new Ae("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction)}});function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:s=!0}){const[o,i]=W("loading"),[a,l]=W(null);return G(()=>{n().then(e=>{l(e),i(s?"success":"done")})},[n,s]),G(()=>{if("done"===o&&null!==a&&r(a),"success"===o&&null!==a){const e=setTimeout(()=>r(a),100);return()=>clearTimeout(e)}},[o,a,r]),"done"===o?null:B.createElement(ws,null,"loading"===o?B.createElement(fs,{message:e}):B.createElement(ys,{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 ${re.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${re.green(be.tick)} ${re.bold("Already logged in")}${t}`,"",`${re.dim("Run")} ${re.cyan("cmd")} ${re.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${re.green(be.tick)} ${re.bold("Logged in")}${n}`,"",`${re.dim("API key stored in")} ${re.cyan(`~/.commandcode/${t}`)}`,`${re.dim("Run")} ${re.cyan("cmd")} ${re.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 ms(e.message):isLoginCancelled(e)?new ds(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 ds||e instanceof ms}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),Ee.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await ve({message:"Select provider",options:e});if(Te(t))throw Ce(`${be.cross} No provider selected.`),new ds("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){Ce(`${be.cross} ${e}`)}function showAnthropicAuthNote(){ke("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(s=>{const o=__name(e=>{i(),s(e)},"handleComplete"),{unmount:i}=ee(B.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:o,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=ee(B.createElement(os,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=ee(B.createElement(Ss,{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=Lt(),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(`${be.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}var Cs=__esm({"src/tui/auth/login.tsx"(){Nt(),Ot(),cs(),un(),Dt(),us(),ir(),nr(),gs(),hs(),Es(),rr(),fs=__name(({message:e})=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.CYAN},B.createElement(Se,{type:"dots"})),B.createElement(Y,null," ",e)),"LoadingIndicator"),ys=__name(({message:e})=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.GREEN},be.tick),B.createElement(Y,null," ",e)),"SuccessIndicator"),ws=__name(({children:e})=>B.createElement(K,{flexDirection:"column"},B.createElement(Y,null," "),B.createElement(K,null,e)),"StatusContainer"),__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"),Ss=__name(({env:e,onComplete:t})=>{const[n,r]=W("checking"),[s,o]=W(null);return G(()=>{checkExistingAuth(e).then(e=>{o(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),G(()=>{if("checking"!==n&&null!==s){const e=setTimeout(()=>t(s),100);return()=>clearTimeout(e)}},[n,s,t]),B.createElement(ws,null,"checking"===n&&B.createElement(fs,{message:"Checking authentication status..."}),"logged_in"===n&&B.createElement(ys,{message:"Authenticated"}),"not_logged_in"===n&&B.createElement(ys,{message:"Ready to log in"}))},"AuthCheckSpinner"),__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleAnthropicAuth,"handleAnthropicAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction"),bs=new Ae("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction)}});async function safeRemoveFile(e,t){try{return await L.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"}}}var vs,Ts,ks,_s,Ps,As,xs=__esm({"src/utils/auth/logout.ts"(){Nt(),jt(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout")}});function printWarnings(e){e.length>0&&(console.warn(re.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(re.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=ee(B.createElement(Ps,{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)}var Is,Ns,Rs,$s,Ls,Ms,Os,Ds,qs,Fs,js,zs,Bs,Us,Ws=__esm({"src/tui/auth/logout.tsx"(){Nt(),xs(),rr(),vs=__name(()=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.CYAN},B.createElement(Se,{type:"dots"})),B.createElement(Y,null," Logging out...")),"LoadingIndicator"),Ts=__name(()=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.GREEN},be.tick),B.createElement(Y,null," Logged out")),"SuccessIndicator"),ks=__name(({errorMessage:e})=>B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.RED},be.cross),B.createElement(Y,{color:Ln.RED}," Logout failed: ",e)),"ErrorIndicator"),_s=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return B.createElement(vs,null);case"success":return B.createElement(Ts,null);case"error":return B.createElement(ks,{errorMessage:t})}},"StatusDisplay"),Ps=__name(({onComplete:e})=>{const[t,n]=W("loading"),[r,s]=W(""),[o,i]=W(null);return G(()=>{performLogout().then(e=>{i(e),e.success?n("success"):(s(e.error||"Unknown error"),n("error"))})},[]),G(()=>{if(("success"===t||"error"===t)&&o){const t=setTimeout(()=>e(o),100);return()=>clearTimeout(t)}},[t,o,e]),B.createElement(K,{flexDirection:"column"},B.createElement(Y,null," "),B.createElement(K,null,B.createElement(_s,{status:t,errorMessage:r})))},"LogoutSpinner"),__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction"),As=new Ae("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction)}}),Qs=__esm({"src/commands/auth/index.ts"(){Nt(),Cs(),Ws(),Es(),hs(),Es(),Ws(),Cs(),gs(),Dt(),jt(),new Ae("auth").description("Manage authentication with Command Code").addCommand(bs).addCommand(As).addCommand(ps)}}),Gs=__esm({"../shared/src/constants/tools.ts"(){Nt(),Is={READ_FILE:"read_file",EDIT_FILE:"edit_file",WRITE_FILE:"write_file",READ_DIRECTORY:"read_directory",READ_MULTIPLE_FILES:"read_multiple_files",GREP:"grep",SHELL_COMMAND:"shell_command",THINKING:"think",TODO_WRITE:"todo_write",QUESTION:"ask_user_question",EXPLORE:"explore",KILL_SHELL:"kill_shell",ENTER_PLAN_MODE:"enter_plan_mode",EXIT_PLAN_MODE:"exit_plan_mode",DIAGNOSTICS:"diagnostics"},Ns={WEB_SEARCH:"web_search",WEB_FETCH:"web_fetch"},Rs=__name(e=>e===Ns.WEB_SEARCH,"isWebSearchTool"),$s=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],Ls=__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 $s.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:Rs(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),Ms=["create_file","delete_file",Is.EDIT_FILE,Is.WRITE_FILE,Is.SHELL_COMMAND],Os=[Is.SHELL_COMMAND]}}),Hs=__esm({"src/mcp/constants.ts"(){Nt(),Ds="2025-03-26",qs={name:"command-code",version:"1.0.0"},Promise.resolve().then(()=>(yr(),ur)).then(({getPackageJson:e})=>{qs.version=e().version??"1.0.0"}).catch(()=>{})}}),Vs=__esm({"src/mcp/types.ts"(){Nt(),Fs=g.object({authorizationUrl:g.string(),tokenUrl:g.string(),clientId:g.string(),clientSecret:g.string().optional(),scopes:g.array(g.string()).optional()}),js=g.object({transport:g.enum(["stdio","http"]),enabled:g.boolean().default(!0),command:g.string().optional(),args:g.array(g.string()).optional(),url:g.string().optional(),headers:g.record(g.string(),g.string()).optional(),oauth:Fs.optional(),env:g.record(g.string(),g.string()).optional()}),zs=g.object({mcpServers:g.record(g.string(),js)})}});function getUserMcpConfigPath(){return e.join(f.homedir(),".commandcode",Bs)}function getLocalMcpConfigPath(t=process.cwd()){const n=Ne(t);return e.join(f.homedir(),".commandcode","projects",n,Bs)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,Us)}function getMcpConfigPath({scope:e,projectPath:t=process.cwd()}){switch(e){case"user":return getUserMcpConfigPath();case"local":return getLocalMcpConfigPath(t);case"project":return getProjectMcpConfigPath(t)}}function getAllMcpConfigPaths(e=process.cwd()){return[{scope:"user",path:getUserMcpConfigPath()},{scope:"project",path:getProjectMcpConfigPath(e)},{scope:"local",path:getLocalMcpConfigPath(e)}]}var Ks,Ys=__esm({"src/mcp/config/scopes.ts"(){Nt(),Ot(),Bs="mcp.json",Us=".mcp.json",__name(getUserMcpConfigPath,"getUserMcpConfigPath"),__name(getLocalMcpConfigPath,"getLocalMcpConfigPath"),__name(getProjectMcpConfigPath,"getProjectMcpConfigPath"),__name(getMcpConfigPath,"getMcpConfigPath"),__name(getAllMcpConfigPaths,"getAllMcpConfigPaths")}});function getTokenFilePath(){return e.join(f.homedir(),".commandcode",Ks)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await $.readFile(e,"utf-8"),n=JSON.parse(t);return 1!==n.version||"object"!=typeof n.tokens?{version:1,tokens:{}}:n}catch(e){return dlog("[MCP] Failed to load token storage",e),{version:1,tokens:{}}}}async function saveTokenStorage(t){const n=getTokenFilePath(),r=e.dirname(n);await $.mkdir(r,{recursive:!0}),await $.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await $.chmod(n,384)}async function storeTokens(e,t){const n=await loadTokenStorage();n.tokens[e]=t,await saveTokenStorage(n)}async function getTokens(e){return(await loadTokenStorage()).tokens[e]||null}async function deleteTokens(e){const t=await loadTokenStorage();return e in t.tokens&&(delete t.tokens[e],await saveTokenStorage(t),!0)}async function hasTokens(e){return e in(await loadTokenStorage()).tokens}function isTokenExpired(e){return!!e.expiresAt&&Date.now()>=e.expiresAt-6e4}async function getValidAccessToken({serverName:e,refreshCallback:t}){const n=await getTokens(e);if(!n)return null;if(!isTokenExpired(n))return n.accessToken;if(n.refreshToken&&t)try{const r=await t(n.refreshToken);return await storeTokens(e,r),r.accessToken}catch(t){return dlog("[MCP] Token refresh failed",t),await deleteTokens(e),null}return await deleteTokens(e),null}async function listServersWithTokens(){const e=await loadTokenStorage();return Object.keys(e.tokens)}async function storeClientSecret(e,t){const n=await loadTokenStorage();n.clientSecrets||(n.clientSecrets={}),n.clientSecrets[e]=t,await saveTokenStorage(n)}async function getClientSecret(e){const t=await loadTokenStorage();return t.clientSecrets?.[e]??null}var Js=__esm({"src/mcp/auth/token-storage.ts"(){Nt(),Ot(),$n(),Ks="mcp-tokens.json",__name(getTokenFilePath,"getTokenFilePath"),__name(loadTokenStorage,"loadTokenStorage"),__name(saveTokenStorage,"saveTokenStorage"),__name(storeTokens,"storeTokens"),__name(getTokens,"getTokens"),__name(deleteTokens,"deleteTokens"),__name(hasTokens,"hasTokens"),__name(isTokenExpired,"isTokenExpired"),__name(getValidAccessToken,"getValidAccessToken"),__name(listServersWithTokens,"listServersWithTokens"),__name(storeClientSecret,"storeClientSecret"),__name(getClientSecret,"getClientSecret")}});async function loadMcpConfig({scope:e,projectPath:t=process.cwd()}){try{const n=getMcpConfigPath({scope:e,projectPath:t}),r=await $.readFile(n,"utf-8"),s=JSON.parse(r),o=zs.safeParse(s);return o.success?o.data:null}catch(e){return dlog("[MCP] Failed to load config",e),null}}async function saveMcpConfig({config:t,scope:n,projectPath:r=process.cwd()}){const s=getMcpConfigPath({scope:n,projectPath:r}),o=e.dirname(s);await $.mkdir(o,{recursive:!0}),await $.writeFile(s,JSON.stringify(t,null,2)+"\n",{mode:384})}async function loadMergedMcpConfig(e=process.cwd()){const t=getAllMcpConfigPaths(e),n={},r=new Map;for(const{scope:s}of t){const t=await loadMcpConfig({scope:s,projectPath:e});if(t?.mcpServers)for(const[e,o]of Object.entries(t.mcpServers))n[e]=o,r.set(e,s)}return{config:{mcpServers:n},serverScopes:r}}async function addMcpServer({name:e,serverConfig:t,scope:n,projectPath:r=process.cwd()}){let s=await loadMcpConfig({scope:n,projectPath:r});s||(s={mcpServers:{}});let o=t;if("project"===n&&t.oauth?.clientSecret){await storeClientSecret(e,t.oauth.clientSecret);const{clientSecret:n,...r}=t.oauth;o={...t,oauth:r}}s.mcpServers[e]=o,await saveMcpConfig({config:s,scope:n,projectPath:r})}async function removeMcpServer({name:e,scope:t,projectPath:n=process.cwd()}){const r=await loadMcpConfig({scope:t,projectPath:n});return!!r?.mcpServers[e]&&(delete r.mcpServers[e],await saveMcpConfig({config:r,scope:t,projectPath:n}),!0)}async function getMcpServer({name:e,projectPath:t=process.cwd()}){const{config:n,serverScopes:r}=await loadMergedMcpConfig(t),s=n.mcpServers[e],o=r.get(e);return s&&o?{config:s,scope:o}:null}async function listMcpServers(e=process.cwd()){const{config:t,serverScopes:n}=await loadMergedMcpConfig(e);return Object.entries(t.mcpServers).map(([e,t])=>({name:e,config:t,scope:n.get(e)}))}var Xs,Zs,eo=__esm({"src/mcp/config/mcp-config.ts"(){Nt(),Vs(),Ys(),$n(),Js(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers")}}),to=__esm({"src/mcp/client/stdio-transport.ts"(){Nt(),Xs=class _StdioTransport extends Re{constructor(e){super(),this.options=e}static{__name(this,"StdioTransport")}process=null;buffer="";pendingRequests=new Map;static REQUEST_TIMEOUT_MS=8e4;nextRequestId=0;isConnected=!1;static fromConfig(e){if("stdio"!==e.transport)throw new Error("Config is not for stdio transport");if(!e.command)throw new Error("Command is required for stdio transport");return new _StdioTransport({command:e.command,args:e.args,env:e.env})}async connect(){if(!this.isConnected)return new Promise((e,t)=>{try{this.process=N(this.options.command,this.options.args||[],{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.options.env}}),this.process.on("error",e=>{this.handleError(e),this.isConnected||t(e)}),this.process.on("exit",(e,t)=>{this.isConnected=!1,this.emit("close",e,t);for(const[,n]of this.pendingRequests){const r=t?`signal ${t}`:`code ${e}`;n.reject(new Error(`Process exited with ${r}`))}this.pendingRequests.clear()}),this.process.stdout?.on("data",e=>{this.handleData(e.toString())}),this.process.stderr?.on("data",e=>{this.emit("stderr",e.toString())}),this.isConnected=!0,e()}catch(e){t(e)}})}async request(e,t){if(!this.isConnected||!this.process?.stdin)throw new Error("Transport is not connected");const n=this.nextRequestId++,r={jsonrpc:"2.0",method:e,id:n,...t&&{params:t}};return new Promise((e,t)=>{const s=setTimeout(()=>{this.pendingRequests.delete(n),t(new Error("Request timed out"))},_StdioTransport.REQUEST_TIMEOUT_MS);this.pendingRequests.set(n,{resolve:__name(t=>{clearTimeout(s),e(t)},"resolve"),reject:__name(e=>{clearTimeout(s),t(e)},"reject")});const o=JSON.stringify(r)+"\n";this.process.stdin.write(o,e=>{e&&(clearTimeout(s),this.pendingRequests.delete(n),t(e))})})}notify(e,t){if(!this.isConnected||!this.process?.stdin)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,...t&&{params:t}},r=JSON.stringify(n)+"\n";this.process.stdin.write(r,e=>{e&&this.handleError(e)})}async close(){this.process&&(this.process.stdin?.end(),this.process.kill(),this.process=null),this.isConnected=!1,this.pendingRequests.clear()}get connected(){return this.isConnected}handleData(e){let t;for(this.buffer+=e;-1!==(t=this.buffer.indexOf("\n"));){const e=this.buffer.substring(0,t);this.buffer=this.buffer.substring(t+1),e.trim()&&this.handleMessage(e)}}handleMessage(e){try{const t=JSON.parse(e);if("id"in t&&void 0!==t.id){const e=t,n=this.pendingRequests.get(e.id);n&&(this.pendingRequests.delete(e.id),n.resolve(e))}else{const e=t;this.emit("notification",e)}}catch(t){this.emit("error",new Error(`Failed to parse message: ${e}`))}}handleError(e){this.isConnected=!1,this.emit("error",e)}}}});function fetchWithTimeout(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),Zs);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var no,ro,so=__esm({"src/mcp/fetch.ts"(){Nt(),Zs=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),oo={};function generateRandomString(e){return F.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:F.createHash("sha256").update(e).digest("base64url")}}function escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function startCallbackServer(e,t){return new Promise((n,r)=>{let s=null,o=null;const i=new Promise((e,t)=>{s=e,o=t}),a=fe.createServer((n,r)=>{const i=new d(n.url||"/",`http://${ro}:${e}`);if("/callback"===i.pathname){const e=i.searchParams.get("code"),n=i.searchParams.get("error"),a=i.searchParams.get("error_description");if(i.searchParams.get("state")!==t)r.writeHead(400,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Failed</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Failed</h1>\n\t\t\t\t\t\t\t<p>Invalid state parameter. Please try again.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),o?.(new Error("OAuth state parameter mismatch"));else if(n){const e=escapeHtml(a||n);r.writeHead(400,{"Content-Type":"text/html"}),r.end(`\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Failed</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Failed</h1>\n\t\t\t\t\t\t\t<p>${e}</p>\n\t\t\t\t\t\t\t<p>You can close this window.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t`),o?.(new Error(a||n))}else e?(r.writeHead(200,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Successful</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Successful</h1>\n\t\t\t\t\t\t\t<p>You can close this window and return to Command Code.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),s?.(e)):(r.writeHead(400,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Invalid Request</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Invalid Request</h1>\n\t\t\t\t\t\t\t<p>No authorization code received.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),o?.(new Error("No authorization code received")))}else r.writeHead(404),r.end("Not Found")});a.on("error",r),a.listen(e,ro,()=>{n({server:a,getCode:__name(()=>i,"getCode")})})})}async function exchangeCodeForTokens(e,t,n,r){const s=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r,client_id:e.clientId,code_verifier:n});e.clientSecret&&s.set("client_secret",e.clientSecret);const o=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()});if(!o.ok){const e=await o.text();throw new Error(`Token exchange failed: ${o.status} ${e}`)}const i=await o.json();return{accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?Date.now()+1e3*i.expires_in:void 0,tokenType:i.token_type,scope:i.scope}}async function refreshAccessToken({config:e,refreshToken:t}){const n=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId});e.clientSecret&&n.set("client_secret",e.clientSecret);const r=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});if(!r.ok){const e=await r.text();throw new Error(`Token refresh failed: ${r.status} ${e}`)}const s=await r.json();return{accessToken:s.access_token,refreshToken:s.refresh_token||t,expiresAt:s.expires_in?Date.now()+1e3*s.expires_in:void 0,tokenType:s.token_type,scope:s.scope}}async function performOAuthFlow(e,t,n){const r=n?.port||no,s=n?.timeout||12e4,o=n?.onStatus||(()=>{});let i=null;try{const n=generatePKCE(),a=generateRandomString(32),l=`http://${ro}:${r}/callback`;o("Starting authentication server...");const{server:u,getCode:m}=await startCallbackServer(r,a);i=u;const p=new d(t.authorizationUrl);if(p.searchParams.set("response_type","code"),p.searchParams.set("client_id",t.clientId),p.searchParams.set("redirect_uri",l),p.searchParams.set("state",a),p.searchParams.set("code_challenge",n.challenge),p.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&p.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))p.searchParams.set(e,n);o("Opening browser for authentication..."),await ie(p.toString()),o("Waiting for authorization...");const g=m();let h;const f=new Promise((e,t)=>{h=setTimeout(()=>t(new Error("Authentication timed out")),s)}),y=await Promise.race([g,f]);clearTimeout(h),o("Exchanging authorization code for tokens...");const w=await exchangeCodeForTokens(t,y,n.verifier,l);return await storeTokens(e,w),o("Authentication successful!"),{success:!0,tokens:w}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{i&&i.close()}}function createRefreshCallback(e){return t=>refreshAccessToken({config:e,refreshToken:t})}__export(oo,{DEFAULT_OAUTH_CALLBACK_PORT:()=>no,LOCALHOST_IP:()=>ro,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var io,ao,lo,co=__esm({"src/mcp/auth/oauth-flow.ts"(){Nt(),Js(),so(),no=8085,ro="127.0.0.1",__name(generateRandomString,"generateRandomString"),__name(generatePKCE,"generatePKCE"),__name(escapeHtml,"escapeHtml"),__name(startCallbackServer,"startCallbackServer"),__name(exchangeCodeForTokens,"exchangeCodeForTokens"),__name(refreshAccessToken,"refreshAccessToken"),__name(performOAuthFlow,"performOAuthFlow"),__name(createRefreshCallback,"createRefreshCallback")}}),uo=__esm({"src/mcp/client/http-transport.ts"(){Nt(),Hs(),Js(),so(),io=class _HttpTransport extends Re{constructor(e){super(),this.options=e}static{__name(this,"HttpTransport")}nextRequestId=0;isConnected=!1;abortController=null;static fromConfig({config:e,serverName:t}){if("http"!==e.transport)throw new Error("Config is not for http transport");if(!e.url)throw new Error("URL is required for http transport");return new _HttpTransport({url:e.url,headers:e.headers,serverName:t,oauth:e.oauth?{authorizationUrl:e.oauth.authorizationUrl,tokenUrl:e.oauth.tokenUrl,clientId:e.oauth.clientId,clientSecret:e.oauth.clientSecret,scopes:e.oauth.scopes}:void 0})}async connect(){this.isConnected||(this.abortController=new AbortController,this.isConnected=!0)}sessionId=null;async getHeaders(){const e={"Content-Type":"application/json",Accept:"application/json, text/event-stream","User-Agent":`${qs.name}/${qs.version}`,...this.options.headers};if(this.sessionId&&(e["Mcp-Session-Id"]=this.sessionId),this.options.serverName&&this.options.oauth){if(!this.options.oauth.clientSecret){const e=await getClientSecret(this.options.serverName);e&&(this.options.oauth.clientSecret=e)}const t=__name(async e=>{const{refreshAccessToken:t}=await Promise.resolve().then(()=>(co(),oo));return t({config:this.options.oauth,refreshToken:e})},"refreshCallback"),n=await getValidAccessToken({serverName:this.options.serverName,refreshCallback:t});n&&(e.Authorization=`Bearer ${n}`)}return e}parseSSEResponse(e){const t=e.split("\n");for(const e of t)if(e.startsWith("data: ")){const t=e.slice(6).trim();if(t&&"[DONE]"!==t)try{return JSON.parse(t)}catch{}}return null}async request(e,t){if(!this.isConnected)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,id:this.nextRequestId++,...t&&{params:t}},r=new AbortController,s=setTimeout(()=>r.abort(),Zs);this.abortController&&this.abortController.signal.addEventListener("abort",()=>r.abort(),{once:!0});try{const e=await this.getHeaders(),t=await fetch(this.options.url,{method:"POST",headers:e,body:JSON.stringify(n),signal:r.signal});if(!t.ok){let e=t.statusText;try{const n=await t.text(),r=JSON.parse(n);r.error?.message?e=r.error.message:r.message&&(e=r.message)}catch{}throw new Error(`MCP connection failed (${t.status}): ${e}`)}const s=t.headers.get("mcp-session-id");s&&(this.sessionId=s);const o=t.headers.get("content-type")||"",i=await t.text();if(o.includes("text/event-stream")||i.startsWith("event:")||i.startsWith("data:")){const e=this.parseSSEResponse(i);if(e)return e;throw new Error("Failed to parse SSE response")}return JSON.parse(i)}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw new Error("Request timed out");throw e}finally{clearTimeout(s)}}async notify(e,t){if(!this.isConnected)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,...t&&{params:t}},r=new AbortController,s=setTimeout(()=>r.abort(),Zs);this.abortController&&this.abortController.signal.addEventListener("abort",()=>r.abort(),{once:!0});try{const e=await this.getHeaders();await fetch(this.options.url,{method:"POST",headers:e,body:JSON.stringify(n),signal:r.signal})}catch(e){e instanceof Error&&"AbortError"!==e.name&&this.emit("error",e)}finally{clearTimeout(s)}}async close(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.isConnected=!1,this.emit("close")}get connected(){return this.isConnected}}}});function getMcpConnectionManager(){return lo||(lo=new ao),lo}var mo=__esm({"src/mcp/client/connection-manager.ts"(){Nt(),Hs(),eo(),to(),uo(),po(),ao=class extends Re{static{__name(this,"McpConnectionManager")}connections=new Map;initialized=!1;initializePromise=null;async initialize(e=process.cwd()){if(!this.initialized){if(this.initializePromise)return this.initializePromise;this.initializePromise=this.doInitialize(e);try{await this.initializePromise}finally{this.initializePromise=null}}}async doInitialize(e){const{config:t,serverScopes:n}=await loadMergedMcpConfig(e),r=[];for(const[e,s]of Object.entries(t.mcpServers)){if(!s.enabled)continue;const t=n.get(e);r.push(this.connectServer(e,s,t))}await Promise.allSettled(r),this.initialized=!0}async connectServer(e,t,n){const r={name:e,config:t,scope:n,transport:this.createTransport(t,e),status:"connecting",tools:[]};this.connections.set(e,r),this.emit("connecting",e);try{await r.transport.connect();const t=await this.initializeProtocol(r);if(r.serverInfo=t.serverInfo,r.capabilities=t.capabilities,r.transport instanceof Xs?r.transport.notify("notifications/initialized"):await r.transport.notify("notifications/initialized"),t.capabilities.tools){const e=await this.fetchTools(r);r.tools=e.tools}r.status="connected",this.emit("connected",e,r.tools.length)}catch(t){r.status="error",r.error=t instanceof Error?t.message:String(t),this.emit("error",e,r.error)}}createTransport(e,t){return"stdio"===e.transport?Xs.fromConfig(e):io.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:Ds,capabilities:{roots:{}},clientInfo:qs});if(t.error)throw new Error(`Initialize failed: ${t.error.message}`);return t.result}async fetchTools(e){const t=await e.transport.request("tools/list");if(t.error)throw new Error(`Tools list failed: ${t.error.message}`);return t.result}getConnectedServers(){return Array.from(this.connections.values()).map(e=>({name:e.name,config:e.config,scope:e.scope,status:e.status,error:e.error,capabilities:e.capabilities,serverInfo:e.serverInfo,tools:e.tools}))}getAllTools(){const e=[];for(const t of this.connections.values())if("connected"===t.status)for(const n of t.tools)e.push({serverName:t.name,tool:n,prefixedName:`mcp__${t.name}__${n.name}`});return e}async callTool(e,t,n){const r=this.connections.get(e);if(!r)throw new Error(`Server '${e}' not found`);if("connected"!==r.status)throw new Error(`Server '${e}' is not connected (status: ${r.status})`);const s=await r.transport.request("tools/call",{name:t,arguments:n});if(s.error)throw new Error(`Tool call failed: ${s.error.message}`);return s.result}async callToolByPrefixedName(e,t){const n=parseMcpToolName(e);if(!n)throw new Error(`Invalid MCP tool name: ${e}`);return this.callTool(n.serverName,n.toolName,t)}async disconnectServer(e){const t=this.connections.get(e);t&&(await t.transport.close(),t.status="disconnected",this.emit("disconnected",e))}async disconnectAll(){const e=[];for(const t of this.connections.values())e.push(t.transport.close());await Promise.allSettled(e),this.connections.clear(),this.initialized=!1}async reconnectServer(e){const t=this.connections.get(e);if(!t)throw new Error(`Server '${e}' not found`);await t.transport.close(),await this.connectServer(e,t.config,t.scope)}get isInitialized(){return this.initialized}},lo=null,__name(getMcpConnectionManager,"getMcpConnectionManager")}});function mcpToolToSchema({serverName:e,tool:t}){return{name:`mcp__${e}__${t.name}`,description:t.description||`MCP tool: ${t.name} (from ${e})`,input_schema:{type:"object",properties:t.inputSchema.properties??{},required:t.inputSchema.required}}}function getAllMcpToolSchemas(){return getMcpConnectionManager().getAllTools().map(({serverName:e,tool:t})=>mcpToolToSchema({serverName:e,tool:t}))}function isMcpTool(e){return e.startsWith("mcp__")}function parseMcpToolName(e){if(!isMcpTool(e))return null;const t=e.split("__");return t.length<3?null:{serverName:t[1],toolName:t.slice(2).join("__")}}async function executeMcpTool({prefixedName:e,args:t}){const n=getMcpConnectionManager();try{const r=await n.callToolByPrefixedName(e,t),s=r.content.map(e=>"text"===e.type?e.text||"":"image"===e.type?`[Image: ${e.mimeType||"unknown type"}]`:"resource"===e.type?`[Resource: ${e.mimeType||"unknown type"}]`:"").join("\n");return{success:!r.isError,result:s,...r.isError&&{error:s}}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}var po=__esm({"src/mcp/client/tool-adapter.ts"(){Nt(),mo(),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool")}});function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",s=e.relative(n,t);return s.startsWith("..")?r&&t.startsWith(r)?t.replace(r,"~"):t:""===s?e.basename(t):s}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}var ho,fo,yo,wo,So,bo,Eo,Co,vo,To,ko,_o,Po,Ao,xo,Io,No,Ro,$o,Lo,Mo,Oo,Do,qo,Fo,jo,zo,Bo,Uo,Wo,Qo,Go,Ho,Vo,Ko=__esm({"src/tools/utils/path-display.ts"(){Nt(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText")}}),Yo={};__export(Yo,{FeedEntrySchema:()=>Po,LLM_STATUS_MESSAGES:()=>Uo,createAgentToolEntry:()=>qo,createAssistantEntry:()=>Io,createBashEntry:()=>Ro,createCommandResultEntry:()=>Oo,createErrorEntry:()=>Lo,createIDEStatusEntry:()=>Do,createInfoEntry:()=>xo,createSystemEntry:()=>$o,createTasteOnboardingEntry:()=>Mo,createToolEntry:()=>No,createUserEntry:()=>Ao,formatError:()=>jo,getRandomLLMStatus:()=>Wo,getToolDisplayName:()=>Qo,getToolInputContent:()=>Ho,isErrorEntry:()=>zo,isPendingEntry:()=>Bo,parseTodosFromOutput:()=>Vo,updateEntryWithOutput:()=>Fo});var Jo=__esm({"src/types/feed.ts"(){Nt(),Gs(),po(),Ko(),jr(),ho=g.object({id:g.string(),timestamp:g.number(),type:g.literal("image"),source:g.object({type:g.enum(["base64","url"]),media_type:g.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:g.string()})}),fo=g.object({id:g.string(),timestamp:g.number(),input:g.string(),output:g.string().optional(),metadata:g.record(g.string(),g.any()).optional(),images:g.array(ho).optional().default([])}),yo=fo.extend({role:g.literal("user")}),wo=fo.extend({role:g.literal("assistant")}),So=fo.extend({role:g.literal("tool"),name:g.string(),description:g.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),bo=fo.extend({role:g.literal("bash"),command:g.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),Eo=fo.extend({role:g.literal("system")}),Co=fo.extend({role:g.literal("error")}),vo=fo.extend({role:g.literal("info")}),To=fo.extend({role:g.literal("taste-onboarding")}),ko=fo.extend({role:g.literal("command-result"),hasError:g.boolean().optional(),details:g.string().optional()}),_o=fo.extend({role:g.literal("ide-status"),status:g.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:g.string().nullable(),details:g.array(g.string()).optional()}),Po=g.discriminatedUnion("role",[yo,wo,So,bo,Eo,Co,vo,To,ko,_o]),Ao=__name((e,t)=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),xo=__name((e,t)=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),Io=__name(e=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),No=__name((e,t,n)=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Ro=__name(e=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),$o=__name(e=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Lo=__name(e=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),Mo=__name(()=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Oo=__name((e,t=!1,n)=>Po.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),Do=__name((e,t,n)=>Po.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 Po.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"),Fo=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return Po.parse(n)},"updateEntryWithOutput"),jo=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),zo=__name(e=>/^error:/i.test(e.output??""),"isErrorEntry"),Bo=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),Uo=["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…"],Wo=__name(()=>Uo[Math.floor(Math.random()*Uo.length)],"getRandomLLMStatus"),Qo=__name(e=>{switch(e){case Is.READ_FILE:return"READ";case Is.EDIT_FILE:return"EDIT";case Is.WRITE_FILE:return"WRITE";case Is.READ_DIRECTORY:return"LIST";case Is.READ_MULTIPLE_FILES:return"READ MULTIPLE";case Is.GREP:return"SEARCH";case Is.SHELL_COMMAND:return"SHELL";case Is.TODO_WRITE:return"TODOS";case Is.THINKING:return"thinking…";case Ns.WEB_SEARCH:return"WEB SEARCH";case Ns.WEB_FETCH:return"WEB FETCH";case Is.QUESTION:return"QUESTION";case Is.EXPLORE:return"EXPLORE";case Is.KILL_SHELL:return"KILL SHELL";default:if(isMcpTool(e)){const t=parseMcpToolName(e);if(t){const e=t.toolName.replace(/[-_]/g," ").toUpperCase();return`${t.serverName}: ${e} (MCP)`}}return e.replace(/_/g," ").toUpperCase()}},"getToolDisplayName"),Go=__name(e=>{const t=Object.entries(e);if(0===t.length)return"";const[n,r]=t[0];return`${n}: ${truncateString({text:"string"==typeof r?r:JSON.stringify(r)??"",maxChars:$r})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),Ho=__name((e,t)=>{try{switch(e){case Is.READ_FILE:case Is.WRITE_FILE:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case Is.EDIT_FILE:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Is.READ_DIRECTORY:return toRelativePath(t.path||"directory");case Is.GREP:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Is.SHELL_COMMAND: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 Is.TODO_WRITE:let s;try{s="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=Vo(s);return`${e?e.length:0} items`}catch{return"items"}case Is.THINKING:return t.content||"planning";case Is.READ_MULTIPLE_FILES:const o=t.include||[];return Array.isArray(o)?o.join(", "):"multiple files";case Ns.WEB_SEARCH:return t.query||"search";case Ns.WEB_FETCH:return t.url||"fetch";case Is.QUESTION:return"User answered questions";case Is.KILL_SHELL:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case Is.ENTER_PLAN_MODE:case Is.EXIT_PLAN_MODE:return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return Go(t);let n=t?.messages||[];if("string"==typeof n)try{n=JSON.parse(n)}catch(e){return JSON.stringify(t||{})}if(Array.isArray(n)&&n.length>0&&n[0]&&"object"==typeof n[0]&&"content"in n[0]){const e=n[0].content;if("string"==typeof e){const t=e.trim(),n=t.indexOf(".");return truncateString({text:n>0?t.slice(0,n):t,maxChars:Lr})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),Vo=__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")}});async function resolveEditStartLine({filePath:e,oldContent:t}){const n=await P.readFile(e,"utf-8"),r=n.indexOf(t);if(-1!==r)return n.substring(0,r).split("\n").length}function isDirectoryEmpty(){try{return 0===T(process.cwd()).length}catch{return!1}}var Xo,Zo=__esm({"src/utils/fs.ts"(){Nt(),__name(resolveEditStartLine,"resolveEditStartLine"),__name(isDirectoryEmpty,"isDirectoryEmpty")}}),ei=__esm({"src/tools/skills/types.ts"(){Nt()}}),ti=__esm({"../shared/src/types/skills.ts"(){Nt(),Xo=g.object({name:g.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:g.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:g.string().optional(),compatibility:g.string().max(500,"Skill compatibility must be 500 characters or less").optional(),metadata:g.record(g.string(),g.any()).optional(),"allowed-tools":g.union([g.string(),g.array(g.string())]).optional()}),g.object({name:g.string(),description:g.string(),license:g.string().optional(),compatibility:g.string().max(500).optional(),metadata:g.record(g.string(),g.any()).optional(),"allowed-tools":g.union([g.string(),g.array(g.string())]).optional(),content:g.string(),filePath:g.string()}),g.object({name:g.string(),description:g.string(),filePath:g.string()})}});function getPersonalSkillsDir(){return t.join(f.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return t.join(process.cwd(),".commandcode","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await L.access(r),r}catch{}const s=t.join(n,"skill.md");try{return await L.access(s),s}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await L.access(n);const e=await L.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await L.stat(t.join(n,e.name))).isDirectory()?e:null}catch{return null}return null}))).filter(e=>null!==e);return(await Promise.all(r.map(async e=>{try{const r=await resolveSkillFilePath({skillDir:t.join(n,e.name)});if(!r)return null;const s=await L.readFile(r,"utf-8"),{data:o}=$e(s),i=Xo.parse(o);return i.name!==e.name?null:{name:i.name,description:i.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}}var ni=__esm({"src/tools/skills/loader.ts"(){Nt(),ti(),Ot(),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries")}});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,s=[...n,...r];return 0===s.length?"":`<available_skills>\n${s.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>`}var ri,si,oi,ii,ai,li,ci,ui,di,mi,pi=__esm({"src/tools/skills/xml-generator.ts"(){Nt(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML")}}),gi=__esm({"src/tools/skills/index.ts"(){Nt(),ei(),ni(),pi()}}),hi=__esm({"src/api/errors.ts"(){Nt(),ri=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 s=t;this.error=s,this.code=s?.code,this.status=s?.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 si({cause:t instanceof Error?t:void 0});const s=t?.error;switch(e){case 400:return new oi(e,s,n,r);case 401:return new ii(e,s,n,r);case 403:return new ai(e,s,n,r);case 404:return new li(e,s,n,r);case 409:return new ci(e,s,n,r);case 422:return new ui(e,s,n,r);case 429:return new di(e,s,n,r);default:return e>=500?new mi(e,s,n,r):new _APIError(e,s,n,r)}}},si=class extends ri{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)}},oi=class extends ri{static{__name(this,"BadRequestError")}status=400},ii=class extends ri{static{__name(this,"AuthenticationError")}status=401},ai=class extends ri{static{__name(this,"PermissionDeniedError")}status=403},li=class extends ri{static{__name(this,"NotFoundError")}status=404},ci=class extends ri{static{__name(this,"ConflictError")}status=409},ui=class extends ri{static{__name(this,"UnprocessableEntityError")}status=422},di=class extends ri{static{__name(this,"RateLimitError")}status=429},mi=class extends ri{static{__name(this,"InternalServerError")}}}});function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}var fi,yi,wi,Si=__esm({"src/utils/index.ts"(){Nt(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath")}}),bi=__esm({"src/tools/read-file/types.ts"(){Nt(),fi=g.object({absolutePath:g.string().describe("The absolute path to the file to read"),offset:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional()).describe("Optional line number to start reading from (0-based index)"),limit:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional()).describe("Optional number of lines to read")}),g.object({content:g.union([g.string(),g.instanceof(Buffer)]),contentType:g.enum(["text","binary"]),fileType:g.string(),size:g.number(),linesRead:g.number().optional()}),yi=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:s}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new yi("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=e.normalize(n);try{await $.access(o,w.constants.F_OK|w.constants.R_OK)}catch{throw new yi(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await $.stat(o)).isFile())throw new yi("Path does not point to a file","NOT_A_FILE");const i=getFileType(o),a=isBinaryFile(i);if(void 0!==r&&void 0===s||void 0===r&&void 0!==s)throw new yi("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new yi("Offset must be >= 0","INVALID_OFFSET");if(void 0!==s&&s<=0)throw new yi("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await $.readFile(o);return{fileType:i,content:e,size:e.length,contentType:"binary"}}if(void 0!==r&&void 0!==s){const e=await readTextFileLines(o,r,s);return{fileType:i,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await $.readFile(o,"utf8");return{content:e,fileType:i,contentType:"text",size:e.length}}}catch(e){if(e instanceof yi)throw e;throw new yi(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}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",...wi}[n]||"unknown"}function isBinaryFile(e){return Object.values(wi).includes(e)}async function readTextFileLines(e,t,n){const r=(await $.readFile(e,"utf8")).split(/\r?\n/),s=t,o=Math.min(s+n,r.length),i=r.slice(s,o);return{content:i.join("\n"),linesRead:i.length}}var Ei=__esm({"src/tools/read-file/read-file.ts"(){Nt(),Si(),bi(),__name(readFileContent,"readFileContent"),wi={".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"},__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines")}});async function processFileReferences(t){const n=[];let r=t;const s=[...t.matchAll(/@([^\s@]+)/g)];for(const t of s){const s=t[0],o=t[1];try{const t=e.isAbsolute(o)?o:e.resolve(process.cwd(),o),i=await readFileContent({absolutePath:t});if("binary"===i.contentType)continue;const a=String(i.content),l=e.relative(process.cwd(),t),u=1e5;if(a.length>u){n.push({token:s,resolvedPath:t,content:"",tooLarge:!0});const e=`${l}`;r=r.replace(s,e);continue}n.push({token:s,resolvedPath:t,content:a});const d=`{${l}: ${a}}`;r=r.replace(s,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}var Ci=__esm({"src/utils/file-references.ts"(){Nt(),Ei(),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent")}});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")}var vi,Ti,ki,_i,Pi,Ai=__esm({"src/tools/read-file/formatter.ts"(){Nt(),__name(formatOutput,"formatOutput")}}),xi=__esm({"src/tools/read-file/index.ts"(){Nt(),bi(),Ei(),Ai(),vi={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=fi.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading file"}},"execute")}}}),Ii=__esm({"src/tools/edit-file/types.ts"(){Nt(),Ti=g.object({filePath:g.string().describe("The absolute path to the file to edit"),oldValue:g.string().describe("The text to replace"),newValue:g.string().describe("The new text to insert"),replacementCount:g.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:g.boolean().optional().describe("Whether to replace all occurrences (default: false)")}),g.object({path:g.string(),replacementsCount:g.number(),oldContent:g.string(),newContent:g.string()}),g.object({name:g.string(),message:g.string(),code:g.string().optional()})}}),Ni=__esm({"src/lib/checkpoints/types.ts"(){Nt(),ki=g.object({backupFileName:g.string().nullable(),version:g.number().int().positive(),backupTime:g.string().datetime()}),_i=g.object({messageId:g.string().uuid(),trackedFileBackups:g.record(g.string(),ki),timestamp:g.string().datetime()}),g.object({type:g.literal("file-history-snapshot"),messageId:g.string().uuid(),snapshot:_i,isSnapshotUpdate:g.boolean()}),g.object({maxFileSize:g.number().int().positive().default(10485760),retentionDays:g.number().int().positive().default(30)}),Pi=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`${j.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(f.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 L.statfs(t);return e.bavail*e.bsize}catch{return-1}}async function hasEnoughDiskSpace(e){const{fileSizeBytes:t,targetPath:n}=e,r=2*t,s=await getAvailableDiskSpace({targetPath:n});return-1===s||s>=r}async function ensureDirectoryExists(e){const{dirPath:t}=e;await L.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await L.writeFile(r,n);const e=await L.stat(r),s="string"==typeof n?Buffer.byteLength(n,"utf-8"):n.length;if(e.size!==s)throw new Error(`Write verification failed: expected ${s} bytes, got ${e.size}`);await L.rename(r,t)}catch(e){try{await L.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await L.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await L.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),s=Math.floor(r/60),o=Math.floor(s/60),i=Math.floor(o/24);return i>0?`${i}d ago`:o>0?`${o}h ago`:s>0?`${s}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}var Ri,$i,Li,Mi,Oi=__esm({"src/lib/checkpoints/utils.ts"(){Nt(),Ot(),__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(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod")}}),Di=__esm({"src/lib/checkpoints/file-history.ts"(){Nt(),Ni(),Oi(),Vr(),Ri={maxFileSize:10485760,retentionDays:30},$i=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Ri,...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 L.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,s=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const o=getBackupFilePath({sessionId:this.sessionId,backupFileName:s});await atomicWriteFile({filePath:o,content:e});const i={backupFileName:s,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,i),this.trackedState.versions.set(t,n),{success:!0,backup:i,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:Br.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 L.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new Pi(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:Br.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const s=await L.readFile(r);await atomicWriteFile({filePath:t,content:s})}async verifyRestoreOperation(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName){if(!await fileExists({filePath:t}))return{canRestore:!0};try{return await L.access(t,L.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 L.readdir(n);for(const s of e)if(!s.endsWith(".tmp")&&!t.has(s))try{await L.unlink(`${n}/${s}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await L.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}}}}),qi=__esm({"src/lib/checkpoints/checkpoint-manager.ts"(){Nt(),Di(),Oi(),jr(),Vr(),Li=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new $i({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||{},s={};for(const[e,n]of Object.entries(t)){const t=r[e];(!t||t.version!==n.version||t.backupFileName!==n.backupFileName)&&(s[e]=n)}e.trackedFileBackups=s,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=truncateString({text:t.content,maxChars:100}))}const s=Object.keys(n.trackedFileBackups);let o=null;if(s.length>0){const e=s[0];n.trackedFileBackups[e]&&(o={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:s,codeChanges:o})}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 s=0,o=0,i=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:Br.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?o++:s++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(i=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 a=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&a.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&a.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:a}),{success:!0,filesRestored:s,filesDeleted:o,messagesRemoved:i}}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}}}});function initializeCheckpointService(e){const{sessionId:t}=e;return Mi=new Li({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return Mi?Mi.backupFile({filePath:t}):{success:!0,backup:null}}var Fi=__esm({"src/lib/checkpoints/checkpoint-service.ts"(){Nt(),qi(),Mi=null,__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit")}}),ji=__esm({"src/lib/checkpoints/index.ts"(){Nt(),Ni(),Di(),qi(),Oi(),Fi()}});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:s,replaceAll:o=!1,replacementCount:i=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==s)throw createFileEditError("newValue is required","INVALID_INPUT");if(!o&&i<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await P.access(n,A.F_OK|A.R_OK|A.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${n}`,"FILE_ACCESS_ERROR")}let a;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");a=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const l=(a.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===l)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let u,d;if(o)u=l;else if(u=i,u>l)throw createFileEditError(`Expected ${u} replacements, but only found ${l} occurrences`,"INSUFFICIENT_MATCHES");let m=0;if(o||u===l)d=a.split(r).join(s),m=l;else{d=a;for(let e=0;e<u;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+s+d.substring(e+r.length),m++)}}if(0===m)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await P.writeFile(n,d,"utf-8"),{path:n,replacementsCount:m,oldContent:a,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,"\\$&")}var zi=__esm({"src/tools/edit-file/edit-file.ts"(){Nt(),Ei(),Si(),Ii(),ji(),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp")}});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}var Bi,Ui,Wi,Qi=__esm({"src/tools/edit-file/formatter.ts"(){Nt(),__name(formatOutput2,"formatOutput")}}),Gi=__esm({"src/tools/edit-file/index.ts"(){Nt(),Ii(),zi(),Qi(),Bi={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=Ti.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while editing file"}},"execute")}}}),Hi=__esm({"src/tools/read-directory/types.ts"(){Nt(),Ui=g.object({path:g.string().describe("The absolute path to the directory to read"),exclude:g.array(g.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:g.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")}),g.object({files:g.array(g.string()),directories:g.array(g.string())}),Wi=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:s=!1}=t;if(!e.isAbsolute(n))throw new Wi("Path must be absolute, not relative","INVALID_PATH");try{if(!(await $.stat(n)).isDirectory())throw new Wi("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Wi)throw e;throw new Wi(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await $.readdir(n);let o=[];s&&(o=await loadGitIgnorePatterns(n));const i=[...r,...o],a=[],l=[];for(const r of t){if(shouldIgnoreEntry(r,i))continue;const t=e.join(n,r);try{const e=await $.stat(t);e.isDirectory()?l.push(r):e.isFile()&&a.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:a.sort(),directories:l.sort()}}catch(e){if(e instanceof Wi)throw e;throw new Wi(`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 s=await findGitRoot(t);for(;r&&isWithinGitRoot(r,s);){const t=e.join(r,".gitignore");try{const e=(await $.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch(e){}const s=e.dirname(r);if(s===r)break;r=s}}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 $.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),s=e.resolve(n);return"win32"===process.platform?r.toLowerCase().startsWith(s.toLowerCase()):r.startsWith(s)}function shouldIgnoreEntry(e,t){for(const n of t)if(Le(e,n))return!0;return!1}var Vi=__esm({"src/tools/read-directory/read-directory.ts"(){Nt(),Hi(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry")}});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")}var Ki,Yi,Ji=__esm({"src/tools/read-directory/formatter.ts"(){Nt(),__name(formatOutput3,"formatOutput")}}),Xi=__esm({"src/tools/read-directory/index.ts"(){Nt(),Hi(),Vi(),Ji(),Ki={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=Ui.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading directory"}},"execute")}}}),Zi=__esm({"src/tools/write-file/types.ts"(){Nt(),Yi=g.object({filePath:g.string().describe("The absolute path where the file should be written"),content:g.string().describe("The content to write to the file")}),g.object({success:g.boolean(),message:g.string(),path:g.string().optional()})}});async function writeFile4({filePath:e,content:n}){const s=e.startsWith("~/")?t.join(f.homedir(),e.slice(2)):e;if(!l(s))throw new Error(`Invalid file path: '${s}'. Only absolute paths are supported.`);try{const e=r(s);return E(e)||await q(e,{recursive:!0}),await backupFileBeforeEdit({filePath:s}),await M(s,n,"utf-8"),{path:s,bytesWritten:Buffer.byteLength(n,"utf-8")}}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";throw new Error(`Failed to write file '${s}': ${t}`)}}var ea=__esm({"src/tools/write-file/write-file.ts"(){Nt(),ji(),__name(writeFile4,"writeFile")}});function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}var ta,na,ra,sa,oa,ia=__esm({"src/tools/write-file/formatter.ts"(){Nt(),__name(formatOutput4,"formatOutput")}}),aa=__esm({"src/tools/write-file/index.ts"(){Nt(),Zi(),ea(),ia(),ta={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=Yi.parse(e),n=await writeFile4(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")}}}),la=__esm({"src/tools/read-multiple-files/types.ts"(){Nt(),na=g.object({include:g.array(g.string()).describe("Array of glob patterns to include files"),exclude:g.array(g.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:g.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:g.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:g.string().optional().describe("Base directory for relative paths. Default: current working directory")}),ra=g.object({filePath:g.string(),content:g.string(),fileType:g.string(),size:g.number()}),g.object({content:g.string(),filesRead:g.array(g.string()),errors:g.array(g.object({file:g.string(),error:g.string()})),fileDetails:g.array(ra)}),sa=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}}}});async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const s=new Set;for(const o of e)try{(await Me(o,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>s.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${o}": ${e}`)}return Array.from(s).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:s=!0,defaultExclude:o=!0,targetDirectory:i=process.cwd()}=e;if(!n||0===n.length)throw new sa("At least one include pattern must be provided","NO_PATTERNS");const a=t.resolve(i),l={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];o&&e.push(...oa);const i=await findMatchingFiles({include:n,exclude:e,gitIgnore:s,targetDirectory:a});for(const e of i)try{const n=t.resolve(a,e),r=await readFileContent({absolutePath:n}),s=processFileResult({content:r,filePath:e});l.fileDetails.push(s),l.content+=`\n// File: ${e} (${r.fileType})\n`,l.content+=s.content,l.content+="\n",l.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);l.errors.push({file:e,error:n}),l.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return l}catch(e){if(e instanceof sa)throw e;throw new sa(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}var ca=__esm({"src/tools/read-multiple-files/read-multiple-files.ts"(){Nt(),Ei(),la(),oa=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles")}});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")}var ua,da,ma=__esm({"src/tools/read-multiple-files/formatter.ts"(){Nt(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput")}}),pa=__esm({"src/tools/read-multiple-files/index.ts"(){Nt(),la(),ca(),ma(),ua={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=na.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading multiple files"}},"execute")}}}),ga=__esm({"src/tools/grep/types.ts"(){Nt(),da=g.object({pattern:g.string().min(1,"Pattern is required"),include:g.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},g.array(g.string()).optional()),directory:g.string().optional()})}});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const s=N(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let o="",i="";s.stdout?.on("data",e=>{try{const t=e.toString();if(o.length+t.length>Mr)return i="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",void s.kill("SIGTERM");o+=t}catch(e){i+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,s.kill("SIGTERM")}}),s.stderr?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>Or)return void(i+="\n[Error output truncated: too large]");i+=t}catch(e){i+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),s.on("close",e=>{0===e?n(o):1!==e||i?r(new Error(i||`Command failed with exit code ${e}`)):n("")}),s.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,s]=t;return{file:n,line:parseInt(r,10),column:1,content:s.trim(),match:s.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",s=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)s.splice(-1,0,"--glob",e);s.splice(-1,0,"--glob","!node_modules/**"),s.splice(-1,0,"--glob","!.git/**"),s.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:s,command:"rg"})}catch(o){if(!(o instanceof Error&&o.message.includes("ENOENT")))throw o;if(r="grep",s=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)s.splice(-1,0,"--include",e);s.splice(-1,0,"--exclude-dir=node_modules"),s.splice(-1,0,"--exclude-dir=.git"),s.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:s,command:"grep"})}if(!e.trim())return[];const o=e.trim().split("\n"),i=[];for(const e of o){const t=parseGrepLine(e);t&&i.push(t)}return i}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}var ha=__esm({"src/tools/grep/grep.ts"(){Nt(),jr(),__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory")}});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,s=Object.keys(t).length;n.push(`Found ${r} matches in ${s} 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")}var fa,ya,wa,Sa=__esm({"src/tools/grep/formatter.ts"(){Nt(),__name(formatGrepResults,"formatGrepResults")}}),ba=__esm({"src/tools/grep/index.ts"(){Nt(),ga(),ha(),Sa(),fa={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=da.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while searching files"}},"execute")}}}),Ea=__esm({"src/tools/glob/types.ts"(){Nt(),ya=g.object({pattern:g.string().min(1,"Pattern is required"),path:g.string().optional()}),wa=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 wa("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new wa("Search path must be within the current working directory or an added directory","INVALID_PATH");const s=await Me(n,{cwd:e,ignore:Pt,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),o=await Promise.all(s.map(async n=>{const r=t.join(e,n);try{return{file:n,mtime:(await L.stat(r)).mtimeMs}}catch{return{file:n,mtime:0}}}));return o.sort((e,t)=>t.mtime-e.mtime),{files:o.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof wa)throw e;if(e instanceof Error)throw new wa(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new wa("Unknown error occurred during file search","UNKNOWN_ERROR")}}var Ca=__esm({"src/tools/glob/glob.ts"(){Nt(),Ea(),Ot(),zt(),__name(globSearch,"globSearch")}});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")}var va,Ta,ka,_a=__esm({"src/tools/glob/formatter.ts"(){Nt(),__name(formatGlobResults,"formatGlobResults")}}),Pa=__esm({"src/tools/glob/index.ts"(){Nt(),Ea(),Ca(),_a(),va={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=ya.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while finding files"}},"execute")}}}),Aa=__esm({"src/tools/shell-command/types.ts"(){Nt(),Ta=g.object({command:g.string().min(1,"Command cannot be empty"),args:g.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},g.array(g.string()).optional()),directory:g.string().optional(),timeout:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional())}),ka=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,s,o,i){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=s,this.stderr=o,this.duration=i}}}});async function executeShellCommand(t){const{command:n,args:r=[],directory:s,timeout:o=3e4}=t,i=Date.now();if(!n.trim())throw new ka("Command cannot be empty","EMPTY_COMMAND");let a;if(s){if(e.isAbsolute(s))throw new ka("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");a=e.resolve(process.cwd(),s)}else a=process.cwd();try{if(!(await L.stat(a)).isDirectory())throw new ka(`Path is not a directory: ${s}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof ka)throw e;throw new ka(`Directory does not exist or is not accessible: ${s||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:a,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((t,s)=>{let a="",l="",u=!1;const d=r.length>0?Oe([n,...r]):n,m=setTimeout(()=>{if(!u){p.kill("SIGTERM");const e=Date.now()-i;s(new ka(`Command timed out after ${o}ms`,"TIMEOUT",null,"SIGTERM",a,l,e))}},o),p=N(d,[],e);p.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>Mr)return l="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void p.kill("SIGTERM");a+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,p.kill("SIGTERM")}}),p.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>Or)return void(l+="\n[Error output truncated: too large]");l+=t}catch(e){l+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),p.on("close",(e,n)=>{u=!0,clearTimeout(m);const r=Date.now()-i;0===e?t({stdout:a.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):s(new ka(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,a.trim(),l.trim(),r))}),p.on("error",e=>{u=!0,clearTimeout(m);const t=Date.now()-i;s(new ka(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),l.trim(),t))})})}catch(e){if(e instanceof ka)throw e;throw new ka(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}var xa=__esm({"src/tools/shell-command/shell-command.ts"(){Nt(),Aa(),jr(),__name(executeShellCommand,"executeShellCommand")}});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")}var Ia,Na=__esm({"src/tools/shell-command/formatter.ts"(){Nt(),__name(formatShellCommandResult,"formatShellCommandResult")}}),Ra=__esm({"src/tools/shell-command/index.ts"(){Nt(),Aa(),xa(),Na(),Ia={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=Ta.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`ERROR: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`ERROR: ${e.message}`}return"ERROR: Unknown error occurred while executing command"}},"execute")}}});async function think(e){const{thought:t}=e;return`${t}`}var $a,La=__esm({"src/tools/thinking/thinking.ts"(){Nt(),__name(think,"think")}}),Ma=__esm({"src/tools/thinking/index.ts"(){Nt(),La(),$a={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)}var Oa,Da=__esm({"src/tools/todo-write/todo-write.ts"(){Nt(),__name(todoWrite,"todoWrite")}}),qa=__esm({"src/tools/todo-write/index.ts"(){Nt(),Da(),Oa={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){const n=e.questions;if("string"==typeof n)try{const t=n.replace(/,\s*([}\]])/g,"$1"),r=JSON.parse(t);if(!Array.isArray(r))return JSON.stringify({error:"The questions parameter must be an array of question objects, not a single object."});e.questions=r}catch{return JSON.stringify({error:"The questions parameter could not be parsed. Please provide questions as a valid JSON array."})}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`});n.header.length>20&&(n.header=n.header.slice(0,20).trimEnd())}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"})}}var Fa=__esm({"src/tools/ask-user-question/ask-user-question.ts"(){Nt(),__name(askUserQuestion,"askUserQuestion")}});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 s=[];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(", ");s.push(`${t} → ${r}`)}),s.join("\n")}var ja,za,Ba,Ua=__esm({"src/tools/ask-user-question/formatter.ts"(){Nt(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput")}}),Wa=__esm({"src/tools/ask-user-question/index.ts"(){Nt(),Fa(),Ua(),Ua(),ja={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 20 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")}}}),Qa=__esm({"src/tools/killshell/types.ts"(){Nt(),za=g.object({port:g.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:g.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"}),Ba=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 s=N(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let o="",i="";s.stdout?.on("data",e=>{o+=e.toString()}),s.stderr?.on("data",e=>{i+=e.toString()}),s.on("close",e=>{0===e?n(o.trim()):r(new Error(i.trim()||o.trim()))}),s.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 s=r[1].match(/:(\d+)$/);if(!s)continue;const o=parseInt(s[1],10);if(isNaN(o)||o!==e)continue;const i=parseInt(r[r.length-1],10);if(!isNaN(i))return i}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 Ba(`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 Ba("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 Ba(`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}}var Ga=__esm({"src/tools/killshell/killshell.ts"(){Nt(),Qa(),__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")}});function formatKillshellResult(e){const t=[];return t.push(`${be.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}var Ha,Va,Ka,Ya,Ja,Xa,Za,el,tl,nl,rl,sl,ol,il,al,ll,cl,ul,dl,ml=__esm({"src/tools/killshell/formatter.ts"(){Nt(),__name(formatKillshellResult,"formatKillshellResult")}}),pl=__esm({"src/tools/killshell/index.ts"(){Nt(),Qa(),Ga(),ml(),Ha={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=za.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?"ERROR: Permission denied — Process termination was not approved":formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while killing process"}},"execute")}}}),gl=__esm({"src/tools/exit-plan-mode/index.ts"(){Nt(),Va={name:"exit_plan_mode",description:'Call this tool when your plan is complete and ready for user approval.\n\nThis will:\n1. Ask the user if they want to exit plan mode and begin implementation\n2. If user says "Yes": Exit plan mode and begin implementation\n3. If user says "No": Stay in plan mode for further refinement\n\nUsage:\n- Call this AFTER writing the plan file\n- Call this AFTER asking any clarifying questions\n- This is the FINAL step in plan mode\n\nIMPORTANT: Call this tool ALONE — do not combine it with other tool calls in the same message. It switches your mode and system prompt.\n\nDO NOT:\n- Call this before the plan is written\n- Call this multiple times\n- Ask "Ready to implement?" yourself - this tool does that',acceptsCallbacks:!0,input_schema:{type:"object",properties:{},required:[]},execute:__name(async(e,t)=>{if(!t?.onQuestionRequest)return JSON.stringify({error:"Question callback not available"});const n=await t.onQuestionRequest({questions:[{question:"Exit plan mode and begin implementation?",header:"Exit Plan",options:[{label:"Yes, auto-accept",description:"Exit plan mode and implement with auto-accept (no permission prompts)"},{label:"Yes, exit",description:"Exit plan mode and implement with manual approval for each change"},{label:"Cancel",description:"Stay in plan mode to refine the plan further"}],multiSelect:!1}],hideCustomInput:!0,exitPlanMode:!0}),r=n?.answers?.[0]?.selectedOptions?.[0]||"";return r.startsWith("Yes, auto-accept")?"Exited plan mode. Now in auto-accept mode.":r.startsWith("Yes, exit")?"Exited plan mode. Now in standard mode.":"Staying in plan mode. Continue refining the plan."},"execute")}}}),hl=__esm({"src/tools/enter-plan-mode/index.ts"(){Nt(),Ka={name:"enter_plan_mode",description:'Call this tool to enter plan mode for read-only exploration and structured planning.\n\nThis will:\n1. Ask the user if they want to enter plan mode\n2. If user says "Yes": Switch to plan mode (read-only exploration and planning)\n3. If user says "No": Stay in current mode\n\nWHEN TO CALL:\n- User explicitly asks to "plan", "design", or "explore"\n- Task requires understanding multiple files/systems you haven\'t read yet\n- Task involves architectural decisions or spans 3+ files\n- You need to research the codebase before you can implement effectively\n- You\'re unsure about the right approach\n\nIMPORTANT: Call this tool ALONE — do not combine it with other tool calls in the same message. It switches your mode and system prompt, so other tools in the same message would run under the wrong mode.\n\nDO NOT:\n- Call this if already in plan mode\n- Call this for simple, well-defined tasks where you know exactly what to do',acceptsCallbacks:!0,input_schema:{type:"object",properties:{},required:[]},execute:__name(async(e,t)=>{if(!t?.onQuestionRequest)return JSON.stringify({error:"Question callback not available"});const n=await t.onQuestionRequest({questions:[{question:"Enter plan mode for read-only exploration and planning?",header:"Plan Mode",options:[{label:"Yes (Recommended)",description:"Switch to plan mode — explore codebase and create an implementation plan"},{label:"No, stay in current mode",description:"Continue without entering plan mode"}],multiSelect:!1}],hideCustomInput:!0,enterPlanMode:!0});return(n?.answers?.[0]?.selectedOptions?.[0]||"").startsWith("Yes")?"User approved. Entered plan mode. Begin exploring the codebase to understand the task.":"User chose to stay in current mode. Proceed normally."},"execute")}}}),fl=__esm({"src/tools/web-search/index.ts"(){Nt(),Ya={type:"web_search_20250305",name:"web_search",max_uses:5}}}),yl=__esm({"src/tools/web-fetch/index.ts"(){Nt(),Ja={type:"web_fetch_20250910",name:"web_fetch"}}}),wl=__esm({"src/tools/get-diagnostics/types.ts"(){Nt(),Xa=g.preprocess(e=>{if("string"==typeof e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{return[e]}return e},g.array(g.string()).optional()),Za=g.object({filePaths:Xa.describe('Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.')})}}),Sl=__esm({"src/tui/vscode-context/ipc-client.ts"(){Nt(),$n(),el=t.join(f.homedir(),".commandcode","ide"),tl=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),nl=__name(e=>{if("win32"===process.platform)return null;try{const t=I(`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"),rl=__name((e,t,n=nl)=>{const r=new Map;for(const t of e)r.set(t.session.pid,t);let s=t;for(let e=0;e<10&&null!==s;e++){const e=r.get(s);if(e)return e;s=n(s)}return null},"findAncestorSession"),sl=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),ol=__name((e,n)=>{try{S.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{S.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),il=__name((e,n={})=>{const{sessionDir:r=el,parentPidFn:s=nl,startPid:o=process.ppid}=n;try{if(!S.existsSync(r))return null;const n=`${e}-`,i=S.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),a=[];for(const e of i)try{const n=t.join(r,e),s=JSON.parse(S.readFileSync(n,"utf-8"));if(!tl(s.pid)){ol(n,r);continue}a.push({session:s,file:e})}catch{continue}if(0===a.length)return null;const l=rl(a,o,s);if(l)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:l.session.socketPath,ideName:l.session.ideName}),l.session.socketPath;const u=process.cwd();let d=null,m=0;for(const{session:e}of a)for(const n of e.workspaceFolders)(u===n||u.startsWith(n+t.sep))&&n.length>m&&(d=e,m=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"),al=__name(()=>{const e=sl();return e?il(e):null},"resolveSocketPath"),ll=__name(()=>({type:"request",id:z(),payload:{action:"getContext"}}),"createContextRequest"),cl=__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"),ul=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!cl(n))return dlog("[VSCode:IPC] Invalid message structure"),null;if("response"!==n.type)return null;if(n.id!==t)return null;const r=n.payload;return"object"!=typeof r||null===r?null:r}catch{return null}},"parseResponse"),dl=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??al()}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;dlog("[VSCode:IPC] Connecting to socket",{path:t,timeout:e});try{return await new Promise(n=>{try{const r=we.connect(t);this.socket=r;const s=__name(()=>{r.off("error",o)},"cleanup"),o=__name(e=>{clearTimeout(i),s(),this.connected=!1,dlog("[VSCode:IPC] Connection error",{error:e.message}),n(!1)},"handleError"),i=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),s(),r.destroy(),n(!1)},e);r.on("connect",()=>{try{if(clearTimeout(i),s(),this.socket!==r)return r.destroy(),void n(!1);this.connected=!0,dlog("[VSCode:IPC] Connected successfully"),r.on("close",()=>{this.connected=!1}),r.on("error",()=>{this.connected=!1}),n(!0)}catch(e){dlog("[VSCode:IPC] Error in connect handler",{error:e}),r.destroy(),n(!1)}}),r.on("error",o)}catch(e){dlog("[VSCode:IPC] Connection exception",{error:e}),n(!1)}})}catch{return!1}}async getContext(e=5e3){try{const t=this.socket;if(!t||!this.connected)return dlog("[VSCode:IPC] Cannot get context - not connected"),null;const n=ll();return await new Promise(r=>{const s=__name(()=>{t.off("data",a),t.off("error",l)},"cleanup"),o=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),s(),r(null)},e);let i="";const a=__name(e=>{try{i+=e.toString();const t=i.indexOf("\n");if(-1===t)return;clearTimeout(o),s();const a=i.slice(0,t),l=ul(Buffer.from(a),n.id);l||dlog("[VSCode:IPC] Invalid response received"),r(l)}catch(e){clearTimeout(o),s(),dlog("[VSCode:IPC] Error processing response",{error:e}),r(null)}},"handleData"),l=__name(e=>{clearTimeout(o),s(),dlog("[VSCode:IPC] Socket error during request",{error:e.message}),r(null)},"handleError");t.on("data",a),t.on("error",l);try{t.write(JSON.stringify(n)+"\n")}catch(e){clearTimeout(o),s(),dlog("[VSCode:IPC] Failed to send request",{error:e}),r(null)}})}catch{return null}}async getDiagnostics(e={}){const{filePaths:t,timeout:n=5e3}=e,r=this.socket;if(!r||!this.connected)return dlog("[VSCode:IPC] Cannot get diagnostics - not connected"),null;const s={type:"request",id:z(),payload:{action:"getDiagnostics",filePaths:t}};return new Promise(e=>{const t=__name(()=>{r.off("data",a),r.off("error",l)},"cleanup"),o=setTimeout(()=>{dlog("[VSCode:IPC] Diagnostics request timeout"),t(),e(null)},n);let i="";const a=__name(n=>{for(i+=n.toString();;){const n=i.indexOf("\n");if(-1===n)return;const r=i.slice(0,n);if(i=i.slice(n+1),r.trim())try{const n=JSON.parse(r);if(n.id!==s.id){dlog("[VSCode:IPC] Ignoring diagnostics response for different request id");continue}return clearTimeout(o),t(),void("response"===n.type&&n.payload?.diagnostics?e(n.payload.diagnostics):"error"===n.type?(dlog("[VSCode:IPC] Diagnostics error response",{message:n.payload?.message,code:n.payload?.code}),e(null)):(dlog("[VSCode:IPC] Invalid diagnostics response"),e(null)))}catch(e){dlog("[VSCode:IPC] Failed to parse diagnostics response line",{error:e})}}},"handleData"),l=__name(n=>{clearTimeout(o),t(),dlog("[VSCode:IPC] Socket error during diagnostics request",{error:n.message}),e(null)},"handleError");r.on("data",a),r.on("error",l);try{r.write(JSON.stringify(s)+"\n")}catch(n){clearTimeout(o),t(),dlog("[VSCode:IPC] Failed to send diagnostics request",{error:n}),e(null)}})}disconnect(){if(this.socket){dlog("[VSCode:IPC] Disconnecting");try{this.socket.end()}catch{}this.socket=null,this.connected=!1}}static async isAvailable(e=1e3){try{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}catch{return!1}}}}});async function fetchDiagnostics(e){if(!sl())throw new Error("Not running inside an IDE terminal. The diagnostics tool requires the Command Code VS Code extension.");const n=e?.map(e=>t.resolve(e)),r=new dl;try{if(!await r.connect())throw new Error("Could not connect to IDE extension. Make sure the Command Code extension is installed and active.");const e=await r.getDiagnostics({filePaths:n,timeout:5e3});if(null===e)throw new Error("Failed to get diagnostics from IDE.");return dlog("[diagnostics] Fetched diagnostics",{fileCount:e.length,total:e.reduce((e,t)=>e+t.diagnostics.length,0)}),e}finally{r.disconnect()}}var bl=__esm({"src/tools/get-diagnostics/get-diagnostics.ts"(){Nt(),Sl(),$n(),__name(fetchDiagnostics,"fetchDiagnostics")}});function formatDiagnostics(e){if(0===e.length)return"No diagnostics found. All files are clean.";const t=[];let n=0,r=0,s=0,o=0;for(const i of e){t.push(`${i.relativePath}:`);for(const e of i.diagnostics){const i=`L${e.range.startLine}:${e.range.startCol}`,a=e.code?` ${e.code}`:"",l=e.source?` [${e.source}]`:"";switch(t.push(` ${i} ${e.severity}${a}: ${e.message}${l}`),e.severity){case"error":n++;break;case"warning":r++;break;case"information":s++;break;case"hint":o++}}t.push("")}const i=[];n>0&&i.push(`${n} error${1!==n?"s":""}`),r>0&&i.push(`${r} warning${1!==r?"s":""}`),s>0&&i.push(`${s} info`),o>0&&i.push(`${o} hint${1!==o?"s":""}`);const a=`${e.length} file${1!==e.length?"s":""}`;return t.push(`Summary: ${i.join(", ")} across ${a}`),t.join("\n")}var El,Cl,vl,Tl=__esm({"src/tools/get-diagnostics/formatter.ts"(){Nt(),__name(formatDiagnostics,"formatDiagnostics")}}),kl=__esm({"src/tools/get-diagnostics/index.ts"(){Nt(),wl(),bl(),Tl(),El={name:"diagnostics",description:"Get LSP diagnostics (errors, warnings, hints) from the IDE. Returns type errors, lint warnings, and other language server diagnostics reported by all active language servers (TypeScript, ESLint, Python, etc.). Only available when connected to an IDE with the Command Code extension. Pass specific file paths when you know which files are relevant. Only omit filePaths to scan the entire workspace when the user explicitly asks for all workspace diagnostics.",input_schema:{type:"object",properties:{filePaths:{type:"array",items:{type:"string"},description:'Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.'}},required:[]},execute:__name(async e=>{const t=Za.parse(e);return formatDiagnostics(await fetchDiagnostics(t.filePaths))},"execute")}}}),_l=__esm({"src/tools/agents/defaults.ts"(){Nt(),Cl=["explore","plan","review","general"],vl=[{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__"},{name:"plan",description:"Use this to design implementation approaches by synthesizing exploration findings and considering architectural trade-offs",tools:"read_file, read_multiple_files, think",systemPrompt:"You are an implementation planner and software architect. You receive findings from exploration and design the implementation approach.\n\nTOOLS AVAILABLE:\n- read_file: Read specific files for detailed analysis\n- read_multiple_files: Read many files efficiently\n- think: Reason through design decisions\n\nYOUR ROLE:\n1. Synthesize findings from exploration agents\n2. Identify possible implementation approaches\n3. Consider architectural trade-offs and implications\n4. Determine what clarifications are needed from the user\n5. Design the optimal approach based on existing patterns\n\nDESIGN PROCESS:\n1. Review exploration findings to understand current architecture\n2. Identify 2-4 possible approaches for the task\n3. For each approach, consider:\n - How well it fits existing patterns\n - Complexity vs benefits\n - Risks and potential issues\n - What needs to be modified\n4. Determine if user clarification is needed (approach choice, scope, preferences)\n5. Recommend an approach with clear rationale\n\nOUTPUT FORMAT:\nProvide a structured analysis:\n- **Current Architecture**: Summary of relevant findings\n- **Possible Approaches**: 2-4 options with pros/cons\n- **Recommended Approach**: Your suggestion with rationale\n- **Clarifications Needed**: Questions for the user (if any)\n- **Implementation Outline**: High-level steps for the recommended approach\n\nBe concise but thorough. Focus on actionable design decisions.",location:"personal",filePath:"__builtin__"}]}});function isReservedAgentName(e){return!!e&&Cl.includes(e.toLowerCase())}var Pl=__esm({"src/tools/agents/utils.ts"(){Nt(),_l(),__name(isReservedAgentName,"isReservedAgentName")}});function getRootAgentDir(){return t.join(f.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await L.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await L.readFile(s,"utf-8"),{data:i,content:a}=$e(o),l=i.name||r.replace(".md","");if(isReservedAgentName(l))return null;let u=i.tools||"";return"*"!==u&&'"*"'!==u||(u="*"),{name:l,description:i.description||"",tools:u,systemPrompt:a.trim(),location:n,filePath:s}}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}}var Al,xl,Il,Nl,Rl,$l,Ll,Ml,Ol,Dl,ql,Fl=__esm({"src/tools/agents/loader.ts"(){Nt(),Ot(),Pl(),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents")}}),jl=__esm({"../shared/src/types/share.ts"(){Nt(),Al=g.object({messageId:g.string().optional(),timestamp:g.string(),model:g.string().optional(),duration:g.number().optional(),usage:g.object({inputTokens:g.number(),outputTokens:g.number(),totalTokens:g.number(),cacheReadTokens:g.number().optional(),cacheWriteTokens:g.number().optional(),estimatedCost:g.number().optional()}).optional(),source:g.string().optional(),context:g.object({sessionId:g.string().optional(),threadId:g.string().optional(),userId:g.string().optional()}).optional(),highlight:g.boolean().optional(),isSummary:g.boolean().optional()}),g.object({message:g.any(),meta:Al}),g.object({sessionId:g.string(),messages:g.array(g.any()).optional()}),g.object({secret:g.string(),url:g.string()}),g.object({sessionId:g.string(),secret:g.string()}),g.object({sessionId:g.string(),secret:g.string(),key:g.string(),content:g.any()}),g.object({sessionId:g.string(),secret:g.string(),message:g.any()}),g.object({shortId:g.string()}),g.object({info:g.any().optional(),messages:g.array(g.any())})}}),zl=__esm({"../shared/src/types/whoami.ts"(){Nt()}}),Bl=__esm({"../shared/src/types/email.ts"(){Nt(),g.object({to:g.union([g.email(),g.array(g.email())]),subject:g.string(),html:g.string().optional(),text:g.string().optional(),template:g.string().optional(),templateData:g.record(g.any(),g.any()).optional(),cc:g.array(g.email()).optional(),bcc:g.array(g.email()).optional(),replyTo:g.array(g.email()).optional(),tags:g.array(g.object({name:g.string(),value:g.string()})).optional()}),g.object({success:g.boolean(),messageId:g.string().optional(),error:g.string().optional()})}}),Ul=__esm({"../shared/src/types/billing.ts"(){Nt(),xl=g.enum(["active","canceled","incomplete","incomplete_expired","past_due","trialing","unpaid"]),Il=g.enum(["admin_grant","signup_credits","purchased_credits","subscription_credits"]),Nl=g.enum(["agent","learning","custom-agent","custom-agent-create"]),Rl=g.enum(["free","monthly","purchased"]),g.enum(["team","individual","enterprise"]),g.object({type:g.enum(["api","oauth"]).default("api"),orgId:g.string().nullable().optional(),model:g.string().min(1),userId:g.string().min(1),traceId:g.string(),provider:g.enum(["openai","anthropic","azure"]).default("anthropic"),tokensIn:g.number().min(0),tokensOut:g.number().min(0),inputCost:g.number().min(0),totalCost:g.number().min(0),outputCost:g.number().min(0),ownerLogin:g.string(),tokensTotal:g.number().min(0),creditsTotal:g.number().min(0),durationTotal:g.number().min(0),mode:Nl.nullable().optional(),cacheCost:g.number().min(0).optional(),cacheSavings:g.number().optional(),cacheCreation:g.object({ephemeral_5m_input_tokens:g.number().optional(),ephemeral_1h_input_tokens:g.number().optional()}).nullable().optional(),cacheCreationInputTokens:g.number().min(0).nullable().optional(),cacheReadInputTokens:g.number().min(0).nullable().optional(),threadId:g.string().nullable().optional(),messageInId:g.string().nullable().optional(),messageOutId:g.string().nullable().optional()}),g.object({success:g.boolean(),instanceId:g.string().optional(),error:g.string().optional()}),g.object({userId:g.string().min(1),orgId:g.string().nullable()}),g.object({credits:g.object({freeCredits:g.number(),belowThreshold:g.boolean(),monthlyCredits:g.number(),creditThreshold:g.number(),availableCredits:g.number(),purchasedCredits:g.number()})}),g.object({userId:g.string().min(1),orgId:g.string().nullable().optional()}),g.object({success:g.boolean(),data:g.object({id:g.string(),userId:g.uuid(),orgId:g.string().nullable(),stripeCustomerId:g.string(),autoCharge:g.boolean(),creditThreshold:g.string(),rechargeAmount:g.string(),monthlyCreditThreshold:g.string()}).optional(),error:g.string().optional()}),g.object({userId:g.string().min(1),orgId:g.string().nullable().optional(),autoCharge:g.boolean().optional(),rechargeAmount:g.number().min(0).optional(),creditThreshold:g.number().min(0).optional(),monthlyCreditThreshold:g.number().min(0).optional(),stripeCustomerId:g.string().optional()}),g.object({success:g.boolean(),data:g.object({id:g.string(),userId:g.uuid(),orgId:g.string().nullable(),stripeCustomerId:g.string(),autoCharge:g.boolean(),creditThreshold:g.string(),rechargeAmount:g.string()}).optional(),error:g.string().optional()}),g.object({userId:g.string().min(1),userEmail:g.email(),orgId:g.string().nullable().optional()}),g.object({success:g.boolean(),data:g.object({clientSecret:g.string(),customerId:g.string()}).optional(),error:g.string().optional(),message:g.string().optional()}),g.object({userId:g.string().min(1),orgId:g.string().nullable().optional()}),g.object({success:g.boolean(),data:g.object({hasPaymentMethod:g.boolean(),paymentMethods:g.array(g.object({id:g.string(),brand:g.string().optional(),last4:g.string().optional(),expMonth:g.number().optional(),expYear:g.number().optional(),default:g.boolean()})),customerId:g.string().optional()}).optional(),error:g.string().optional()}),g.object({userId:g.string().min(1),paymentMethodId:g.string().min(1),orgId:g.string().nullable().optional()}),g.object({success:g.boolean(),error:g.string().optional()}),g.object({userId:g.string().min(1),orgId:g.string().nullable().optional(),customerId:g.string().min(1),paymentMethodId:g.string().min(1)}),g.object({success:g.boolean(),message:g.string().optional(),error:g.string().optional()}),g.object({body:g.string(),signature:g.string()}),g.object({success:g.boolean(),received:g.boolean().optional(),error:g.string().optional()}),g.object({orgId:g.string().nullable().optional(),amount:g.number().min(0),credits:g.number().min(0),userEmail:g.email(),creditType:Rl.optional(),invoiceType:Il}),g.object({success:g.boolean(),message:g.string().optional(),error:g.string().optional()}),g.object({orgId:g.string().nullable(),limit:g.number().min(1).max(100).default(10),userId:g.string().min(1),startingAfter:g.string().optional()}),g.object({success:g.boolean(),data:g.object({invoices:g.array(g.object({id:g.string(),status:g.enum(["paid"]),invoicePdf:g.url().nullable(),amountPaid:g.number(),currency:g.string(),credits:g.string(),autoCharged:g.boolean(),createdAt:g.string(),invoiceType:Il})),hasMore:g.boolean()}).optional(),error:g.string().optional()}),g.object({userId:g.uuid(),orgId:g.uuid().nullable().optional()}),g.object({success:g.boolean(),data:g.object({id:g.string(),orgId:g.string().nullable(),userId:g.string().nullable(),status:xl,planId:g.string(),priceId:g.string(),quantity:g.number(),currentPeriodEnd:g.string(),cancelAtPeriodEnd:g.boolean(),currentPeriodStart:g.string()}).nullable(),error:g.string().optional()}),g.object({success:g.boolean(),data:g.object({totalGiven:g.number(),limit:g.number(),remaining:g.number()}).optional(),error:g.string().optional()}),g.object({amount:g.number().min(0)}),g.object({success:g.boolean(),totalGiven:g.number().optional(),exceeded:g.boolean().optional(),error:g.string().optional()})}}),Wl=__esm({"../shared/src/types/templates.ts"(){Nt()}}),Ql=__esm({"../shared/src/types/auth.types.ts"(){Nt()}}),Gl=__esm({"../shared/src/types/keys.types.ts"(){Nt()}}),Hl=__esm({"../shared/src/types/orgs.types.ts"(){Nt()}}),Vl=__esm({"../shared/src/types/usage.ts"(){Nt()}}),Kl=__esm({"../shared/src/types/cli-auth.types.ts"(){Nt()}}),Yl=__esm({"../shared/src/types/index.ts"(){Nt(),jl(),Bl(),Ul(),Wl(),Ql(),Gl(),Hl(),Vl(),ti(),Kl()}}),Jl=__esm({"../shared/src/utils/path-sanitizer.ts"(){Nt(),$l=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))}}}}),Xl=__esm({"../shared/src/utils/calculate-cost.ts"(){Nt(),Ot()}});function cachedError(e){if(Ll.has(e))return Ll.get(e);const t=Error.stackTraceLimit;return Error.stackTraceLimit=4,Ll.set(e,new Error),Error.stackTraceLimit=t,Ll.get(e)}var Zl,ec,tc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/query.js"(){Nt(),Ll=new Map,Ml=new Map,Ol=Symbol("OriginError"),Dl={},ql=class extends Promise{static{__name(this,"Query")}constructor(e,t,n,r,s={}){let o,i;super((e,t)=>{o=e,i=t}),this.tagged=Array.isArray(e.raw),this.strings=e,this.args=t,this.handler=n,this.canceller=r,this.options=s,this.state=null,this.statement=null,this.resolve=e=>(this.active=!1,o(e)),this.reject=e=>(this.active=!1,i(e)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[Ol]=this.handler.debug?new Error:this.tagged&&cachedError(this.strings)}get origin(){return(this.handler.debug?this[Ol].stack:this.tagged&&Ml.has(this.strings)?Ml.get(this.strings):Ml.set(this.strings,this[Ol].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(e=1,t){if(this.options.simple=!1,"function"==typeof e&&(t=e,e=1),this.cursorRows=e,"function"==typeof t)return this.cursorFn=t,this;let n;return{[Symbol.asyncIterator]:()=>({next:__name(()=>{if(this.executed&&!this.active)return{done:!0};n&&n();const e=new Promise((e,t)=>{this.cursorFn=t=>(e({value:t,done:!1}),new Promise(e=>n=e)),this.resolve=()=>(this.active=!1,e({done:!0})),this.reject=e=>(this.active=!1,t(e))});return this.execute(),e},"next"),return:()=>(n&&n(Dl),{done:!0})})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(e){return this.forEachFn=e,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}},__name(cachedError,"cachedError")}});function connection(e,t,n){const{host:r,port:s}=n||t,o=Object.assign(new Error("write "+e+" "+(t.path||r+":"+s)),{code:e,errno:e,address:t.path||r},t.path?{}:{port:s});return Error.captureStackTrace(o,connection),o}function postgres(e){const t=new Zl(e);return Error.captureStackTrace(t,postgres),t}function generic(e,t){const n=Object.assign(new Error(e+": "+t),{code:e});return Error.captureStackTrace(n,generic),n}function notSupported(e){const t=Object.assign(new Error(e+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:e});return Error.captureStackTrace(t,notSupported),t}var nc,rc,sc,oc,ic,ac,lc,cc,uc,dc,mc,pc,gc,hc,fc,yc,wc,Sc,bc,Ec,Cc,vc,Tc,kc,_c,Pc,Ac=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/errors.js"(){Nt(),Zl=class extends Error{static{__name(this,"PostgresError")}constructor(e){super(e.message),this.name=this.constructor.name,Object.assign(this,e)}},ec={connection:connection,postgres:postgres,generic:generic,notSupported:notSupported},__name(connection,"connection"),__name(postgres,"postgres"),__name(generic,"generic"),__name(notSupported,"notSupported")}});function handleValue(e,t,n,r){let s=e instanceof oc?e.value:e;if(void 0===s&&(e instanceof oc?e.value=r.transform.undefined:s=e=r.transform.undefined,void 0===s))throw ec.generic("UNDEFINED_VALUE","Undefined values are not allowed");return"$"+n.push(e instanceof oc?(t.push(e.value),e.array?e.array[e.type||pc(e.value)]||e.type||firstIsString(e.value):e.type):(t.push(e),pc(e)))}function stringify(e,t,n,r,s,o){for(let i=1;i<e.strings.length;i++)t+=stringifyValue(t,n,r,s,o)+e.strings[i],n=e.args[i];return t}function stringifyValue(e,t,n,r,s){return t instanceof ic?t.build(e,n,r,s):t instanceof ql?fragment(t,n,r,s):t instanceof sc?t.value:t&&t[0]instanceof ql?t.reduce((e,t)=>e+" "+fragment(t,n,r,s),""):handleValue(t,n,r,s)}function fragment(e,t,n,r){return e.fragment=!0,stringify(e,e.strings[0],e.args[0],t,n,r)}function valuesBuilder(e,t,n,r,s){return e.map(e=>"("+r.map(r=>stringifyValue("values",e[r],t,n,s)).join(",")+")").join(",")}function values(e,t,n,r,s){const o=Array.isArray(e[0]);return valuesBuilder(o?e:[e],n,r,t.length?t.flat():Object.keys(o?e[0]:e),s)}function select2(e,t,n,r,s){if("string"==typeof e&&(e=[e].concat(t)),Array.isArray(e))return escapeIdentifiers(e,s);let o;return(t.length?t.flat():Object.keys(e)).map(t=>(o=e[t],(o instanceof ql?fragment(o,n,r,s):o instanceof sc?o.value:handleValue(o,n,r,s))+" as "+mc(s.transform.column.to?s.transform.column.to(t):t))).join(",")}function notTagged(){throw ec.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function firstIsString(e){return Array.isArray(e)?firstIsString(e[0]):"string"==typeof e?1009:0}function typeHandlers(e){return Object.keys(e).reduce((t,n)=>(e[n].from&&[].concat(e[n].from).forEach(r=>t.parsers[r]=e[n].parse),e[n].serialize&&(t.serializers[e[n].to]=e[n].serialize,e[n].from&&[].concat(e[n].from).forEach(r=>t.serializers[r]=e[n].serialize)),t),{parsers:{},serializers:{}})}function escapeIdentifiers(e,{transform:{column:t}}){return e.map(e=>mc(t.to?t.to(e):e)).join(",")}function arrayEscape(e){return e.replace(gc,"\\\\").replace(hc,'\\"')}function arrayParserLoop(e,t,n,r){const s=[],o=1020===r?";":",";for(;e.i<t.length;e.i++){if(e.char=t[e.i],e.quoted)"\\"===e.char?e.str+=t[++e.i]:'"'===e.char?(s.push(n?n(e.str):e.str),e.str="",e.quoted='"'===t[e.i+1],e.last=e.i+2):e.str+=e.char;else if('"'===e.char)e.quoted=!0;else if("{"===e.char)e.last=++e.i,s.push(arrayParserLoop(e,t,n,r));else{if("}"===e.char){e.quoted=!1,e.last<e.i&&s.push(n?n(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1;break}e.char===o&&"}"!==e.p&&'"'!==e.p&&(s.push(n?n(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1)}e.p=e.char}return e.last<e.i&&s.push(n?n(t.slice(e.last,e.i+1)):t.slice(e.last,e.i+1)),s}function createJsonTransform(e){return __name(function jsonTransform(t,n){return"object"!=typeof t||null===t||114!==n.type&&3802!==n.type?t:Array.isArray(t)?t.map(e=>jsonTransform(e,n)):Object.entries(t).reduce((t,[r,s])=>Object.assign(t,{[e(r)]:jsonTransform(s,n)}),{})},"jsonTransform")}var xc,Ic,Nc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/types.js"(){Nt(),tc(),Ac(),nc={string:{to:25,from:null,serialize:__name(e=>""+e,"serialize")},number:{to:0,from:[21,23,26,700,701],serialize:__name(e=>""+e,"serialize"),parse:__name(e=>+e,"parse")},json:{to:114,from:[114,3802],serialize:__name(e=>JSON.stringify(e),"serialize"),parse:__name(e=>JSON.parse(e),"parse")},boolean:{to:16,from:16,serialize:__name(e=>!0===e?"t":"f","serialize"),parse:__name(e=>"t"===e,"parse")},date:{to:1184,from:[1082,1114,1184],serialize:__name(e=>(e instanceof Date?e:new Date(e)).toISOString(),"serialize"),parse:__name(e=>new Date(e),"parse")},bytea:{to:17,from:17,serialize:__name(e=>"\\x"+Buffer.from(e).toString("hex"),"serialize"),parse:__name(e=>Buffer.from(e.slice(2),"hex"),"parse")}},rc=class{static{__name(this,"NotTagged")}then(){notTagged()}catch(){notTagged()}finally(){notTagged()}},sc=class extends rc{static{__name(this,"Identifier")}constructor(e){super(),this.value=mc(e)}},oc=class extends rc{static{__name(this,"Parameter")}constructor(e,t,n){super(),this.value=e,this.type=t,this.array=n}},ic=class extends rc{static{__name(this,"Builder")}constructor(e,t){super(),this.first=e,this.rest=t}build(e,t,n,r){const s=lc.map(([t,n])=>({fn:n,i:e.search(t)})).sort((e,t)=>e.i-t.i).pop();return-1===s.i?escapeIdentifiers(this.first,r):s.fn(this.first,this.rest,t,n,r)}},__name(handleValue,"handleValue"),ac=typeHandlers(nc),__name(stringify,"stringify"),__name(stringifyValue,"stringifyValue"),__name(fragment,"fragment"),__name(valuesBuilder,"valuesBuilder"),__name(values,"values"),__name(select2,"select"),lc=Object.entries({values:values,in:__name((...e)=>{const t=values(...e);return"()"===t?"(null)":t},"in"),select:select2,as:select2,returning:select2,"\\(":select2,update:(e,t,n,r,s)=>(t.length?t.flat():Object.keys(e)).map(t=>mc(s.transform.column.to?s.transform.column.to(t):t)+"="+stringifyValue("values",e[t],n,r,s)),insert(e,t,n,r,s){const o=t.length?t.flat():Object.keys(Array.isArray(e)?e[0]:e);return"("+escapeIdentifiers(o,s)+")values"+valuesBuilder(Array.isArray(e)?e:[e],n,r,o,s)}}).map(([e,t])=>[new RegExp("((?:^|[\\s(])"+e+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),t]),__name(notTagged,"notTagged"),cc=ac.serializers,uc=ac.parsers,__name(firstIsString,"firstIsString"),dc=__name(function(e){const t=typeHandlers(e||{});return{serializers:Object.assign({},cc,t.serializers),parsers:Object.assign({},uc,t.parsers)}},"mergeUserTypes"),__name(typeHandlers,"typeHandlers"),__name(escapeIdentifiers,"escapeIdentifiers"),mc=__name(function escape(e){return'"'+e.replace(/"/g,'""').replace(/\./g,'"."')+'"'},"escape"),pc=__name(function inferType2(e){return e instanceof oc?e.type:e instanceof Date?1184:e instanceof Uint8Array?17:!0===e||!1===e?16:"bigint"==typeof e?20:Array.isArray(e)?inferType2(e[0]):0},"inferType"),gc=/\\/g,hc=/"/g,__name(arrayEscape,"arrayEscape"),fc=__name(function arraySerializer2(e,t,n,r){if(!1===Array.isArray(e))return e;if(!e.length)return"{}";const s=e[0],o=1020===r?";":",";return Array.isArray(s)&&!s.type?"{"+e.map(e=>arraySerializer2(e,t,n,r)).join(o)+"}":"{"+e.map(e=>{if(void 0===e&&void 0===(e=n.transform.undefined))throw ec.generic("UNDEFINED_VALUE","Undefined values are not allowed");return null===e?"null":'"'+arrayEscape(t?t(e.type?e.value:e):""+e)+'"'}).join(o)+"}"},"arraySerializer"),yc={i:0,char:null,str:"",quoted:!1,last:0},wc=__name(function arrayParser2(e,t,n){return yc.i=yc.last=0,arrayParserLoop(yc,e,t,n)},"arrayParser"),__name(arrayParserLoop,"arrayParserLoop"),Sc=__name(e=>{let t=e[0];for(let n=1;n<e.length;n++)t+="_"===e[n]?e[++n].toUpperCase():e[n];return t},"toCamel"),bc=__name(e=>{let t=e[0].toUpperCase();for(let n=1;n<e.length;n++)t+="_"===e[n]?e[++n].toUpperCase():e[n];return t},"toPascal"),Ec=__name(e=>e.replace(/_/g,"-"),"toKebab"),Cc=__name(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase(),"fromCamel"),vc=__name(e=>(e.slice(0,1)+e.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),"fromPascal"),Tc=__name(e=>e.replace(/-/g,"_"),"fromKebab"),__name(createJsonTransform,"createJsonTransform"),Sc.column={from:Sc},Sc.value={from:createJsonTransform(Sc)},Cc.column={to:Cc},(kc={...Sc}).column.to=Cc,bc.column={from:bc},bc.value={from:createJsonTransform(bc)},vc.column={to:vc},(_c={...bc}).column.to=vc,Ec.column={from:Ec},Ec.value={from:createJsonTransform(Ec)},Tc.column={to:Tc},(Pc={...Ec}).column.to=Tc}}),Rc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/result.js"(){Nt(),xc=class extends Array{static{__name(this,"Result")}constructor(){super(),Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}}});function Queue(e=[]){let t=e.slice(),n=0;return{get length(){return t.length-n},remove:__name(e=>{const n=t.indexOf(e);return-1===n?null:(t.splice(n,1),e)},"remove"),push:__name(e=>(t.push(e),e),"push"),shift:__name(()=>{const e=t[n++];return n===t.length?(n=0,t=[]):t[n-1]=void 0,e},"shift")}}var $c,Lc,Mc,Oc,Dc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/queue.js"(){Nt(),Ic=Queue,__name(Queue,"Queue")}});function fit(e){if($c.length-Mc.i<e){const t=$c,n=t.length;$c=Buffer.allocUnsafe(n+(n>>1)+e),t.copy($c)}}function reset(){return Mc.i=0,Mc}var qc,Fc,jc,zc,Bc,Uc,Wc,Qc,Gc,Hc,Vc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/bytes.js"(){Nt(),$c=Buffer.allocUnsafe(256),Lc="BCcDdEFfHPpQSX".split("").reduce((e,t)=>{const n=t.charCodeAt(0);return e[t]=()=>($c[0]=n,Mc.i=5,Mc),e},{}),Mc=Object.assign(reset,Lc,{N:String.fromCharCode(0),i:0,inc:e=>(Mc.i+=e,Mc),str(e){const t=Buffer.byteLength(e);return fit(t),Mc.i+=$c.write(e,Mc.i,t,"utf8"),Mc},i16:e=>(fit(2),$c.writeUInt16BE(e,Mc.i),Mc.i+=2,Mc),i32:(e,t)=>t||0===t?($c.writeUInt32BE(e,t),Mc):(fit(4),$c.writeUInt32BE(e,Mc.i),Mc.i+=4,Mc),z:e=>(fit(e),$c.fill(0,Mc.i,Mc.i+e),Mc.i+=e,Mc),raw:e=>($c=Buffer.concat([$c.subarray(0,Mc.i),e]),Mc.i=$c.length,Mc),end(e=1){$c.writeUInt32BE(Mc.i-e,e);const t=$c.subarray(0,Mc.i);return Mc.i=0,$c=Buffer.allocUnsafe(256),t}}),Oc=Mc,__name(fit,"fit"),__name(reset,"reset")}});function Connection(e,t={},{onopen:n=Qc,onend:r=Qc,onclose:s=Qc}={}){const{sslnegotiation:o,ssl:i,max:a,user:l,host:u,port:d,database:m,parsers:p,transform:g,onnotice:h,onnotify:f,onparameter:y,max_pipeline:w,keep_alive:S,backoff:b,target_session_attrs:E}=e,C=Ic(),v=Fc++,T={pid:null,secret:null},k=timer(end,e.idle_timeout),_=timer(end,e.max_lifetime),P=timer(function connectTimedOut(){errored(ec.connection("CONNECT_TIMEOUT",e,x)),x.destroy()},e.connect_timeout);let A,x=null,I=null,N=new xc,R=Buffer.alloc(0),$=e.fetch_types,L={},M={},O=Math.random().toString(36).slice(2),D=1,q=0,F=0,z=0,B=0,U=0,W=0,Q=0,G=null,H=null,V=!1,K=null,Y=null,J=null,X=null,Z=null,ee=null,te=null,ne=null,re=null,se=null;const oe={queue:t.closed,idleTimer:k,connect(e){J=e,reconnect()},terminate:terminate,execute:execute,cancel:async function cancel5({pid:e,secret:t},n,r){try{A=Oc().i32(16).i32(80877102).i32(e).i32(t).end(16),await connect(),x.once("error",r),x.once("close",n)}catch(e){r(e)}},end:end,count:0,id:v};return t.closed&&t.closed.push(oe),oe;function execute(t){if(V)return queryError(t,ec.connection("CONNECTION_DESTROYED",e));if(Z)return queryError(t,ec.generic("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(!t.cancelled)try{return t.state=T,re?C.push(t):(re=t,re.active=!0),function build(t){const n=[],r=[],s=stringify(t,t.strings[0],t.args[0],n,r,e);!t.tagged&&t.args.forEach(t=>handleValue(t,n,r,e)),t.prepare=e.prepare&&(!("prepare"in t.options)||t.options.prepare),t.string=s,t.signature=t.prepare&&r+s,t.onlyDescribe&&delete M[t.signature],t.parameters=t.parameters||n,t.prepared=t.prepare&&t.signature in M,t.describeFirst=t.onlyDescribe||n.length&&!t.prepared,t.statement=t.prepared?M[t.signature]:{string:s,types:r,name:t.prepare?O+D++:""},"function"==typeof e.debug&&e.debug(v,s,n,r)}(t),write(function toBuffer(e){if(e.parameters.length>=65534)throw ec.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return e.options.simple?Oc().Q().str(e.statement.string+Oc.N).end():e.describeFirst?Buffer.concat([describe(e),zc]):e.prepare?e.prepared?prepared(e):Buffer.concat([describe(e),prepared(e)]):function unnamed(e){return Buffer.concat([Parse(e.statement.string,e.parameters,e.statement.types),Wc,prepared(e)])}(e)}(t))&&!t.describeFirst&&!t.cursorFn&&C.length<w&&(!t.options.onexecute||t.options.onexecute(oe))}catch(e){return 0===C.length&&write(jc),errored(e),!0}}function describe(e){return Buffer.concat([Parse(e.statement.string,e.parameters,e.statement.types,e.statement.name),Describe("S",e.statement.name)])}function prepared(e){return Buffer.concat([Bind(e.parameters,e.statement.types,e.statement.name,e.cursorName),e.cursorFn?Execute("",e.cursorRows):Uc])}function write(e,t){return ee=ee?Buffer.concat([ee,e]):Buffer.from(e),ee.length>=1024?nextWrite(t):(null===H&&(H=setImmediate(nextWrite)),!0)}function nextWrite(e){const t=x.write(ee,e);return null!==H&&clearImmediate(H),ee=H=null,t}async function secure(){if("direct"!==o&&(write(Bc),!await new Promise(e=>x.once("data",t=>e(83===t[0])))&&"prefer"===i))return connected();const e={socket:x,servername:we.isIP(x.host)?void 0:x.host};"direct"===o&&(e.ALPNProtocols=["postgresql"]),"require"===i||"allow"===i||"prefer"===i?e.rejectUnauthorized=!1:"object"==typeof i&&Object.assign(e,i),x.removeAllListeners(),x=De.connect(e),x.on("secureConnect",connected),x.on("error",error),x.on("close",closed),x.on("drain",drain)}function drain(){!re&&n(oe)}function data(e){if(!(K&&(K.push(e),F-=e.length,F>0)))for(R=K?Buffer.concat(K,U-F):0===R.length?e:Buffer.concat([R,e],R.length+e.length);R.length>4;){if(U=R.readUInt32BE(1),U>=R.length){F=U-R.length,K=[R];break}try{handle(R.subarray(0,U+1))}catch(e){re&&(re.cursorFn||re.describeFirst)&&write(jc),errored(e)}R=R.subarray(U+1),F=0,K=null}}async function connect(){if(V=!1,L={},x||(x=await async function createSocket(){let t;try{t=e.socket?await Promise.resolve(e.socket(e)):new we.Socket}catch(e){return void error(e)}return t.on("error",error),t.on("close",closed),t.on("drain",drain),t}()),x){if(P.start(),e.socket)return i?secure():connected();if(x.on("connect",i?secure:connected),e.path)return x.connect(e.path);x.ssl=i,x.connect(d[z],u[z]),x.host=u[z],x.port=d[z],z=(z+1)%d.length}}function reconnect(){setTimeout(connect,q?Math.max(0,q+W-Fe.now()):0)}function connected(){try{M={},$=e.fetch_types,O=Math.random().toString(36).slice(2),D=1,_.start(),x.on("data",data),S&&x.setKeepAlive&&x.setKeepAlive(!0,1e3*S),write(function StartupMessage(){return A||Oc().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:l,database:m,client_encoding:"UTF8"},e.connection)).filter(([,e])=>e).map(([e,t])=>e+Oc.N+t).join(Oc.N)).z(2).end(0)}())}catch(e){error(e)}}function error(n){if(oe.queue!==t.connecting||!e.host[B+1])for(errored(n);C.length;)queryError(C.shift(),n)}function errored(e){Z&&(Z.destroy(e),Z=null),re&&queryError(re,e),J&&(queryError(J,e),J=null)}function queryError(t,n){if(t.reserve)return t.reject(n);n&&"object"==typeof n||(n=new Error(n)),"query"in n||"parameters"in n||Object.defineProperties(n,{stack:{value:n.stack+t.origin.replace(/.*\n/,"\n"),enumerable:e.debug},query:{value:t.string,enumerable:e.debug},parameters:{value:t.parameters,enumerable:e.debug},args:{value:t.args,enumerable:e.debug},types:{value:t.statement&&t.statement.types,enumerable:e.debug}}),t.reject(n)}function end(){return X||(!oe.reserved&&r(oe),oe.reserved||J||re||0!==C.length?X=new Promise(e=>te=e):(terminate(),new Promise(e=>x&&"closed"!==x.readyState?x.once("close",e):e())))}function terminate(){V=!0,(Z||re||J||C.length)&&error(ec.connection("CONNECTION_DESTROYED",e)),clearImmediate(H),x&&(x.removeListener("data",data),x.removeListener("connect",connected),"open"===x.readyState&&x.end(Oc().X().end())),te&&(te(),X=te=null)}async function closed(t){if(R=Buffer.alloc(0),F=0,K=null,clearImmediate(H),x.removeListener("data",data),x.removeListener("connect",connected),k.cancel(),_.cancel(),P.cancel(),x.removeAllListeners(),x=null,J)return reconnect();!t&&(re||C.length)&&error(ec.connection("CONNECTION_CLOSED",e,x)),q=Fe.now(),t&&e.shared.retries++,W=1e3*("function"==typeof b?b(e.shared.retries):b),s(oe,ec.connection("CONNECTION_CLOSED",e,x))}function handle(e,t=e[0]){(68===t?DataRow:100===t?CopyData:65===t?NotificationResponse:83===t?ParameterStatus:90===t?ReadyForQuery:67===t?CommandComplete:50===t?BindComplete:49===t?ParseComplete:116===t?ParameterDescription:84===t?RowDescription:82===t?Authentication:110===t?NoData:75===t?BackendKeyData:69===t?ErrorResponse:115===t?PortalSuspended:51===t?CloseComplete:71===t?CopyInResponse:78===t?NoticeResponse:72===t?CopyOutResponse:99===t?CopyDone:73===t?EmptyQueryResponse:86===t?FunctionCallResponse:118===t?NegotiateProtocolVersion:87===t?CopyBothResponse:UnknownMessage)(e)}function DataRow(e){let t,n,r,s=7;const o=re.isRaw?new Array(re.statement.columns.length):{};for(let i=0;i<re.statement.columns.length;i++)n=re.statement.columns[i],t=e.readInt32BE(s),s+=4,r=-1===t?null:!0===re.isRaw?e.subarray(s,s+=t):void 0===n.parser?e.toString("utf8",s,s+=t):!0===n.parser.array?n.parser(e.toString("utf8",s+1,s+=t)):n.parser(e.toString("utf8",s,s+=t)),re.isRaw?o[i]=!0===re.isRaw?r:g.value.from?g.value.from(r,n):r:o[n.name]=g.value.from?g.value.from(r,n):r;re.forEachFn?re.forEachFn(g.row.from?g.row.from(o):o,N):N[Q++]=g.row.from?g.row.from(o):o}function ParameterStatus(t){const[n,r]=t.toString("utf8",5,t.length-1).split(Oc.N);L[n]=r,e.parameters[n]!==r&&(e.parameters[n]=r,y&&y(n,r))}function ReadyForQuery(t){if(re?I?re.retried?errored(re.retried):re.prepared&&Gc.has(I.routine)?function retry(e,t){delete M[e.signature],e.retried=t,execute(e)}(re,I):errored(I):re.resolve(Y||N):I&&errored(I),re=Y=I=null,N=new xc,P.cancel(),J){if(E){if(!L.in_hot_standby||!L.default_transaction_read_only)return function fetchState(){const e=new ql(["\n show transaction_read_only;\n select pg_catalog.pg_is_in_recovery()\n "],[],execute,null,{simple:!0});e.resolve=([[e],[t]])=>{L.default_transaction_read_only=e.transaction_read_only,L.in_hot_standby=t.pg_is_in_recovery?"on":"off"},e.execute()}();if(function tryNext(t,n){return"read-write"===t&&"on"===n.default_transaction_read_only||"read-only"===t&&"off"===n.default_transaction_read_only||"primary"===t&&"on"===n.in_hot_standby||"standby"===t&&"off"===n.in_hot_standby||"prefer-standby"===t&&"off"===n.in_hot_standby&&e.host[B]}(E,L))return terminate()}return $?(J.reserve&&(J=null),async function fetchArrayTypes(){$=!1,(await new ql(["\n select b.oid, b.typarray\n from pg_catalog.pg_type a\n left join pg_catalog.pg_type b on b.oid = a.typelem\n where a.typcategory = 'A'\n group by b.oid, b.typarray\n order by b.oid\n "],[],execute)).forEach(({oid:t,typarray:n})=>function addArrayType(t,n){if(e.parsers[n]&&e.serializers[n])return;const r=e.parsers[t];e.shared.typeArrayMap[t]=n,e.parsers[n]=e=>wc(e,r,n),e.parsers[n].array=!0,e.serializers[n]=r=>fc(r,e.serializers[t],e,n)}(t,n))}()):(J&&!J.reserve&&execute(J),e.shared.retries=B=0,void(J=null))}for(;C.length&&(re=C.shift())&&(re.active=!0,re.cancelled);)Connection(e).cancel(re.state,re.cancelled.resolve,re.cancelled.reject);re||(oe.reserved?oe.reserved.release||73!==t[5]?oe.reserved():X?terminate():(oe.reserved=null,n(oe)):X?terminate():n(oe))}function CommandComplete(e){Q=0;for(let t=e.length-1;t>0;t--)if(32===e[t]&&e[t+1]<58&&null===N.count&&(N.count=+e.toString("utf8",t+1,e.length-1)),e[t-1]>=65){N.command=e.toString("utf8",5,t),N.state=T;break}return se&&(se(),se=null),"BEGIN"!==N.command||1===a||oe.reserved?re.options.simple?BindComplete():void(re.cursorFn&&(N.count&&re.cursorFn(N),write(jc))):errored(ec.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"))}function ParseComplete(){re.parsing=!1}function BindComplete(){!N.statement&&(N.statement=re.statement),N.columns=re.statement.columns}function ParameterDescription(e){const t=e.readUInt16BE(5);for(let n=0;n<t;++n)!re.statement.types[n]&&(re.statement.types[n]=e.readUInt32BE(7+4*n));re.prepare&&(M[re.signature]=re.statement),re.describeFirst&&!re.onlyDescribe&&(write(prepared(re)),re.describeFirst=!1)}function RowDescription(e){N.command&&(Y=Y||[N],Y.push(N=new xc),N.count=null,re.statement.columns=null);const t=e.readUInt16BE(5);let n,r=7;re.statement.columns=Array(t);for(let s=0;s<t;++s){for(n=r;0!==e[r++];);const t=e.readUInt32BE(r),o=e.readUInt16BE(r+4),i=e.readUInt32BE(r+6);re.statement.columns[s]={name:g.column.from?g.column.from(e.toString("utf8",n,r-1)):e.toString("utf8",n,r-1),parser:p[i],table:t,number:o,type:i},r+=18}if(N.statement=re.statement,re.onlyDescribe)return re.resolve(re.statement),write(jc)}async function Authentication(e,t=e.readUInt32BE(5)){(3===t?AuthenticationCleartextPassword:5===t?AuthenticationMD5Password:10===t?SASL:11===t?SASLContinue:12===t?SASLFinal:0!==t?UnknownAuth:Qc)(e,t)}async function AuthenticationCleartextPassword(){const e=await Pass();write(Oc().p().str(e).z(1).end())}async function AuthenticationMD5Password(e){const t="md5"+await md5(Buffer.concat([Buffer.from(await md5(await Pass()+l)),e.subarray(9)]));write(Oc().p().str(t).z(1).end())}async function SASL(){ne=(await j.randomBytes(18)).toString("base64"),Oc().p().str("SCRAM-SHA-256"+Oc.N);const e=Oc.i;write(Oc.inc(4).str("n,,n=*,r="+ne).i32(Oc.i-e-4,e).end())}async function SASLContinue(e){const t=e.toString("utf8",9).split(",").reduce((e,t)=>(e[t[0]]=t.slice(2),e),{}),n=await j.pbkdf2Sync(await Pass(),Buffer.from(t.s,"base64"),parseInt(t.i),32,"sha256"),r=await hmac(n,"Client Key"),s="n=*,r="+ne+",r="+t.r+",s="+t.s+",i="+t.i+",c=biws,r="+t.r;G=(await hmac(await hmac(n,"Server Key"),s)).toString("base64");const o="c=biws,r="+t.r+",p="+xor(r,Buffer.from(await hmac(await sha256(r),s))).toString("base64");write(Oc().p().str(o).end())}function SASLFinal(e){e.toString("utf8",9).split(Oc.N,1)[0].slice(2)!==G&&(errored(ec.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),x.destroy())}function Pass(){return Promise.resolve("function"==typeof e.pass?e.pass():e.pass)}function NoData(){if(N.statement=re.statement,N.statement.columns=[],re.onlyDescribe)return re.resolve(re.statement),write(jc)}function BackendKeyData(e){T.pid=e.readUInt32BE(5),T.secret=e.readUInt32BE(9)}function ErrorResponse(e){re?((re.cursorFn||re.describeFirst)&&write(jc),I=ec.postgres(parseError(e))):errored(ec.postgres(parseError(e)))}function NotificationResponse(e){if(!f)return;let t=9;for(;0!==e[t++];);f(e.toString("utf8",9,t-1),e.toString("utf8",t,e.length-1))}async function PortalSuspended(){try{const e=await Promise.resolve(re.cursorFn(N));Q=0,e===Dl?write(function Close(e=""){return Buffer.concat([Oc().C().str("P").str(e+Oc.N).end(),Oc().S().end()])}(re.portal)):(N=new xc,write(Execute("",re.cursorRows)))}catch(e){write(jc),re.reject(e)}}function CloseComplete(){N.count&&re.cursorFn(N),re.resolve(N)}function CopyInResponse(){Z=new qe.Writable({autoDestroy:!0,write(e,t,n){x.write(Oc().d().raw(e).end(),n)},destroy(e,t){t(e),x.write(Oc().f().str(e+Oc.N).end()),Z=null},final(e){x.write(Oc().c().end()),se=e,Z=null}}),re.resolve(Z)}function CopyOutResponse(){Z=new qe.Readable({read(){x.resume()}}),re.resolve(Z)}function CopyBothResponse(){Z=new qe.Duplex({autoDestroy:!0,read(){x.resume()},write(e,t,n){x.write(Oc().d().raw(e).end(),n)},destroy(e,t){t(e),x.write(Oc().f().str(e+Oc.N).end()),Z=null},final(e){x.write(Oc().c().end()),se=e}}),re.resolve(Z)}function CopyData(e){Z&&(Z.push(e.subarray(5))||x.pause())}function CopyDone(){Z&&Z.push(null),Z=null}function NoticeResponse(e){h?h(parseError(e)):console.log(parseError(e))}function EmptyQueryResponse(){}function FunctionCallResponse(){errored(ec.notSupported("FunctionCallResponse"))}function NegotiateProtocolVersion(){errored(ec.notSupported("NegotiateProtocolVersion"))}function UnknownMessage(e){console.error("Postgres.js : Unknown Message:",e[0])}function UnknownAuth(e,t){console.error("Postgres.js : Unknown Auth:",t)}function Bind(t,n,r="",s=""){let o,i;return Oc().B().str(s+Oc.N).str(r+Oc.N).i16(0).i16(t.length),t.forEach((r,s)=>{if(null===r)return Oc.i32(4294967295);i=n[s],t[s]=r=i in e.serializers?e.serializers[i](r):""+r,o=Oc.i,Oc.inc(4).str(r).i32(Oc.i-o-4,o)}),Oc.i16(0),Oc.end()}function Parse(e,t,n,r=""){return Oc().P().str(r+Oc.N).str(e+Oc.N).i16(t.length),t.forEach((e,t)=>Oc.i32(n[t]||0)),Oc.end()}function Describe(e,t=""){return Oc().D().str(e).str(t+Oc.N).end()}function Execute(e="",t=0){return Buffer.concat([Oc().E().str(e+Oc.N).i32(t).end(),zc])}}function parseError(e){const t={};let n=5;for(let r=5;r<e.length-1;r++)0===e[r]&&(t[Hc[e[n]]]=e.toString("utf8",n+1,r),n=r+1);return t}function md5(e){return j.createHash("md5").update(e).digest("hex")}function hmac(e,t){return j.createHmac("sha256",e).update(t).digest()}function sha256(e){return j.createHash("sha256").update(e).digest()}function xor(e,t){const n=Math.max(e.length,t.length),r=Buffer.allocUnsafe(n);for(let s=0;s<n;s++)r[s]=e[s]^t[s];return r}function timer(e,t){if(!(t="function"==typeof t?t():t))return{cancel:Qc,start:Qc};let n;return{cancel(){n&&(clearTimeout(n),n=null)},start(){n&&clearTimeout(n),n=setTimeout(done,1e3*t,arguments)}};function done(t){e.apply(null,t),n=null}}var Kc,Yc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/connection.js"(){Nt(),Nc(),Ac(),Rc(),Dc(),tc(),Vc(),qc=Connection,Fc=1,jc=Oc().S().end(),zc=Oc().H().end(),Bc=Oc().i32(8).i32(80877103).end(8),Uc=Buffer.concat([Oc().E().str(Oc.N).i32(0).end(),jc]),Wc=Oc().D().str("S").str(Oc.N).end(),Qc=__name(()=>{},"noop"),Gc=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Hc={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"},__name(Connection,"Connection"),__name(parseError,"parseError"),__name(md5,"md5"),__name(hmac,"hmac"),__name(sha256,"sha256"),__name(xor,"xor"),__name(timer,"timer")}});function Subscribe(e,t){const n=new Map,r="postgresjs_"+Math.random().toString(36).slice(2),s={};let o,i,a=!1;const l=subscribe.sql=e({...t,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...t.connection,replication:"database"},onclose:__name(async function(){a||(i=null,s.pid=s.secret=void 0,connected(await init(l,r,t.publications)),n.forEach(e=>e.forEach(({onsubscribe:e})=>e())))},"onclose"),no_subscribe:!0}),u=l.end,d=l.close;return l.end=async()=>(a=!0,i&&await new Promise(e=>(i.once("close",e),i.end())),u()),l.close=async()=>(i&&await new Promise(e=>(i.once("close",e),i.end())),d()),subscribe;async function subscribe(e,a,u=Kc,d=Kc){e=parseEvent(e),o||(o=init(l,r,t.publications));const m={fn:a,onsubscribe:u},p=n.has(e)?n.get(e).add(m):n.set(e,new Set([m])).get(e),g=__name(()=>{p.delete(m),0===p.size&&n.delete(e)},"unsubscribe");return o.then(e=>(connected(e),u(),i&&i.on("error",d),{unsubscribe:g,state:s,sql:l}))}function connected(e){i=e.stream,s.pid=e.state.pid,s.secret=e.state.secret}async function init(e,n,r){if(!r)throw new Error("Missing publication names");const s=await e.unsafe(`CREATE_REPLICATION_SLOT ${n} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[o]=s,i=await e.unsafe(`START_REPLICATION SLOT ${n} LOGICAL ${o.consistent_point} (proto_version '1', publication_names '${r}')`).writable(),a={lsn:Buffer.concat(o.consistent_point.split("/").map(e=>Buffer.from(("00000000"+e).slice(-8),"hex")))};return i.on("data",function data(n){119===n[0]?parse(n.subarray(25),a,e.options.parsers,handle,t.transform):107===n[0]&&n[17]&&(a.lsn=n.subarray(1,9),function pong(){const e=Buffer.alloc(34);e[0]="r".charCodeAt(0),e.fill(a.lsn,1),e.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2e3,0,1))*BigInt(1e3),25),i.write(e)}())}),i.on("error",function error(e){console.error("Unexpected error during logical streaming - reconnecting",e)}),i.on("close",e.close),{stream:i,state:s.state};function handle(e,t){const n=t.relation.schema+"."+t.relation.table;call("*",e,t),call("*:"+n,e,t),t.relation.keys.length&&call("*:"+n+"="+t.relation.keys.map(t=>e[t.name]),e,t),call(t.command,e,t),call(t.command+":"+n,e,t),t.relation.keys.length&&call(t.command+":"+n+"="+t.relation.keys.map(t=>e[t.name]),e,t)}}function call(e,t,r){n.has(e)&&n.get(e).forEach(({fn:n})=>n(t,r,e))}}function Time(e){return new Date(Date.UTC(2e3,0,1)+Number(e/BigInt(1e3)))}function parse(e,t,n,r,s){const o=__name((e,[t,n])=>(e[t.charCodeAt(0)]=n,e),"char");Object.entries({R:__name(e=>{let r=1;const o=t[e.readUInt32BE(r)]={schema:e.toString("utf8",r+=4,r=e.indexOf(0,r))||"pg_catalog",table:e.toString("utf8",r+1,r=e.indexOf(0,r+1)),columns:Array(e.readUInt16BE(r+=2)),keys:[]};r+=2;let i,a=0;for(;r<e.length;)i=o.columns[a++]={key:e[r++],name:s.column.from?s.column.from(e.toString("utf8",r,r=e.indexOf(0,r))):e.toString("utf8",r,r=e.indexOf(0,r)),type:e.readUInt32BE(r+=1),parser:n[e.readUInt32BE(r)],atttypmod:e.readUInt32BE(r+=4)},i.key&&o.keys.push(i),r+=4},"R"),Y:__name(()=>{},"Y"),O:__name(()=>{},"O"),B:__name(e=>{t.date=Time(e.readBigInt64BE(9)),t.lsn=e.subarray(1,9)},"B"),I:__name(e=>{let n=1;const o=t[e.readUInt32BE(n)],{row:i}=tuples(e,o.columns,n+=7,s);r(i,{command:"insert",relation:o})},"I"),D:__name(e=>{let n=1;const o=t[e.readUInt32BE(n)];n+=4;const i=75===e[n];r(i||79===e[n]?tuples(e,o.columns,n+=3,s).row:null,{command:"delete",relation:o,key:i})},"D"),U:__name(e=>{let n=1;const o=t[e.readUInt32BE(n)];n+=4;const i=75===e[n],a=i||79===e[n]?tuples(e,o.columns,n+=3,s):null;a&&(n=a.i);const{row:l}=tuples(e,o.columns,n+3,s);r(l,{command:"update",relation:o,key:i,old:a&&a.row})},"U"),T:__name(()=>{},"T"),C:__name(()=>{},"C")}).reduce(o,{})[e[0]](e)}function tuples(e,t,n,r){let s,o,i;const a=r.raw?new Array(t.length):{};for(let l=0;l<t.length;l++)s=e[n++],o=t[l],i=110===s?null:117===s?void 0:void 0===o.parser?e.toString("utf8",n+4,n+=4+e.readUInt32BE(n)):!0===o.parser.array?o.parser(e.toString("utf8",n+5,n+=4+e.readUInt32BE(n))):o.parser(e.toString("utf8",n+4,n+=4+e.readUInt32BE(n))),r.raw?a[l]=!0===r.raw?i:r.value.from?r.value.from(i,o):i:a[o.name]=r.value.from?r.value.from(i,o):i;return{i:n,row:r.row.from?r.row.from(a):a}}function parseEvent(e){const t=e.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!t)throw new Error("Malformed subscribe pattern: "+e);const[,n,r,s]=t;return(n||"*")+(r?":"+(-1===r.indexOf(".")?"public."+r:r):"")+(s?"="+s:"")}var Jc=__esm({"../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/subscribe.js"(){Nt(),Kc=__name(()=>{},"noop"),__name(Subscribe,"Subscribe"),__name(Time,"Time"),__name(parse,"parse"),__name(tuples,"tuples"),__name(parseEvent,"parseEvent")}});function largeObject(e,t,n=393216){return new Promise(async(r,s)=>{await e.begin(async e=>{let s;!t&&([{oid:t}]=await(e`select lo_creat(-1) as oid`));const[{fd:o}]=await(e`select lo_open(${t}, ${n}) as fd`),i={writable:async function writable({highWaterMark:e=16384,start:t=0}={}){return t&&await i.seek(t),new qe.Writable({highWaterMark:e,write(e,t,n){i.write(e).then(()=>n(),n)}})},readable:async function readable({highWaterMark:e=16384,start:t=0,end:n=1/0}={}){let r=n-t;return t&&await i.seek(t),new qe.Readable({highWaterMark:e,async read(e){const t=e>r?e-r:e;r-=e;const[{data:n}]=await i.read(t);this.push(n),n.length<e&&this.push(null)}})},close:__name(()=>e`select lo_close(${o})`.then(s),"close"),tell:__name(()=>e`select lo_tell64(${o})`,"tell"),read:__name(t=>e`select loread(${o}, ${t}) as data`,"read"),write:__name(t=>e`select lowrite(${o}, ${t})`,"write"),truncate:__name(t=>e`select lo_truncate64(${o}, ${t})`,"truncate"),seek:__name((t,n=0)=>e`select lo_lseek64(${o}, ${t}, ${n})`,"seek"),size:__name(()=>e`
3
3
  select
4
4
  lo_lseek64(${o}, location, 0) as position,
5
5
  seek.size
@@ -248,6 +248,6 @@ import*as e from"path";import t,{join as n,dirname as r,relative as s,resolve as
248
248
  WHERE user_id = ${qb}
249
249
  AND role IN ('owner')
250
250
  )
251
- `}),index("subscriptions_owner_idx").on(e.userId,e.orgId)])),b2(Bb)}}),gE=__esm({"../shared/src/database/schema/free-credits-audit.ts"(){Nt(),fh(),rE(),Sh(),Ub=sql`(SELECT NULLIF(current_setting('app.current_user_id', true), '')::uuid)`,Wb=sql`users`,c(Qb=Pp("free_credits_audit",{id:uuid("id").defaultRandom().primaryKey(),date:date("date").notNull().unique(),totalCreditsGiven:numeric("total_credits_given").notNull(),syncedAt:timestamp("synced_at",{withTimezone:!0}).notNull()},e=>[index("free_credits_audit_date_idx").on(e.date),pgPolicy("free_credits_audit_select_admin",{as:"permissive",to:"app_user",for:"select",using:sql`(SELECT admin FROM ${Wb} WHERE id = ${Ub})`}),pgPolicy("free_credits_audit_insert_admin",{as:"permissive",to:"app_user",for:"insert",withCheck:sql`(SELECT admin FROM ${Wb} WHERE id = ${Ub})`}),pgPolicy("free_credits_audit_update_admin",{as:"permissive",to:"app_user",for:"update",using:sql`(SELECT admin FROM ${Wb} WHERE id = ${Ub})`}),pgPolicy("free_credits_audit_delete_admin",{as:"permissive",to:"app_user",for:"delete",using:sql`(SELECT admin FROM ${Wb} WHERE id = ${Ub})`})])),b2(Qb)}}),hE=__esm({"../shared/src/database/schema/follows.ts"(){Nt(),fh(),Sh(),rE(),sE(),oE(),Gb=sql`(SELECT NULLIF(current_setting('app.current_user_id', true), '')::uuid)`,c(Hb=Pp("follows",{id:uuid("id").defaultRandom().primaryKey(),followerId:uuid("follower_id").references(()=>eb.id,{onUpdate:"cascade",onDelete:"cascade"}).notNull(),followedUserId:uuid("followed_user_id").references(()=>eb.id,{onUpdate:"cascade",onDelete:"cascade"}),followedOrgId:uuid("followed_org_id").references(()=>nb.id,{onUpdate:"cascade",onDelete:"cascade"}),createdAt:timestamp("created_at",{withTimezone:!0}).defaultNow().notNull()},e=>[check("follows_exactly_one_target",sql`(followed_user_id IS NOT NULL AND followed_org_id IS NULL) OR (followed_user_id IS NULL AND followed_org_id IS NOT NULL)`),check("follows_no_self_follow",sql`follower_id != followed_user_id OR followed_user_id IS NULL`),uniqueIndex("follows_user_unique").on(e.followerId,e.followedUserId).where(sql`followed_user_id IS NOT NULL`),uniqueIndex("follows_org_unique").on(e.followerId,e.followedOrgId).where(sql`followed_org_id IS NOT NULL`),index("follows_follower_idx").on(e.followerId),index("follows_followed_user_idx").on(e.followedUserId),index("follows_followed_org_idx").on(e.followedOrgId),pgPolicy("follows_select_all",{for:"select",to:"app_user",using:sql`true`}),pgPolicy("follows_insert_own",{for:"insert",to:"app_user",withCheck:sql`follower_id = ${Gb}`}),pgPolicy("follows_delete_own",{for:"delete",to:"app_user",using:sql`follower_id = ${Gb}`}),pgPolicy("follows_select_public",{for:"select",to:"public_user",using:sql`true`})])),b2(Hb)}}),fE=__esm({"../shared/src/database/schema/index.ts"(){Nt(),oE(),iE(),aE(),sE(),lE(),cE(),uE(),dE(),mE(),pE(),gE(),hE()}}),yE=__esm({"../shared/src/database/config/database.ts"(){Nt(),eu(),fE()}}),wE=__esm({"../shared/src/database/index.ts"(){Nt(),yE(),fE()}}),SE=__esm({"../shared/src/index.ts"(){Nt(),jl(),zl(),Yl(),Jl(),Xl(),Ot(),Rt(),wE()}}),bE=__esm({"src/api/request.ts"(){Nt(),Qs(),hi(),Vr(),Tr(),cr(),SE(),Vb=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=trackAPICallStart({method:e.method,endpoint:t}),s=await this.buildHeaders({headers:e.headers,span:r.span});let o;try{o=await this.makeRequest({url:n,options:e,headers:s})}catch(e){const t=new si({cause:e instanceof Error?e:void 0});throw r.end({statusCode:0,error:t}),t}if(!o.ok){const{error:e}=await this.handleErrorResponse({response:o});throw r.end({statusCode:o.status,error:e}),e}return r.end({statusCode:o.status}),e.stream?o.body:o.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e,span:t}){const n=await getAuthKey(),r=getTraceId(),s=t?.spanContext(),o=r&&s?.spanId?`00-${r}-${s.spanId}-01`:void 0,i=getTelemetryEnv(),a="prod"===i?"production":i;return{"Content-Type":"application/json",[wt.CLI_ENVIRONMENT]:a,...n?{Authorization:`Bearer ${n}`}:{},...o?{traceparent:o}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,s=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const o=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return s&&clearTimeout(s),o}catch(e){throw s&&clearTimeout(s),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:ri.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"})}}}}),EE=__esm({"src/utils/strip-ide-context.ts"(){Nt(),Kb=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext")}}),CE=__esm({"src/sessions/index.ts"(){Nt(),Jo(),Ci(),Ot(),Vr(),$n(),EE(),Yb=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(f.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Ne(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=I("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await L.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:Br.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await L.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(),s={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(s)),this.lastMessageId=e}await L.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 L.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(),s=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=Kb(n),n&&t.push({id:s,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)t.push({id:s,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=Ho(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=Ho(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 L.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 L.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await L.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 L.access(n)}catch{return[]}const e=(await L.readdir(n)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),r=[];for(const s of e){const e=s.replace(".jsonl",""),o=t.join(n,s);try{const t=await L.stat(o),s=(await L.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(s.length>0){let o="",i="";const a=JSON.parse(s[0]);a.gitBranch&&(i=a.gitBranch);for(const e of s){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)o=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){o=e.text;break}}else t.content?.input&&(o=t.content.input);if(o)break}}o=Kb(o);const l=await _SessionManager.loadSessionMetaForId(e,n),u=l?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:o||"No messages",title:u||void 0,messageCount:s.length,projectPath:n,gitBranch:i||"-"})}}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 L.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 L.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 L.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await L.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 L.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 L.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 L.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const s=n.findIndex(e=>e.messageId===t.messageId);-1!==s?n[s]=e:n.push(e);const o=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await L.writeFile(r,o)}else await L.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 L.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 L.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),s=e.findIndex(e=>e.messageId===t);if(-1===s)return;const o=(n?e.slice(0,s):e.slice(0,s+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await L.writeFile(r,o)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let s="";if("string"==typeof r.message.content)s=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(s+=e.text);return s=Kb(s),{messageId:r.meta.messageId||crypto.randomUUID(),content:s}}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}}}});function getRequest(){return nE||(nE=new Vb({baseUrl:getApiBaseUrl()})),nE}function stableStringify(e){return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map(stableStringify).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+stableStringify(e[t])).join(",")+"}"}function generateCacheKey(e,t){return`${e}:${stableStringify(t)}`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:vt,max_tokens:eE,temperature:tE,stream:!0},threadId:crypto.randomUUID()}}async function getAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced();let n;e===Ct.ANTHROPIC&&(n=await on.getValidAccessToken(),validateOAuthToken({token:n,provider:e}));const r={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(r[wt.OAUTH_TOKEN]=`Bearer ${n}`),r}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=Xb.get(n);if(r)return Xb.delete(n),Xb.set(n,r),dlog(`[ToolDescription] cache hit for ${e}: "${r}"`),r;dlog(`[ToolDescription] generating for ${e}`);try{const e=getRequest(),r=await getAuthHeaders(),s=buildRequestBody(createPrompt(t));dlog(`[ToolDescription] calling ${St.ALPHA.GENERATE} with model: ${vt}`);const o=e.post({endpoint:St.ALPHA.GENERATE,body:s,headers:r,stream:!0}),i=await Promise.race([o,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),5e3))]);if(!i)return dlog("[ToolDescription] no response stream"),null;dlog("[ToolDescription] got response stream");const a=je.fromReadableStream(i);let l="",u=null;if(a.on("text",e=>{l+=e}),a.on("error",e=>{u=e}),await a.finalMessage(),u)throw u;dlog(`[ToolDescription] raw response: "${l}"`);const d=cleanDescription(l);if(d){if(Xb.size>=Jb){const e=Xb.keys().next().value;void 0!==e&&Xb.delete(e)}Xb.set(n,d),dlog(`[ToolDescription] cached: "${d}"`)}else dlog("[ToolDescription] description rejected after cleaning");return d}catch(t){return dlog(`[ToolDescription] failed for ${e}: ${t instanceof Error?t.message:String(t)}`),null}}function sanitize(e){return String(e).replace(/[\r\n\t\f\v]+/g," ").replace(/\s+/g," ").trim().slice(0,Zb)}function createPrompt(e){return`Precisely describe what this command does in active voice. Never use a word like "complex" or "risk" in description. Start with a verb, capital letter, no period. Never say you need to see more or that the command is incomplete — always describe what the command does based on what you see.\n\nFor simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):\n- ls → "List files in current directory"\n- git status → "Show working tree status"\n- npm install → "Install package dependencies"\n\nFor piped commands or obscure flags, add enough context to clarify what it does:\n- find . -name "*.tmp" -exec rm {} \\; → "Find and delete all .tmp files recursively"\n- git reset --hard origin/main → "Discard all local changes and match remote main"\n- curl -s url | jq '.data[]' → "Fetch JSON from URL and extract data array elements"\n\nCommand: ${`${sanitize(e.command||"")} ${sanitize(Array.isArray(e.args)?e.args.join(" "):e.args||"")}`.trim()}\n\nDescription:`}function cleanDescription(e){let t=e.trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim();return t.length>0&&(t=t.charAt(0).toUpperCase()+t.slice(1)),t.split(/\s+/).length<3?null:t}var vE=__esm({"src/utils/tool-description-generator.ts"(){Nt(),Ot(),bE(),ts(),dn(),CE(),en(),nr(),ar(),$n(),Jb=100,Xb=new Map,Zb=4e3,eE=80,tE=.3,nE=null,__name(getRequest,"getRequest"),__name(stableStringify,"stableStringify"),__name(generateCacheKey,"generateCacheKey"),__name(buildRequestBody,"buildRequestBody"),__name(getAuthHeaders,"getAuthHeaders"),__name(generateToolDescription,"generateToolDescription"),__name(sanitize,"sanitize"),__name(createPrompt,"createPrompt"),__name(cleanDescription,"cleanDescription")}});function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=f.homedir(),s=n.startsWith("~/")?t.join(r,n.slice(2)):n,o=t.resolve(s),i=t.join(r,".commandcode","plans");return o.startsWith(i+t.sep)||o===i}var TE,kE,_E,PE=__esm({"src/utils/plan-path-validator.ts"(){Nt(),Ot(),__name(isPlanPath,"isPlanPath")}});function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!kE.includes(e.name)):"plan"===n?t.filter(e=>!TE.includes(e.name)&&!_E.includes(e.name)):t.filter(e=>!kE.includes(e.name))}function isToolAllowedInMode(e){const{toolName:t,mode:n,toolParams:r}=e;if(!t||"string"!=typeof t)return{allowed:!1,reason:"Invalid tool name provided."};if("standard"===n||"auto-accept"===n)return{allowed:!0};if("plan"===n){if(isMcpTool(t))return{allowed:!1,reason:"MCP tools are not available in plan mode. Press Shift+Tab to exit plan mode first."};if("write_file"===t&&r?.filePath){const e=r.filePath;return isPlanPath({filePath:e})?{allowed:!0}:{allowed:!1,reason:`Cannot write to "${e}" in plan mode. Use the full absolute path ~/.commandcode/plans/<filename>.md to write plan files.`}}return TE.includes(t)?{allowed:!1,reason:`Tool "${t}" is not available in plan mode. Plan mode is read-only. Press Shift+Tab to exit plan mode.`}:{allowed:!0}}return{allowed:!1,reason:`Invalid permission mode "${n}". Please restart the application.`}}var AE,xE,IE,NE,RE=__esm({"src/tools/get-tools-for-mode.ts"(){Nt(),PE(),po(),TE=["edit_file","delete_file","shell_command","todo_write","kill_shell"],kE=["exit_plan_mode"],_E=["enter_plan_mode"],__name(getToolsForMode,"getToolsForMode"),__name(isToolAllowedInMode,"isToolAllowedInMode")}});function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(t*NE));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+=estimateTextTokens(JSON.stringify(n.input))*NE);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/IE;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)>AE}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."}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)}var $E=__esm({"src/utils/tokens.ts"(){Nt(),jr(),AE=Dr,xE=2e5,IE=3.5,NE=1.1,__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse")}});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 s=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(s),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}var LE,ME=__esm({"src/utils/sleep.ts"(){Nt(),__name(sleep,"sleep")}}),OE=__esm({"src/utils/logger.ts"(){Nt(),$n(),LE=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${be.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${be.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${be.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${be.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}}}});function getEnterpriseMemoryPath(){switch(h.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=h.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:E(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(E(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 s=getUserMemoryPath();return t.push({type:"user",path:s,exists:E(s),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return E(e)&&k(e).isFile()?await $.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}function getCodeBlockRegex(){return/```[\s\S]*?```|`[^`]+`/g}function getImportRegex(){return/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm}async function processImports(t,n,r=0,s=5){if(r>=s)return t;const o=[],i=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),a=Array.from(i.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let l=i;for(const t of a){const o=t[1];let i=o;o.startsWith("~/")?i=e.join(h.homedir(),o.slice(2)):e.isAbsolute(o)||(i=e.resolve(e.dirname(n),o));const a=await loadMemoryFile(i);if(a){const e=await processImports(a,i,r+1,s);l=l.replace(t[0],`\n# Imported from ${o}\n${e}\n`)}}return l=l.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>o[parseInt(t)]),l}async function loadAllMemories(t,n){const r=new Map,s=getEnterpriseMemoryPath();if(E(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const o=getUserMemoryPath();if(E(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const i=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of i)if(E(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 s of n){const n=e.isAbsolute(s)?e.dirname(s):e.dirname(e.resolve(t,s));if(n.startsWith(t)&&n!==t){const s=[];let o=n;for(;o.startsWith(t)&&o!==t;)s.push(o),o=e.dirname(o);for(const t of s.reverse()){const n=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of n)if(E(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 E(r)||await $.mkdir(r,{recursive:!0}),E(t)||await $.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const s=N(n,[t],{stdio:"inherit",shell:!0});s.on("exit",t=>{0===t?e():r(new Error(`Editor exited with code ${t}`))}),s.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 E(n)||await $.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 s=[],o=getEnterpriseMemoryPath(),i=getUserMemoryPath(),a=[e.join(n,"AGENTS.md"),e.join(n,".commandcode","AGENTS.md")];r.has(o)&&s.push(`# Memory from: ${o}\n\n${r.get(o)}`),r.has(i)&&s.push(`# Memory from: ${i}\n\n${r.get(i)}`);for(const e of a)if(r.has(e)){s.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===o||e===i||a.includes(e)||s.push(`# Memory from: ${e}\n\n${t}`);return s.join("\n\n---\n\n")}catch(e){return null}}var DE,qE=__esm({"src/utils/memory.ts"(){Nt(),Ot(),__name(getEnterpriseMemoryPath,"getEnterpriseMemoryPath"),__name(getUserMemoryPath,"getUserMemoryPath"),__name(getProjectMemoryPaths,"getProjectMemoryPaths"),__name(discoverMemoryFiles,"discoverMemoryFiles"),__name(loadMemoryFile,"loadMemoryFile"),__name(getCodeBlockRegex,"getCodeBlockRegex"),__name(getImportRegex,"getImportRegex"),__name(processImports,"processImports"),__name(loadAllMemories,"loadAllMemories"),__name(openInEditor,"openInEditor"),__name(initProjectMemory,"initProjectMemory"),__name(getMemoryContent,"getMemoryContent")}});function agentToTool(t,n){const{clientTools:r,serverTools:s,toolsMap:o,displayNameToToolName:i}=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,a)=>{let l=null;const u=Date.now();let d=null;try{const m=a?.permissionMode||"standard",p=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:s,toolsMap:o,displayNameToToolName:i}),clientTools:r,serverTools:s,mode:m});let g=Date.now();const h=10,f=[];if(a?.onFeedUpdate){const e=Ho(t.name,n);l=qo({name:t.name,input:e}),a.onFeedUpdate(l)}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3);const y=await getConfiguredProvider(),w=await isOAuthEnforced();let S;y===Ct.ANTHROPIC&&(S=await on.getValidAccessToken(),validateOAuthToken({token:S,provider:y}));const b=getApiBaseUrl(),E=new Vb({baseUrl:b});let C=0;const v=[];let T=n?.messages;if("string"==typeof T)try{T=JSON.parse(T)}catch(e){T=[]}if(Array.isArray(T)&&T.length>0)for(const e of T)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&v.push({role:"user",content:t})}const k={stream:!0,messages:v,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:p,model:`anthropic:${getConfiguredModel()}`},_=await isTasteLearningEnabled(),P={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.TASTE_LEARNING]:_.toString(),[wt.INTERNAL_TEAM_FLAG_HEADER]:w.toString()};S&&(P[wt.OAUTH_TOKEN]=`Bearer ${S}`);const A=getEnvironmentContext(),x=await getMemoryContent([]),I=crypto.randomUUID();let N="",R=!0;const $=__name(()=>{DE.debug("[Agent] Abort signal triggered, stopping immediately"),R=!1,d&&(clearInterval(d),d=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",$);try{for(;R;){if(a?.abortSignal?.aborted)throw DE.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:E,body:{mode:"custom-agent",config:A,memory:x,threadId:I,params:{...k,messages:v}},headers:P,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{C+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&l&&t-g>=h){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:C,elapsedSeconds:e}},a.onFeedUpdate(l),g=t}},"onTextDelta")});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(C=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if(N=t.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(t,a):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&&v.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&&v.push({role:"assistant",content:r});const s=[],o=new Set;let i=!1;for(const t of n){if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{const r=Ms.includes(t.name),p=Os.includes(t.name)?generateToolDescription(t.name,n).catch(()=>null):Promise.resolve(null);if(r&&a?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await p;if(!await a.onPermissionRequest(t.name,n,e)){DE.debug(`Permission denied for tool: ${t.name}`),i=!0;break}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let s=!1;const o=["path","file_path","absolutePath","filePath","directory","folder"];for(const t of o)if(t in r&&"string"==typeof r[t]){const n=r[t];if(!e.isAbsolute(n)){const o=e.resolve(process.cwd(),n);r[t]=o,s=!0,DE.debug(`Converted '${t}': '${n}' -> '${o}'`)}}"paths"in r&&Array.isArray(r.paths)&&(r.paths=r.paths.map(t=>"string"!=typeof t||e.isAbsolute(t)?t:(s=!0,e.resolve(process.cwd(),t)))),s?(n=r,DE.debug(`Resolved input for ${t.name}: ${Ho(t.name,n)}`)):DE.debug(`No path resolution needed for ${t.name}: ${Ho(t.name,n)}`)}if(a?.onFeedUpdate&&l){const e=Ho(t.name,n);f.push({name:t.name,input:e}),f.length>3&&f.shift();const r=Date.now(),s=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:C,elapsedSeconds:s,recentTools:[...f]}},DE.debug(`Updating agent with recentTools (${f.length} tools): ${JSON.stringify(f)}`),a.onFeedUpdate(l)}const g=await executeTool(t.name,n,{abortSignal:a?.abortSignal,permissionMode:m});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const h=checkToolOutputTokensLimit(g,t.name);if(s.push({type:"tool_result",tool_use_id:t.id,content:h}),o.add(t.id),a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:C,elapsedSeconds:t,recentTools:[...f]}},a.onFeedUpdate(l)}DE.debug(`Tool executed successfully: ${t.name}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";s.push({type:"tool_result",tool_use_id:t.id,content:`Error: ${n}`,is_error:!0}),o.add(t.id),DE.error(`Tool execution failed: ${t.name} - ${n}`)}}if(i){const e=v[v.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?o.has(e.id):"text"===e.type);t.length>0?e.content=t:v.pop()}R=!1;break}const p=[...s];v.push({role:"user",content:p})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",$)}if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:N||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:C,elapsedSeconds:t}},a.onFeedUpdate(l)}return N||"DONE"}catch(e){if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const t=Date.now(),n=(t-u)/1e3,r=e instanceof Error?e.message:"Unknown error",s="Interrupted by user"===r||a?.abortSignal?.aborted;l={...l,output:r,metadata:{isAgent:!0,status:s?"interrupted":"error",startTime:u,endTime:t,tokensUsed:l?.metadata?.tokensUsed||0,elapsedSeconds:n}},a.onFeedUpdate(l)}throw e}},"execute")}}function filterToolsForMode(e){const{tools:t,clientTools:n,serverTools:r,mode:s}=e;if("standard"===s||"auto-accept"===s)return t;const o=t.filter(e=>n.includes(e)),i=t.filter(e=>r.includes(e));return[...getToolsForMode({allTools:o,mode:s}),...i]}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:s,displayNameToToolName:o}=t;let i=[];if("*"===e.tools)i=[...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=o[e];if(!t&&s.has(e)&&(t=e),t){const e=s.get(t);if(e)i.push(e);else{const e=r.find(e=>e.name===t);e&&i.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=o[t];if(!e&&s.has(t)&&(e=t),e){const t=s.get(e);if(t)i.push(t);else{const t=r.find(t=>t.name===e);t&&i.push(t)}}}return i}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:s,onTextDelta:o}=e;let i=null;for(let e=0;e<5;e++){if(s?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:St.ALPHA.GENERATE,signal:s,headers:r}),i=je.fromReadableStream(e);o&&i.on("text",o);let a=null;i.on("error",e=>{a="AbortError"===e.name||s?.aborted?new Error("Interrupted by user"):e});const l=await i.finalMessage();if(a)throw a;return l}catch(t){if(i=t,s?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,s))throw formatAPIError(t,s);if(!isRetryableError(t)||4===e)throw formatAPIError(t,s);const n=200*Math.pow(2,e);DE.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:s})}}throw i||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 oi&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ai||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 oi&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof ai||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:s}=Ls({serverToolBlock:e,contentBlocks:r}),o=Ho(e.name,e.input),i={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:o,output:s?jo(n):n};t.onFeedUpdate(i)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}var FE,jE,zE=__esm({"src/tools/agents/execute.ts"(){Nt(),Ot(),dn(),ar(),bE(),ts(),en(),hi(),JE(),vE(),Gs(),RE(),$E(),ME(),OE(),Jo(),qE(),CE(),nr(),Gs(),DE=new LE("AgentExecutor"),__name(agentToTool,"agentToTool"),__name(filterToolsForMode,"filterToolsForMode"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks")}});function initializeAgentManager(e){jE=e}async function loadAgentTools(){if(!jE)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");FE.clear();for(const e of vl){const t=agentToTool(e,jE);FE.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,jE);FE.set(t.name,t)}}async function getAgentTools(){return 0===FE.size&&await loadAgentTools(),Array.from(FE.values())}async function getAgentTool(e){return 0===FE.size&&await loadAgentTools(),FE.get(e)}var BE=__esm({"src/tools/agents/manager.ts"(){Nt(),Fl(),zE(),_l(),FE=new Map,jE=null,__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool")}}),UE=__esm({"src/tools/agents/index.ts"(){Nt(),BE()}});function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,s=e.join(r,".commandcode","taste"),o=e.normalize(e.resolve(r,n)),i=e.normalize(s);return o.startsWith(i)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),s=e.normalize(e.join(h.homedir(),".commandcode","taste"));let o=null;if(n.startsWith(r)?o=r:n.startsWith(s)&&(o=s),!o)return{isTaste:!1};if(!n.endsWith("taste.md"))return{isTaste:!1};const i=e.relative(o,n).split(e.sep);return 1===i.length?{isTaste:!0}:2===i.length?{isTaste:!0,category:i[0]}:{isTaste:!1}}function getTasteAccessError(){return"Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system."}var WE,QE,GE,HE,VE,KE,YE=__esm({"src/utils/taste-path-validator.ts"(){Nt(),Ot(),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(getTasteAccessError,"getTasteAccessError")}});function isAgentTool(e){return!HE.has(e)&&!isMcpTool(e)}async function executeTool(e,t,n){if(isMcpTool(e)){const n=trackToolStart({toolName:e});try{const r=await executeMcpTool({prefixedName:e,args:t});return r.success?(n.end({status:"success"}),r.result??"Tool executed successfully"):(n.end({status:"error",error:new Error(r.error)}),`Error: ${r.error}`)}catch(e){const t=sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"mcp_tool_error"});return n.end({status:"error",error:t}),`Error: ${e instanceof Error?e.message:String(e)}`}}const r=n?.permissionMode||"standard",s=isToolAllowedInMode({toolName:e,mode:r,toolParams:t});if(!s.allowed)throw new Error(s.reason||`Tool "${e}" not allowed in ${r} mode`);let o=GE.get(e);if(o||(o=await getAgentTool(e)),!o){const t=await getAgentTools(),n=[...Array.from(GE.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 i=trackToolStart({toolName:e});try{let r;return r=(!GE.has(e)||!0===o.acceptsCallbacks)&&n?await o.execute(t,n):await o.execute(t),i.end({status:"success"}),r}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message){const t=sanitizeErrorForTelemetry({error:e,label:"tool_interrupted"});throw i.end({status:"error",error:t}),e}if(e instanceof Error){const t=sanitizeErrorForTelemetry({error:e,label:"tool_error"});return i.end({status:"error",error:t}),`Error: ${e.message}`}return i.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(e){const t=e?.mode||"standard",n=null!==sl()?[...WE]:WE.filter(e=>e.name!==Is.GET_DIAGNOSTICS),r=await getAgentTools(),s=getToolsForMode({allTools:n,mode:t}).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),o=r.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}));let i=[];return"plan"!==t&&getMcpConnectionManager().isInitialized&&(i=getAllMcpToolSchemas()),[...s,...o,...i,...QE]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}var JE=__esm({"src/tools/index.ts"(){Nt(),xi(),Gi(),Xi(),aa(),pa(),ba(),Pa(),Ra(),Ma(),qa(),Wa(),pl(),gl(),hl(),fl(),yl(),kl(),Sl(),Gs(),po(),mo(),UE(),YE(),Vr(),RE(),WE=[vi,Bi,Ki,ta,ua,fa,va,Ia,$a,Oa,ja,Ha,Va,Ka,El],QE=[Ya,Ja],GE=new Map(WE.map(e=>[e.name,e])),HE=new Set([...WE.map(e=>e.name),...QE.map(e=>e.name)]),__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase"),VE={},WE.forEach(e=>{VE[e.name]=toPascalCase(e.name)}),QE.forEach(e=>{VE[e.name]=toPascalCase(e.name)}),KE={},Object.entries(VE).forEach(([e,t])=>{KE[t]=e}),initializeAgentManager({clientTools:WE,serverTools:QE,toolsMap:GE,displayNameToToolName:KE})}});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 s=new TextDecoder,o=new TransformStream({transform(e,t){const o=s.decode(e,{stream:!0});r+=o;const i=r.split("\n");r=i.pop()??"";for(const e of i){const r=e.trim();if(!r){t.enqueue((new TextEncoder).encode(e+"\n"));continue}const s=parseErrorLine(r);if(s)return n=s,void t.error(new Error(`Error: Stream error: ${s.type} - ${s.message}`));t.enqueue((new TextEncoder).encode(e+"\n"))}},flush(e){const t=r.trim();if(t){const s=parseErrorLine(t);if(s)return n=s,void e.error(new Error(`Error: Stream error: ${s.type} - ${s.message}`));e.enqueue((new TextEncoder).encode(r))}}});return{stream:t.pipeThrough(o),getStreamError:__name(()=>n,"getStreamError")}}var XE,ZE,eC=__esm({"src/utils/stream-error-interceptor.ts"(){Nt(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors")}}),tC=__esm({"src/utils/learning-events.ts"(){Nt(),XE=class extends Re{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:s,label:o,sessionCount:i,promptCount:a,learningCount:l,categories:u,storage:d}=e,m={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:s,label:o,sessionCount:i,promptCount:a,learningCount:l,categories:u,storage:d};this.events.unshift(m),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",m)}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")}},ZE=new XE}});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}),s=extractLearnings({text:n}),o=new Map(r.map(e=>[e.text,e.confidence])),i=[],a=[],l=[];return s.forEach(e=>{const t=o.get(e.text);void 0===t?i.push(e):e.confidence>t?a.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&l.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:i,upgraded:a,downgraded:l}}var nC,rC,sC,oC,iC,aC,lC,cC,uC,dC,mC,pC=__esm({"src/utils/learning-parser.ts"(){Nt(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings")}}),gC=__esm({"src/agent/learning-agent.ts"(){Nt(),Ot(),dn(),CE(),JE(),ME(),$n(),tC(),pC(),OE(),nr(),ar(),Vr(),nC=new LE("LearningAgent"),rC=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:Br.LEARNING_AGENT,heading:"Learning pass failed"}}),ZE.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)];ZE.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const s=await this.getTasteStructure(),o=t.length-this.lastProcessedMessageIndex-1,i=Math.max(20,o),a=Math.max(0,t.length-i),l=t.slice(a);let u=0,d=!1;dlog(`[LearningAgent] analyzing ${o} new messages for patterns`);const m=[{role:"user",content:`Current taste structure:\n${s}\n\nRecent conversation:\n${JSON.stringify(l,null,2)}`}];for(;u<this.maxTurns;){const e=await this.callLearningAPI({conversation:m}),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")),m.push({role:"assistant",content:e.content}),m.push({role:"user",content:n}),u++}u>=this.maxTurns&&nC.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||ZE.addEvent({type:"no_learnings",message:"no changes to taste"}),ZE.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 s="",o="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(o=String(e.filePath||e.file_path||""),o)try{s=await w.promises.readFile(o,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const i=await executeTool(e.name,t,{allowTasteWrite:!0});let a="";if(("write_file"===e.name||"edit_file"===e.name)&&o)try{a=await w.promises.readFile(o,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=o.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:s,newText:a});(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=>{ZE.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{ZE.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{ZE.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:i})}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,s={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(!s||!r[s])return;const o=String(r[s]);if(e.isAbsolute(o))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: ${o}`);const i=e.normalize(o);if(i.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${o}`);const a=e.join(this.tasteDir,i);if(!e.normalize(a).startsWith(this.tasteDir))throw new Error(`Security: ${n} can only access files within .commandcode/taste/. Attempted: ${o}`)}adjustPathsForTaste(t){const{toolName:n,input:r}=t,s={...r},o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(o&&s[o]){const t=String(s[o]);let r;const i="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)&&t.startsWith(this.tasteDir))if(i){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(i&&!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`)}s[o]=r}return s}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(!w.existsSync(this.tasteDir)){w.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");w.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!w.existsSync(t))return!1;const n=w.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let s=n;for(const t of r){const n=t.name.toLowerCase().replace(/\s+/g,"-"),r=e.join(this.tasteDir,n),o=e.join(r,"taste.md");w.mkdirSync(r,{recursive:!0}),ZE.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const i=`# ${t.name}\n${t.learnings.join("\n")}\n`;w.writeFileSync(o,i,"utf-8");const a=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;s=s.replace(t.fullSection,a)}return w.writeFileSync(t,s,"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 s=t.filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:"));s.length>0&&n.push({name:r,learningCount:s.length,learnings:s,fullSection:`# ${e}`})}return n}async getTasteStructure(){return w.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(t){const{dir:n,prefix:r}=t,s=w.readdirSync(n,{withFileTypes:!0});let o="";for(let t=0;t<s.length;t++){const i=s[t],a=t===s.length-1,l=a?"└── ":"├── ";if(i.isDirectory()){o+=`${r}${l}${i.name}/\n`;const t=r+(a?" ":"│ ");o+=await this.buildTree({dir:e.join(n,i.name),prefix:t})}else if("taste.md"===i.name){const t=(w.readFileSync(e.join(n,i.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${r}${l}${i.name} (${t} learnings)\n`}else o+=`${r}${l}${i.name}\n`}return o}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let s;n===Ct.ANTHROPIC&&(s=await on.getValidAccessToken(),validateOAuthToken({token:s,provider:n}));const o={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(o[wt.OAUTH_TOKEN]=`Bearer ${s}`);const i=await this.getTasteTools(),a=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${a})`);const l={conversation:t,tools:i,model:a,threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:St.ALPHA.TASTE.LEARN,body:l,headers:o,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),u++,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:Br.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(u>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:Br.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":u}}),d;const n=1e3*Math.pow(2,u);dlog(`[LearningAgent] retrying API call (${u}/${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 w.existsSync(r)}}}}),hC=__esm({"src/agent/compact-agent.ts"(){Nt(),Ot(),dn(),CE(),en(),nr(),ar(),$n(),sC="claude-haiku-4-5-20251001",oC=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 s;n===Ct.ANTHROPIC&&(s=await on.getValidAccessToken(),validateOAuthToken({token:s,provider:n}));const o={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(o[wt.OAUTH_TOKEN]=`Bearer ${s}`);const i=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"),a={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${i}`}],model:`anthropic:${sC}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let l=0,u=null;for(;l<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${St.ALPHA.GENERATE} with model: ${sC}`);const e=await this.request.post({endpoint:St.ALPHA.GENERATE,body:a,headers:o,stream:!0});if(!e)throw new Error("No response stream received");const t=je.fromReadableStream(e);let n="",r=null;t.on("text",e=>{n+=e}),t.on("error",e=>{r=e});const s=await t.finalMessage();if(r)throw r;return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:s.usage.input_tokens,output:s.usage.output_tokens}}}catch(e){u=e instanceof Error?e:new Error(String(e)),l++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${u.message}`),u;if(l>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),u;const n=1e3*Math.pow(2,l);dlog(`[CompactAgent] retrying API call (${l}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}throw u||new Error("Compact API call failed")}}}});function migrateHeader(e){const{content:t}=e;if(t.includes(iC))return t.includes(lC)?t:t.includes(aC)?t.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"").replace(iC,lC):t.replace(iC,lC);let n=t;return n.includes(aC)&&(n=n.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"")),dC.test(n)?n=n.replace(dC,`$1${lC}`):mC.test(n)&&(n=n.replace(mC,`$1${lC}`)),n}var fC=__esm({"src/commands/taste/utils/header-migration.ts"(){Nt(),lC=`${iC="# Taste (Continuously Learned by [CommandCode][cmd])"}\n\n${aC="[cmd]: https://commandcode.ai/"}`,cC="# Taste (Continuously Learned by CommandCode)",uC="# Taste (Continuously Learned by CommandCode.ai)",dC=/^(\s*)# Taste \(Continuously Learned by CommandCode\)(?!\.ai)/,mC=/^(\s*)# Taste \(Continuously Learned by CommandCode\.ai\)/,__name(migrateHeader,"migrateHeader")}});async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!E(n))return null;const r=await $.readFile(n,"utf-8"),s=r.trim();return s&&s!==lC&&s!==iC&&s!==uC&&s!==cC?r:null}catch(e){return null}}var yC,wC,SC=__esm({"src/utils/taste/get-taste-content.ts"(){Nt(),Ot(),fC(),__name(getTasteContent,"getTasteContent")}});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={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};if(e===Ct.ANTHROPIC){const e=await on.getValidAccessToken();e&&(n[wt.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 s="",o="";for(const e of t)if(s||"user"!==e.message.role||(s=extractMessageText(e.message.content).slice(0,wC)),o||"assistant"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,wC)),s&&o)break;if(!s||!o)return;const i=`${yC}\n\nSession description:\n<description>User: ${s}\n\n---\n\nAssistant: ${o}</description>\n\nGenerate the session title now.`,a={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:i}],model:vt,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},l=await buildAuthHeaders(),u=await r.post({endpoint:St.ALPHA.GENERATE,body:a,headers:l,stream:!0}),d=je.fromReadableStream(u);let m="";d.on("text",e=>{m+=e}),await d.finalMessage(),m=m.trim(),m&&(await n.saveSessionTitle(m),dlog("Session",`Title generated: ${m}`))}var bC,EC,CC,vC=__esm({"src/chat/title-generator.ts"(){Nt(),dn(),CE(),en(),nr(),ar(),$n(),Ot(),yC="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",wC=1e3,__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle")}}),TC={};__export(TC,{ContextEngine:()=>CC});var kC,_C=__esm({"src/chat/context-engine.ts"(){Nt(),Zo(),dn(),gi(),hi(),Ci(),Jo(),Gs(),JE(),ME(),eC(),OE(),YE(),$E(),CE(),Vr(),ji(),ts(),bE(),Jl(),Ot(),en(),nr(),ar(),qE(),gC(),hC(),SC(),$n(),vC(),vE(),bC=new LE("ContextEngine"),EC=200,CC=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 Vb({baseUrl:n}),this.callbacks=e,this.sessionManager=new Yb(t),this.learningAgent=new rC({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new oC({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new Vb({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,bC.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),bC.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=Ao("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>bC.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n,r){let s=e,o=[];try{const t=await processFileReferences(e);if(s=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&&(s=`${n}\n\n${s}`);const i=Ao(r??e);t&&t.length>0&&(i.metadata={...i.metadata,images:t}),o&&o.length>0&&(i.metadata={...i.metadata,fileReferences:o}),this.callbacks.onFeedUpdate(i);const a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),s.trim()&&a.push({type:"text",text:s});const l={role:"user",content:a},u=crypto.randomUUID(),d=this.createMessageWithMeta(l,{messageId:u});this.addMessageAndSync(d),this.checkpointManager.createSnapshot({messageId:u}).catch(e=>bC.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,i).catch(e=>bC.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const m=await this.processMessages();return this.triggerTitleGeneration(),m}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){bC.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(),s=await this.callAPIWithRetry({body:n,headers:r});this.checkIfInterrupted(),this.updateContextUsage(s),await this.checkAndCompactIfNeeded();const o=s.content.filter(e=>"tool_use"===e.type),i=s.content.filter(e=>"server_tool_use"===e.type);if(e=i.length>0?this.processServerToolBlocks(s):s.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===o.length){const t=s.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===i.length){const t=Io(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>bC.error(`Failed to save messages: ${e}`))}if(0!==i.length&&this.sessionManager.saveMessages(this.messages).catch(e=>bC.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=Ao(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>bC.error(`Failed to save messages: ${e}`)),this.triggerLearningAgent();continue}}break}const a=s.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(a.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:a})),e.trim()){const t=Io(e);this.callbacks.onFeedUpdate(t)}const l=await this.executeToolBlocks({toolBlocks:o}),{toolResults:u,executedToolIds:d,permissionDenied:m}=l;if(m){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 p=[...u];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){p.push({type:"text",text:t});const e=Ao(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:p})),this.sessionManager.saveMessages(this.messages).catch(e=>bC.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&bC.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){bC.error(`Failed to load checkpoints for session ${e}: ${t}`)}const s=this.sessionManager.reconstructFeedFromMessages(t);return bC.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:s,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.sanitizeMessagesForAPI(this.messages.map(e=>e.message))}sanitizeMessagesForAPI(e){const t=[];for(const n of e){if("user"===n.role&&Array.isArray(n.content)){const e=t.length>0?t[t.length-1]:null,r=new Set;if("assistant"===e?.role&&Array.isArray(e.content))for(const t of e.content)"tool_use"===t.type&&r.add(t.id);const s=n.content.filter(e=>"tool_result"!==e.type||r.has(e.tool_use_id));s.length>0&&t.push({...n,content:s});continue}const e=t.length>0?t[t.length-1]:null;if(e&&e.role===n.role){const t=Array.isArray(e.content)?e.content:[{type:"text",text:e.content}],r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];e.content=[...t,...r];continue}t.push({...n})}return t}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};bC.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 s=0;const o=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],i=n.message.role;if(e&&t>=r&&-1!==r)o.push(n);else{if("user"===i){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){s+=estimateTokens(n.message);continue}o.push(n)}else o.push(n)}else if("assistant"===i){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)s+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?o.push({...n,message:{...n.message,content:r}}):s+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&o.push(n)}"user"!==i&&"assistant"!==i&&(s+=estimateTokens(n.message))}}this.messages=o,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,n-s);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:xE}),{messagesRemoved:t-o.length,tokensSaved:s}}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=$l.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:St.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=this.callbacks.getPermissionMode?.()||"standard",t=await getToolSchemas({mode:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let s;n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n),n===Ct.ANTHROPIC&&(s=await on.getValidAccessToken(),validateOAuthToken({token:s,provider:n}));const o={tools:t,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},i={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:o,threadId:this.sessionManager.getSessionId(),permissionMode:e};bC.debug(`calling API (${o.model}, ${this.messages.length} msgs, ${t.length} tools)`);const a=await isTasteLearningEnabled(),l={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.TASTE_LEARNING]:a.toString(),[wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(l[wt.OAUTH_TOKEN]=`Bearer ${s}`),{body:i,headers:l}}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:St.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const s=je.fromReadableStream(n);s.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let o=null;s.on("error",e=>{o="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const i=await s.finalMessage();if(o)throw o;return this.callbacks.onRetryUpdate?.(null),i}catch(e){const s=r?.(),o=s?Object.assign(new Error(s.message),{type:s.type,error:{type:s.type,message:s.message}}):e;if(t=o,this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(o))throw trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"non_retryable_api_error"}),context:{component:Br.CONTEXT_ENGINE,heading:"Non-retryable API error",code:o?.status||o?.statusCode}}),this.formatAPIError(o);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:Br.CONTEXT_ENGINE,code:o?.status||o?.statusCode,"retry.attempts":10}}),this.formatAPIError(o);trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"generate_retry_attempt"}),context:{heading:"Generate API retry",component:Br.CONTEXT_ENGINE,code:o?.status||o?.statusCode,"retry.attempt":n+1,"retry.max":10}});const i=Math.min(n,10),a=100*Math.pow(2,i),l=Math.max(a,1e3),u=Math.min(l,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:u,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,s="Insufficient credits"===t||n.includes("insufficient credits"),o=e instanceof ii||401===e?.status||e instanceof ai||403===e?.status,i=e?.type||e?.error?.type,a="rate_limit_error"===i||429===e?.status||n.includes("rate limit"),l="overloaded_error"===i||529===e?.status||n.includes("overloaded");return r||s||o||a||l}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,s=t.message;dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",s);const o=s?.toLowerCase().includes("insufficient credits");if(o)return new Error("Insufficient credits");const i=s?.toLowerCase().includes("oauth authentication required");if(i)return e;if(e instanceof ai||403===e?.status)return e;if(e instanceof ii||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 a=getSupportId();let l="";if(s)if(s.includes("Invalid 'Authorization' header"))l='Error: Authentication failed. Run "cmd login" to sign in again.';else{let e=s;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>EC&&(t=t.substring(0,EC)+"..."),l=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const o=s.toLowerCase(),i="overloaded_error"===r||o.includes("overloaded"),u="rate_limit_error"===r||o.includes("rate limit");l+=i?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":u?'\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"!==a&&(l+=`\nRequest ID: ${a}`)}else if(e.toString){const t=e.toString();l=t.length>EC?t.substring(0,EC)+"...":t}else l="Error: Unknown error occurred";return new Error(l)}async executeToolBlocks(e){const t=new Set;let n=!1;const r=[],s=[];for(const o of e.toolBlocks){this.checkIfInterrupted();const e=crypto.randomUUID(),i=Ms.includes(o.name),a=Os.includes(o.name)?this.getToolDescription(o):Promise.resolve(null);let l=null;try{i&&this.callbacks.onPermissionRequest&&(l=await a);const t=await this.checkToolPermission(o,l);if(t.needsPermission&&!t.allowed){this.handlePermissionDenied(o,e),n=!0;break}}catch(n){const r=n instanceof Error?n.message:"Permission check failed";this.showToolError(o,r,e,l),s.push({toolBlock:o,toolResult:{type:"tool_result",tool_use_id:o.id,content:`Error: ${r}`,is_error:!0}}),t.add(o.id);continue}null===l&&(l=await a),r.push({toolBlock:o,entryId:e,description:l})}const o=[];for(const{toolBlock:e,toolResult:n}of s)o.push(n),t.add(e.id);if(r.length>0){const e=await Promise.allSettled(r.map(async({toolBlock:e,entryId:t,description:n})=>{this.checkIfInterrupted();const r="edit_file"===e.name?await resolveEditStartLine({filePath:e.input.filePath,oldContent:e.input.oldValue}).catch(()=>{}):void 0,s=await this.executeSingleTool(e);return isAgentTool(e.name)||this.showToolSuccess(e,s,t,n,r),{toolBlock:e,toolResult:{type:"tool_result",tool_use_id:e.id,content:s}}}));for(let n=0;n<e.length;n++){const s=e[n],{toolBlock:i,entryId:a,description:l}=r[n];if("fulfilled"===s.status)o.push(s.value.toolResult),t.add(i.id);else{const e=s.reason instanceof Error?s.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(i.name)?t.add(i.id):(o.push({type:"tool_result",tool_use_id:i.id,content:`Error: ${e}`,is_error:!0}),t.add(i.id),this.showToolError(i,e,a,l))}}}return{toolResults:o,executedToolIds:t,permissionDenied:n}}async getToolDescription(e){try{return await Promise.race([generateToolDescription(e.name,e.input),new Promise(e=>setTimeout(()=>e(null),6e3))])}catch(t){return bC.debug(`Failed to generate description for ${e.name}: ${t instanceof Error?t.message:"Unknown error"}`),this.callbacks.onToolDescriptionError&&this.callbacks.onToolDescriptionError(e.name,t),null}}async checkToolPermission(e,t){return Ms.includes(e.name)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.name,e.input,t)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=this.callbacks.getPermissionMode?.()||"standard",n=await executeTool(e.name,e.input,{onPermissionRequest:this.callbacks.onPermissionRequest,onQuestionRequest:this.callbacks.onQuestionRequest,abortSignal:this.abortController?.signal,onFeedUpdate:this.callbacks.onFeedUpdate,permissionMode:t});this.checkIfInterrupted();const r=checkToolOutputTokensLimit(n,e.name),s=estimateTokens(r);return this.currentInteractionTokens+=s,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),r}handlePermissionDenied(e,t){const n=Ho(e.name,e.input),r={..."edit_file"===e.name?e.input:{},permissionDenied:!0},s={...No(e.name,n,r),id:t},o=Fo(s,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}showToolSuccess(e,t,n,r,s){let o="edit_file"===e.name?{...e.input,...void 0!==s?{startLine:s}:{}}: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&&(o={...o||{},isTasteFile:!0,tasteCategory:e.category})}}const i={...e.input,...o?.isTasteFile?{isTasteFile:o.isTasteFile}:{},...o?.tasteCategory?{tasteCategory:o.tasteCategory}:{}},a=Ho(e.name,i),l={...No(e.name,a,o),id:n,...r?{description:r}:{}},u=Fo(l,t);this.callbacks.onFeedUpdate(u)}showToolError(e,t,n,r){const s=Ho(e.name,e.input),o="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,i={...No(e.name,s,o),id:n,...r?{description:r}:{}},a=Fo(i,jo(t));this.callbacks.onFeedUpdate(a)}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=Io(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:s}=Ls({serverToolBlock:e,contentBlocks:n}),o=Ho(e.name,e.input),i=No(e.name,o),a=Fo(i,s?jo(r):r);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=Io(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:xE})}async checkAndCompactIfNeeded(){const e=Math.floor(xE*At.TIER_1_THRESHOLD),t=Math.floor(xE*At.TIER_2_THRESHOLD),n=Math.floor(xE*At.TIER_3_THRESHOLD);try{if(this.contextTokensUsed>n){bC.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 this.emitAutoCompactInfo(t)}if(this.contextTokensUsed>t){bC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${At.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT);return bC.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void this.emitAutoCompactInfo(e.tokensSaved)}if(this.contextTokensUsed>e){const t=this.countToolCalls(),n=At.TIER_1_KEEP_COUNT;if(t>n){bC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);bC.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){bC.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){e>0&&this.callbacks.onFeedUpdate(xo(`Auto-compacted conversation, saved ~${e.toLocaleString()} tokens.`,{isAutoCompact:!0}))}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 s=new Set(r.slice(-e).map(e=>e.id)),o=new Set(r.filter(e=>!s.has(e.id)).map(e=>e.id)),i=[];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||!o.has(e.tool_use_id)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_use"!==e.type||!o.has(e.id)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}i.push(e)}this.messages=i,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,t-n);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:xE}),{toolsRemoved:o.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return bC.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT);bC.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});bC.debug(`Summarization complete: ${r.summary.length} chars, used ${r.tokensUsed.input}/${r.tokensUsed.output} tokens`);const s=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}),o=this.contextTokensUsed,i=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[s,...t],await this.sessionManager.saveMessages(this.messages);const a=estimateTokens(s.message),l=Math.max(0,o-i+a);this.contextTokensUsed=l,this.callbacks.onContextUsageUpdate?.({current:l,limit:xE}),bC.debug(`Tier 3 summarization complete: reduced from ${o} to ~${l} tokens`)}catch(e){bC.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=At.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r],o=estimateTokens(s.message);if(t+o>e){n=r+1;break}t+=o;const i=s.message.content;Array.isArray(i)&&i.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 s=0;if(-1!==r&&("conversation"===n||"both"===n))for(let e=r;e<this.messages.length;e++)s+=estimateTokens(this.messages[e].message);const o=await this.checkpointManager.restore({messageId:t,mode:n});return!o.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-s),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:xE})),o}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}}}}),PC=__esm({"src/utils/clear-console.ts"(){Nt(),kC=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole")}});async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new Vb({baseUrl:e});return await t.get({endpoint:St.ALPHA.WHOAMI})}var AC=__esm({"src/utils/get-entity.ts"(){Nt(),ts(),bE(),Ot(),__name(getAuthenticatedEntity,"getAuthenticatedEntity")}}),xC={};async function getBillingLink({billingLink:e,setBillingLink:t}){if(e)return e;try{const e=await getAuthKey();if(!e)return;const n=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return t(e),e}if(n.org){const e=`https://commandcode.ai/${n.org.login}/settings/billing`;return t(e),e}}catch{return"https://commandcode.ai/settings/billing"}}async function handleSubmit({role:e,input:t,images:n,ideContext:r,displayMessage:s,feed:o,setFeed:i,isCmdCodeBusy:a,setIsCmdCodeBusy:l,setQueuedMessages:u,setStatus:d,setInteractionTokens:m,updateStatus:p,setUpdateStatus:g,billingLink:h,setBillingLink:f,contextEngineRef:y,isSubmittingRef:w,setInput:S,setStaticKey:b,executeBash:E}){if(!t.length)return;if(p&&g(null),m(0),"bash"===e){if(w.current)return;w.current=!0;const e=Ro(t);return i([...o,e]),S(""),await E(t,e=>{i(e)},()=>{kC(),b(e=>e+1)}),void(w.current=!1)}if(a)return u(e=>[...e,s??t]),void S("");if(w.current)return;w.current=!0,l(!0),d(Wo()),S("");let C=!1;try{y.current&&await y.current.sendMessage(t,n,r,s)}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)return void(C=!0);if(C=!0,"Insufficient credits"===e.message){d("Insufficient credits");const e=`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${await getBillingLink({billingLink:h,setBillingLink:f})}`;return void i(t=>[...t,Lo(e)])}if(e.message.startsWith("Error:"))return d("Error"),void i(t=>[...t,Lo(e.message)]);d("Error");const t=e.message||"An unexpected error occurred";i(e=>[...e,Lo(t)])}finally{l(!1),C||d("Ready..."),w.current=!1}}__export(xC,{getBillingLink:()=>getBillingLink,handleSubmit:()=>handleSubmit});var IC=__esm({"src/tui/actions/submit.ts"(){Nt(),Jo(),Qs(),AC(),Ot(),PC(),__name(getBillingLink,"getBillingLink"),__name(handleSubmit,"handleSubmit")}});Nt(),Nt();var NC=process.argv.includes("-d")||process.argv.includes("--debug");NC&&(process.env.DEBUG="true"),NC||(process.removeAllListeners("warning"),process.on("warning",()=>{})),Nt(),Nt(),Vr();var{red:RC,yellow:$C,dim:LC}=Be,MC=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:s=!0,skipTelemetry:o=!1}=e;if(n){if(o||trackError({error:sanitizeErrorForTelemetry({error:n,label:"cli_error"}),context:{component:Br.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Ue.error} ${RC(t)}`),console.log(`${Ue.error} ${RC("ERROR →")} ${n.name}`),console.log(`${Ue.info} ${RC("REASON →")} ${n.message}`),console.log(`${Ue.info} ${RC("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Ue.info} ${LC(`Request ID: ${e}`)}`),console.log(`${LC(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Ue.warning} ${$C(t)}\n`);if(!s)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:Br.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),MC({heading:ze`CRITICAL: Unhandled Promise Rejection!
251
+ `}),index("subscriptions_owner_idx").on(e.userId,e.orgId)])),b2(Bb)}}),gE=__esm({"../shared/src/database/schema/free-credits-audit.ts"(){Nt(),fh(),rE(),Sh(),Ub=sql`(SELECT NULLIF(current_setting('app.current_user_id', true), '')::uuid)`,Wb=sql`users`,c(Qb=Pp("free_credits_audit",{id:uuid("id").defaultRandom().primaryKey(),date:date("date").notNull().unique(),totalCreditsGiven:numeric("total_credits_given").notNull(),syncedAt:timestamp("synced_at",{withTimezone:!0}).notNull()},e=>[index("free_credits_audit_date_idx").on(e.date),pgPolicy("free_credits_audit_select_admin",{as:"permissive",to:"app_user",for:"select",using:sql`(SELECT admin FROM ${Wb} WHERE id = ${Ub})`}),pgPolicy("free_credits_audit_insert_admin",{as:"permissive",to:"app_user",for:"insert",withCheck:sql`(SELECT admin FROM ${Wb} WHERE id = ${Ub})`}),pgPolicy("free_credits_audit_update_admin",{as:"permissive",to:"app_user",for:"update",using:sql`(SELECT admin FROM ${Wb} WHERE id = ${Ub})`}),pgPolicy("free_credits_audit_delete_admin",{as:"permissive",to:"app_user",for:"delete",using:sql`(SELECT admin FROM ${Wb} WHERE id = ${Ub})`})])),b2(Qb)}}),hE=__esm({"../shared/src/database/schema/follows.ts"(){Nt(),fh(),Sh(),rE(),sE(),oE(),Gb=sql`(SELECT NULLIF(current_setting('app.current_user_id', true), '')::uuid)`,c(Hb=Pp("follows",{id:uuid("id").defaultRandom().primaryKey(),followerId:uuid("follower_id").references(()=>eb.id,{onUpdate:"cascade",onDelete:"cascade"}).notNull(),followedUserId:uuid("followed_user_id").references(()=>eb.id,{onUpdate:"cascade",onDelete:"cascade"}),followedOrgId:uuid("followed_org_id").references(()=>nb.id,{onUpdate:"cascade",onDelete:"cascade"}),createdAt:timestamp("created_at",{withTimezone:!0}).defaultNow().notNull()},e=>[check("follows_exactly_one_target",sql`(followed_user_id IS NOT NULL AND followed_org_id IS NULL) OR (followed_user_id IS NULL AND followed_org_id IS NOT NULL)`),check("follows_no_self_follow",sql`follower_id != followed_user_id OR followed_user_id IS NULL`),uniqueIndex("follows_user_unique").on(e.followerId,e.followedUserId).where(sql`followed_user_id IS NOT NULL`),uniqueIndex("follows_org_unique").on(e.followerId,e.followedOrgId).where(sql`followed_org_id IS NOT NULL`),index("follows_follower_idx").on(e.followerId),index("follows_followed_user_idx").on(e.followedUserId),index("follows_followed_org_idx").on(e.followedOrgId),pgPolicy("follows_select_all",{for:"select",to:"app_user",using:sql`true`}),pgPolicy("follows_insert_own",{for:"insert",to:"app_user",withCheck:sql`follower_id = ${Gb}`}),pgPolicy("follows_delete_own",{for:"delete",to:"app_user",using:sql`follower_id = ${Gb}`}),pgPolicy("follows_select_public",{for:"select",to:"public_user",using:sql`true`})])),b2(Hb)}}),fE=__esm({"../shared/src/database/schema/index.ts"(){Nt(),oE(),iE(),aE(),sE(),lE(),cE(),uE(),dE(),mE(),pE(),gE(),hE()}}),yE=__esm({"../shared/src/database/config/database.ts"(){Nt(),eu(),fE()}}),wE=__esm({"../shared/src/database/index.ts"(){Nt(),yE(),fE()}}),SE=__esm({"../shared/src/index.ts"(){Nt(),jl(),zl(),Yl(),Jl(),Xl(),Ot(),Rt(),wE()}}),bE=__esm({"src/api/request.ts"(){Nt(),Qs(),hi(),Vr(),Tr(),cr(),SE(),Vb=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=trackAPICallStart({method:e.method,endpoint:t}),s=await this.buildHeaders({headers:e.headers,span:r.span});let o;try{o=await this.makeRequest({url:n,options:e,headers:s})}catch(e){const t=new si({cause:e instanceof Error?e:void 0});throw r.end({statusCode:0,error:t}),t}if(!o.ok){const{error:e}=await this.handleErrorResponse({response:o});throw r.end({statusCode:o.status,error:e}),e}return r.end({statusCode:o.status}),e.stream?o.body:o.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e,span:t}){const n=await getAuthKey(),r=getTraceId(),s=t?.spanContext(),o=r&&s?.spanId?`00-${r}-${s.spanId}-01`:void 0,i=getTelemetryEnv(),a="prod"===i?"production":i;return{"Content-Type":"application/json",[wt.CLI_ENVIRONMENT]:a,...n?{Authorization:`Bearer ${n}`}:{},...o?{traceparent:o}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,s=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const o=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return s&&clearTimeout(s),o}catch(e){throw s&&clearTimeout(s),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:ri.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"})}}}}),EE=__esm({"src/utils/strip-ide-context.ts"(){Nt(),Kb=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext")}}),CE=__esm({"src/sessions/index.ts"(){Nt(),Jo(),Ci(),Ot(),Vr(),$n(),EE(),Yb=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(f.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Ne(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=I("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await L.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:Br.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await L.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(),s={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(s)),this.lastMessageId=e}await L.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 L.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(),s=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=Kb(n),n&&t.push({id:s,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)t.push({id:s,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=Ho(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=Ho(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 L.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 L.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await L.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 L.access(n)}catch{return[]}const e=(await L.readdir(n)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),r=[];for(const s of e){const e=s.replace(".jsonl",""),o=t.join(n,s);try{const t=await L.stat(o),s=(await L.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(s.length>0){let o="",i="";const a=JSON.parse(s[0]);a.gitBranch&&(i=a.gitBranch);for(const e of s){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)o=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){o=e.text;break}}else t.content?.input&&(o=t.content.input);if(o)break}}o=Kb(o);const l=await _SessionManager.loadSessionMetaForId(e,n),u=l?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:o||"No messages",title:u||void 0,messageCount:s.length,projectPath:n,gitBranch:i||"-"})}}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 L.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 L.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 L.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await L.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 L.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 L.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 L.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const s=n.findIndex(e=>e.messageId===t.messageId);-1!==s?n[s]=e:n.push(e);const o=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await L.writeFile(r,o)}else await L.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 L.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 L.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),s=e.findIndex(e=>e.messageId===t);if(-1===s)return;const o=(n?e.slice(0,s):e.slice(0,s+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await L.writeFile(r,o)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let s="";if("string"==typeof r.message.content)s=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(s+=e.text);return s=Kb(s),{messageId:r.meta.messageId||crypto.randomUUID(),content:s}}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}}}});function getRequest(){return nE||(nE=new Vb({baseUrl:getApiBaseUrl()})),nE}function stableStringify(e){return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map(stableStringify).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+stableStringify(e[t])).join(",")+"}"}function generateCacheKey(e,t){return`${e}:${stableStringify(t)}`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:vt,max_tokens:eE,temperature:tE,stream:!0},threadId:crypto.randomUUID()}}async function getAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced();let n;e===Ct.ANTHROPIC&&(n=await on.getValidAccessToken(),validateOAuthToken({token:n,provider:e}));const r={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(r[wt.OAUTH_TOKEN]=`Bearer ${n}`),r}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=Xb.get(n);if(r)return Xb.delete(n),Xb.set(n,r),dlog(`[ToolDescription] cache hit for ${e}: "${r}"`),r;dlog(`[ToolDescription] generating for ${e}`);try{const e=getRequest(),r=await getAuthHeaders(),s=buildRequestBody(createPrompt(t));dlog(`[ToolDescription] calling ${St.ALPHA.GENERATE} with model: ${vt}`);const o=e.post({endpoint:St.ALPHA.GENERATE,body:s,headers:r,stream:!0}),i=await Promise.race([o,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),5e3))]);if(!i)return dlog("[ToolDescription] no response stream"),null;dlog("[ToolDescription] got response stream");const a=je.fromReadableStream(i);let l="",u=null;if(a.on("text",e=>{l+=e}),a.on("error",e=>{u=e}),await a.finalMessage(),u)throw u;dlog(`[ToolDescription] raw response: "${l}"`);const d=cleanDescription(l);if(d){if(Xb.size>=Jb){const e=Xb.keys().next().value;void 0!==e&&Xb.delete(e)}Xb.set(n,d),dlog(`[ToolDescription] cached: "${d}"`)}else dlog("[ToolDescription] description rejected after cleaning");return d}catch(t){return dlog(`[ToolDescription] failed for ${e}: ${t instanceof Error?t.message:String(t)}`),null}}function sanitize(e){return String(e).replace(/[\r\n\t\f\v]+/g," ").replace(/\s+/g," ").trim().slice(0,Zb)}function createPrompt(e){return`Precisely describe what this command does in active voice. Never use a word like "complex" or "risk" in description. Start with a verb, capital letter, no period. Never say you need to see more or that the command is incomplete — always describe what the command does based on what you see.\n\nFor simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):\n- ls → "List files in current directory"\n- git status → "Show working tree status"\n- npm install → "Install package dependencies"\n\nFor piped commands or obscure flags, add enough context to clarify what it does:\n- find . -name "*.tmp" -exec rm {} \\; → "Find and delete all .tmp files recursively"\n- git reset --hard origin/main → "Discard all local changes and match remote main"\n- curl -s url | jq '.data[]' → "Fetch JSON from URL and extract data array elements"\n\nCommand: ${`${sanitize(e.command||"")} ${sanitize(Array.isArray(e.args)?e.args.join(" "):e.args||"")}`.trim()}\n\nDescription:`}function cleanDescription(e){let t=e.trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim();return t.length>0&&(t=t.charAt(0).toUpperCase()+t.slice(1)),t.split(/\s+/).length<3?null:t}var vE=__esm({"src/utils/tool-description-generator.ts"(){Nt(),Ot(),bE(),ts(),dn(),CE(),en(),nr(),ar(),$n(),Jb=100,Xb=new Map,Zb=4e3,eE=80,tE=.3,nE=null,__name(getRequest,"getRequest"),__name(stableStringify,"stableStringify"),__name(generateCacheKey,"generateCacheKey"),__name(buildRequestBody,"buildRequestBody"),__name(getAuthHeaders,"getAuthHeaders"),__name(generateToolDescription,"generateToolDescription"),__name(sanitize,"sanitize"),__name(createPrompt,"createPrompt"),__name(cleanDescription,"cleanDescription")}});function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=f.homedir(),s=n.startsWith("~/")?t.join(r,n.slice(2)):n,o=t.resolve(s),i=t.join(r,".commandcode","plans");return o.startsWith(i+t.sep)||o===i}var TE,kE,_E,PE=__esm({"src/utils/plan-path-validator.ts"(){Nt(),Ot(),__name(isPlanPath,"isPlanPath")}});function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!kE.includes(e.name)):"plan"===n?t.filter(e=>!TE.includes(e.name)&&!_E.includes(e.name)):t.filter(e=>!kE.includes(e.name))}function isToolAllowedInMode(e){const{toolName:t,mode:n,toolParams:r}=e;if(!t||"string"!=typeof t)return{allowed:!1,reason:"Invalid tool name provided."};if("standard"===n||"auto-accept"===n)return{allowed:!0};if("plan"===n){if(isMcpTool(t))return{allowed:!1,reason:"MCP tools are not available in plan mode. Press Shift+Tab to exit plan mode first."};if("write_file"===t&&r?.filePath){const e=r.filePath;return isPlanPath({filePath:e})?{allowed:!0}:{allowed:!1,reason:`Cannot write to "${e}" in plan mode. Use the full absolute path ~/.commandcode/plans/<filename>.md to write plan files.`}}return TE.includes(t)?{allowed:!1,reason:`Tool "${t}" is not available in plan mode. Plan mode is read-only. Press Shift+Tab to exit plan mode.`}:{allowed:!0}}return{allowed:!1,reason:`Invalid permission mode "${n}". Please restart the application.`}}var AE,xE,IE,NE,RE=__esm({"src/tools/get-tools-for-mode.ts"(){Nt(),PE(),po(),TE=["edit_file","delete_file","shell_command","todo_write","kill_shell"],kE=["exit_plan_mode"],_E=["enter_plan_mode"],__name(getToolsForMode,"getToolsForMode"),__name(isToolAllowedInMode,"isToolAllowedInMode")}});function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(t*NE));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+=estimateTextTokens(JSON.stringify(n.input))*NE);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/IE;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)>AE}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."}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)}var $E=__esm({"src/utils/tokens.ts"(){Nt(),jr(),AE=Dr,xE=2e5,IE=3.5,NE=1.1,__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse")}});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 s=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(s),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}var LE,ME=__esm({"src/utils/sleep.ts"(){Nt(),__name(sleep,"sleep")}}),OE=__esm({"src/utils/logger.ts"(){Nt(),$n(),LE=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${be.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${be.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${be.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${be.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}}}});function getEnterpriseMemoryPath(){switch(h.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=h.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:E(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(E(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 s=getUserMemoryPath();return t.push({type:"user",path:s,exists:E(s),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return E(e)&&k(e).isFile()?await $.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}function getCodeBlockRegex(){return/```[\s\S]*?```|`[^`]+`/g}function getImportRegex(){return/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm}async function processImports(t,n,r=0,s=5){if(r>=s)return t;const o=[],i=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),a=Array.from(i.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let l=i;for(const t of a){const o=t[1];let i=o;o.startsWith("~/")?i=e.join(h.homedir(),o.slice(2)):e.isAbsolute(o)||(i=e.resolve(e.dirname(n),o));const a=await loadMemoryFile(i);if(a){const e=await processImports(a,i,r+1,s);l=l.replace(t[0],`\n# Imported from ${o}\n${e}\n`)}}return l=l.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>o[parseInt(t)]),l}async function loadAllMemories(t,n){const r=new Map,s=getEnterpriseMemoryPath();if(E(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const o=getUserMemoryPath();if(E(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const i=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of i)if(E(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 s of n){const n=e.isAbsolute(s)?e.dirname(s):e.dirname(e.resolve(t,s));if(n.startsWith(t)&&n!==t){const s=[];let o=n;for(;o.startsWith(t)&&o!==t;)s.push(o),o=e.dirname(o);for(const t of s.reverse()){const n=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of n)if(E(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 E(r)||await $.mkdir(r,{recursive:!0}),E(t)||await $.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const s=N(n,[t],{stdio:"inherit",shell:!0});s.on("exit",t=>{0===t?e():r(new Error(`Editor exited with code ${t}`))}),s.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 E(n)||await $.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 s=[],o=getEnterpriseMemoryPath(),i=getUserMemoryPath(),a=[e.join(n,"AGENTS.md"),e.join(n,".commandcode","AGENTS.md")];r.has(o)&&s.push(`# Memory from: ${o}\n\n${r.get(o)}`),r.has(i)&&s.push(`# Memory from: ${i}\n\n${r.get(i)}`);for(const e of a)if(r.has(e)){s.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===o||e===i||a.includes(e)||s.push(`# Memory from: ${e}\n\n${t}`);return s.join("\n\n---\n\n")}catch(e){return null}}var DE,qE=__esm({"src/utils/memory.ts"(){Nt(),Ot(),__name(getEnterpriseMemoryPath,"getEnterpriseMemoryPath"),__name(getUserMemoryPath,"getUserMemoryPath"),__name(getProjectMemoryPaths,"getProjectMemoryPaths"),__name(discoverMemoryFiles,"discoverMemoryFiles"),__name(loadMemoryFile,"loadMemoryFile"),__name(getCodeBlockRegex,"getCodeBlockRegex"),__name(getImportRegex,"getImportRegex"),__name(processImports,"processImports"),__name(loadAllMemories,"loadAllMemories"),__name(openInEditor,"openInEditor"),__name(initProjectMemory,"initProjectMemory"),__name(getMemoryContent,"getMemoryContent")}});function agentToTool(t,n){const{clientTools:r,serverTools:s,toolsMap:o,displayNameToToolName:i}=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,a)=>{let l=null;const u=Date.now();let d=null;try{const m=a?.permissionMode||"standard",p=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:s,toolsMap:o,displayNameToToolName:i}),clientTools:r,serverTools:s,mode:m});let g=Date.now();const h=10,f=[];if(a?.onFeedUpdate){const e=Ho(t.name,n);l=qo({name:t.name,input:e}),a.onFeedUpdate(l)}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3);const y=await getConfiguredProvider(),w=await isOAuthEnforced();let S;y===Ct.ANTHROPIC&&(S=await on.getValidAccessToken(),validateOAuthToken({token:S,provider:y}));const b=getApiBaseUrl(),E=new Vb({baseUrl:b});let C=0;const v=[];let T=n?.messages;if("string"==typeof T)try{T=JSON.parse(T)}catch(e){T=[]}if(Array.isArray(T)&&T.length>0)for(const e of T)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&v.push({role:"user",content:t})}const k={stream:!0,messages:v,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:p,model:`anthropic:${getConfiguredModel()}`},_=await isTasteLearningEnabled(),P={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.TASTE_LEARNING]:_.toString(),[wt.INTERNAL_TEAM_FLAG_HEADER]:w.toString()};S&&(P[wt.OAUTH_TOKEN]=`Bearer ${S}`);const A=getEnvironmentContext(),x=await getMemoryContent([]),I=crypto.randomUUID();let N="",R=!0;const $=__name(()=>{DE.debug("[Agent] Abort signal triggered, stopping immediately"),R=!1,d&&(clearInterval(d),d=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",$);try{for(;R;){if(a?.abortSignal?.aborted)throw DE.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:E,body:{mode:"custom-agent",config:A,memory:x,threadId:I,params:{...k,messages:v}},headers:P,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{C+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&l&&t-g>=h){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:C,elapsedSeconds:e}},a.onFeedUpdate(l),g=t}},"onTextDelta")});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(C=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if(N=t.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(t,a):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&&v.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&&v.push({role:"assistant",content:r});const s=[],o=new Set;let i=!1;for(const t of n){if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{const r=Ms.includes(t.name),p=Os.includes(t.name)?generateToolDescription(t.name,n).catch(()=>null):Promise.resolve(null);if(r&&a?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await p;if(!await a.onPermissionRequest(t.name,n,e)){DE.debug(`Permission denied for tool: ${t.name}`),i=!0;break}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let s=!1;const o=["path","file_path","absolutePath","filePath","directory","folder"];for(const t of o)if(t in r&&"string"==typeof r[t]){const n=r[t];if(!e.isAbsolute(n)){const o=e.resolve(process.cwd(),n);r[t]=o,s=!0,DE.debug(`Converted '${t}': '${n}' -> '${o}'`)}}"paths"in r&&Array.isArray(r.paths)&&(r.paths=r.paths.map(t=>"string"!=typeof t||e.isAbsolute(t)?t:(s=!0,e.resolve(process.cwd(),t)))),s?(n=r,DE.debug(`Resolved input for ${t.name}: ${Ho(t.name,n)}`)):DE.debug(`No path resolution needed for ${t.name}: ${Ho(t.name,n)}`)}if(a?.onFeedUpdate&&l){const e=Ho(t.name,n);f.push({name:t.name,input:e}),f.length>3&&f.shift();const r=Date.now(),s=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:C,elapsedSeconds:s,recentTools:[...f]}},DE.debug(`Updating agent with recentTools (${f.length} tools): ${JSON.stringify(f)}`),a.onFeedUpdate(l)}const g=await executeTool(t.name,n,{abortSignal:a?.abortSignal,permissionMode:m});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const h=checkToolOutputTokensLimit(g,t.name);if(s.push({type:"tool_result",tool_use_id:t.id,content:h}),o.add(t.id),a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:C,elapsedSeconds:t,recentTools:[...f]}},a.onFeedUpdate(l)}DE.debug(`Tool executed successfully: ${t.name}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";s.push({type:"tool_result",tool_use_id:t.id,content:`Error: ${n}`,is_error:!0}),o.add(t.id),DE.error(`Tool execution failed: ${t.name} - ${n}`)}}if(i){const e=v[v.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?o.has(e.id):"text"===e.type);t.length>0?e.content=t:v.pop()}R=!1;break}const p=[...s];v.push({role:"user",content:p})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",$)}if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:N||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:C,elapsedSeconds:t}},a.onFeedUpdate(l)}return N||"DONE"}catch(e){if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const t=Date.now(),n=(t-u)/1e3,r=e instanceof Error?e.message:"Unknown error",s="Interrupted by user"===r||a?.abortSignal?.aborted;l={...l,output:r,metadata:{isAgent:!0,status:s?"interrupted":"error",startTime:u,endTime:t,tokensUsed:l?.metadata?.tokensUsed||0,elapsedSeconds:n}},a.onFeedUpdate(l)}throw e}},"execute")}}function filterToolsForMode(e){const{tools:t,clientTools:n,serverTools:r,mode:s}=e;if("standard"===s||"auto-accept"===s)return t;const o=t.filter(e=>n.includes(e)),i=t.filter(e=>r.includes(e));return[...getToolsForMode({allTools:o,mode:s}),...i]}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:s,displayNameToToolName:o}=t;let i=[];if("*"===e.tools)i=[...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=o[e];if(!t&&s.has(e)&&(t=e),t){const e=s.get(t);if(e)i.push(e);else{const e=r.find(e=>e.name===t);e&&i.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=o[t];if(!e&&s.has(t)&&(e=t),e){const t=s.get(e);if(t)i.push(t);else{const t=r.find(t=>t.name===e);t&&i.push(t)}}}return i}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:s,onTextDelta:o}=e;let i=null;for(let e=0;e<5;e++){if(s?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:St.ALPHA.GENERATE,signal:s,headers:r}),i=je.fromReadableStream(e);o&&i.on("text",o);let a=null;i.on("error",e=>{a="AbortError"===e.name||s?.aborted?new Error("Interrupted by user"):e});const l=await i.finalMessage();if(a)throw a;return l}catch(t){if(i=t,s?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,s))throw formatAPIError(t,s);if(!isRetryableError(t)||4===e)throw formatAPIError(t,s);const n=200*Math.pow(2,e);DE.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:s})}}throw i||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 oi&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ai||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 oi&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof ai||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:s}=Ls({serverToolBlock:e,contentBlocks:r}),o=Ho(e.name,e.input),i={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:o,output:s?jo(n):n};t.onFeedUpdate(i)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}var FE,jE,zE=__esm({"src/tools/agents/execute.ts"(){Nt(),Ot(),dn(),ar(),bE(),ts(),en(),hi(),JE(),vE(),Gs(),RE(),$E(),ME(),OE(),Jo(),qE(),CE(),nr(),Gs(),DE=new LE("AgentExecutor"),__name(agentToTool,"agentToTool"),__name(filterToolsForMode,"filterToolsForMode"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks")}});function initializeAgentManager(e){jE=e}async function loadAgentTools(){if(!jE)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");FE.clear();for(const e of vl){const t=agentToTool(e,jE);FE.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,jE);FE.set(t.name,t)}}async function getAgentTools(){return 0===FE.size&&await loadAgentTools(),Array.from(FE.values())}async function getAgentTool(e){return 0===FE.size&&await loadAgentTools(),FE.get(e)}var BE=__esm({"src/tools/agents/manager.ts"(){Nt(),Fl(),zE(),_l(),FE=new Map,jE=null,__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool")}}),UE=__esm({"src/tools/agents/index.ts"(){Nt(),BE()}});function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,s=e.join(r,".commandcode","taste"),o=e.normalize(e.resolve(r,n)),i=e.normalize(s);return o.startsWith(i)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),s=e.normalize(e.join(h.homedir(),".commandcode","taste"));let o=null;if(n.startsWith(r)?o=r:n.startsWith(s)&&(o=s),!o)return{isTaste:!1};if(!n.endsWith("taste.md"))return{isTaste:!1};const i=e.relative(o,n).split(e.sep);return 1===i.length?{isTaste:!0}:2===i.length?{isTaste:!0,category:i[0]}:{isTaste:!1}}function getTasteAccessError(){return"Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system."}var WE,QE,GE,HE,VE,KE,YE=__esm({"src/utils/taste-path-validator.ts"(){Nt(),Ot(),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(getTasteAccessError,"getTasteAccessError")}});function isAgentTool(e){return!HE.has(e)&&!isMcpTool(e)}async function executeTool(e,t,n){if(isMcpTool(e)){const n=trackToolStart({toolName:e});try{const r=await executeMcpTool({prefixedName:e,args:t});return r.success?(n.end({status:"success"}),r.result??"Tool executed successfully"):(n.end({status:"error",error:new Error(r.error)}),`Error: ${r.error}`)}catch(e){const t=sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"mcp_tool_error"});return n.end({status:"error",error:t}),`Error: ${e instanceof Error?e.message:String(e)}`}}const r=n?.permissionMode||"standard",s=isToolAllowedInMode({toolName:e,mode:r,toolParams:t});if(!s.allowed)throw new Error(s.reason||`Tool "${e}" not allowed in ${r} mode`);let o=GE.get(e);if(o||(o=await getAgentTool(e)),!o){const t=await getAgentTools(),n=[...Array.from(GE.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 i=trackToolStart({toolName:e});try{let r;return r=(!GE.has(e)||!0===o.acceptsCallbacks)&&n?await o.execute(t,n):await o.execute(t),i.end({status:"success"}),r}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message){const t=sanitizeErrorForTelemetry({error:e,label:"tool_interrupted"});throw i.end({status:"error",error:t}),e}if(e instanceof Error){const t=sanitizeErrorForTelemetry({error:e,label:"tool_error"});return i.end({status:"error",error:t}),`Error: ${e.message}`}return i.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(e){const t=e?.mode||"standard",n=null!==sl()?[...WE]:WE.filter(e=>e.name!==Is.DIAGNOSTICS),r=await getAgentTools(),s=getToolsForMode({allTools:n,mode:t}).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),o=r.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}));let i=[];return"plan"!==t&&getMcpConnectionManager().isInitialized&&(i=getAllMcpToolSchemas()),[...s,...o,...i,...QE]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}var JE=__esm({"src/tools/index.ts"(){Nt(),xi(),Gi(),Xi(),aa(),pa(),ba(),Pa(),Ra(),Ma(),qa(),Wa(),pl(),gl(),hl(),fl(),yl(),kl(),Sl(),Gs(),po(),mo(),UE(),YE(),Vr(),RE(),WE=[vi,Bi,Ki,ta,ua,fa,va,Ia,$a,Oa,ja,Ha,Va,Ka,El],QE=[Ya,Ja],GE=new Map(WE.map(e=>[e.name,e])),HE=new Set([...WE.map(e=>e.name),...QE.map(e=>e.name)]),__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase"),VE={},WE.forEach(e=>{VE[e.name]=toPascalCase(e.name)}),QE.forEach(e=>{VE[e.name]=toPascalCase(e.name)}),KE={},Object.entries(VE).forEach(([e,t])=>{KE[t]=e}),initializeAgentManager({clientTools:WE,serverTools:QE,toolsMap:GE,displayNameToToolName:KE})}});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 s=new TextDecoder,o=new TransformStream({transform(e,t){const o=s.decode(e,{stream:!0});r+=o;const i=r.split("\n");r=i.pop()??"";for(const e of i){const r=e.trim();if(!r){t.enqueue((new TextEncoder).encode(e+"\n"));continue}const s=parseErrorLine(r);if(s)return n=s,void t.error(new Error(`Error: Stream error: ${s.type} - ${s.message}`));t.enqueue((new TextEncoder).encode(e+"\n"))}},flush(e){const t=r.trim();if(t){const s=parseErrorLine(t);if(s)return n=s,void e.error(new Error(`Error: Stream error: ${s.type} - ${s.message}`));e.enqueue((new TextEncoder).encode(r))}}});return{stream:t.pipeThrough(o),getStreamError:__name(()=>n,"getStreamError")}}var XE,ZE,eC=__esm({"src/utils/stream-error-interceptor.ts"(){Nt(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors")}}),tC=__esm({"src/utils/learning-events.ts"(){Nt(),XE=class extends Re{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:s,label:o,sessionCount:i,promptCount:a,learningCount:l,categories:u,storage:d}=e,m={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:s,label:o,sessionCount:i,promptCount:a,learningCount:l,categories:u,storage:d};this.events.unshift(m),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",m)}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")}},ZE=new XE}});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}),s=extractLearnings({text:n}),o=new Map(r.map(e=>[e.text,e.confidence])),i=[],a=[],l=[];return s.forEach(e=>{const t=o.get(e.text);void 0===t?i.push(e):e.confidence>t?a.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&l.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:i,upgraded:a,downgraded:l}}var nC,rC,sC,oC,iC,aC,lC,cC,uC,dC,mC,pC=__esm({"src/utils/learning-parser.ts"(){Nt(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings")}}),gC=__esm({"src/agent/learning-agent.ts"(){Nt(),Ot(),dn(),CE(),JE(),ME(),$n(),tC(),pC(),OE(),nr(),ar(),Vr(),nC=new LE("LearningAgent"),rC=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:Br.LEARNING_AGENT,heading:"Learning pass failed"}}),ZE.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)];ZE.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const s=await this.getTasteStructure(),o=t.length-this.lastProcessedMessageIndex-1,i=Math.max(20,o),a=Math.max(0,t.length-i),l=t.slice(a);let u=0,d=!1;dlog(`[LearningAgent] analyzing ${o} new messages for patterns`);const m=[{role:"user",content:`Current taste structure:\n${s}\n\nRecent conversation:\n${JSON.stringify(l,null,2)}`}];for(;u<this.maxTurns;){const e=await this.callLearningAPI({conversation:m}),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")),m.push({role:"assistant",content:e.content}),m.push({role:"user",content:n}),u++}u>=this.maxTurns&&nC.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||ZE.addEvent({type:"no_learnings",message:"no changes to taste"}),ZE.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 s="",o="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(o=String(e.filePath||e.file_path||""),o)try{s=await w.promises.readFile(o,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const i=await executeTool(e.name,t,{allowTasteWrite:!0});let a="";if(("write_file"===e.name||"edit_file"===e.name)&&o)try{a=await w.promises.readFile(o,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=o.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:s,newText:a});(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=>{ZE.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{ZE.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{ZE.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:i})}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,s={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(!s||!r[s])return;const o=String(r[s]);if(e.isAbsolute(o))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: ${o}`);const i=e.normalize(o);if(i.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${o}`);const a=e.join(this.tasteDir,i);if(!e.normalize(a).startsWith(this.tasteDir))throw new Error(`Security: ${n} can only access files within .commandcode/taste/. Attempted: ${o}`)}adjustPathsForTaste(t){const{toolName:n,input:r}=t,s={...r},o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(o&&s[o]){const t=String(s[o]);let r;const i="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)&&t.startsWith(this.tasteDir))if(i){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(i&&!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`)}s[o]=r}return s}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(!w.existsSync(this.tasteDir)){w.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");w.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!w.existsSync(t))return!1;const n=w.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let s=n;for(const t of r){const n=t.name.toLowerCase().replace(/\s+/g,"-"),r=e.join(this.tasteDir,n),o=e.join(r,"taste.md");w.mkdirSync(r,{recursive:!0}),ZE.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const i=`# ${t.name}\n${t.learnings.join("\n")}\n`;w.writeFileSync(o,i,"utf-8");const a=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;s=s.replace(t.fullSection,a)}return w.writeFileSync(t,s,"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 s=t.filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:"));s.length>0&&n.push({name:r,learningCount:s.length,learnings:s,fullSection:`# ${e}`})}return n}async getTasteStructure(){return w.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(t){const{dir:n,prefix:r}=t,s=w.readdirSync(n,{withFileTypes:!0});let o="";for(let t=0;t<s.length;t++){const i=s[t],a=t===s.length-1,l=a?"└── ":"├── ";if(i.isDirectory()){o+=`${r}${l}${i.name}/\n`;const t=r+(a?" ":"│ ");o+=await this.buildTree({dir:e.join(n,i.name),prefix:t})}else if("taste.md"===i.name){const t=(w.readFileSync(e.join(n,i.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${r}${l}${i.name} (${t} learnings)\n`}else o+=`${r}${l}${i.name}\n`}return o}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let s;n===Ct.ANTHROPIC&&(s=await on.getValidAccessToken(),validateOAuthToken({token:s,provider:n}));const o={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(o[wt.OAUTH_TOKEN]=`Bearer ${s}`);const i=await this.getTasteTools(),a=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${a})`);const l={conversation:t,tools:i,model:a,threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:St.ALPHA.TASTE.LEARN,body:l,headers:o,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),u++,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:Br.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(u>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:Br.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":u}}),d;const n=1e3*Math.pow(2,u);dlog(`[LearningAgent] retrying API call (${u}/${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 w.existsSync(r)}}}}),hC=__esm({"src/agent/compact-agent.ts"(){Nt(),Ot(),dn(),CE(),en(),nr(),ar(),$n(),sC="claude-haiku-4-5-20251001",oC=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 s;n===Ct.ANTHROPIC&&(s=await on.getValidAccessToken(),validateOAuthToken({token:s,provider:n}));const o={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(o[wt.OAUTH_TOKEN]=`Bearer ${s}`);const i=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"),a={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${i}`}],model:`anthropic:${sC}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let l=0,u=null;for(;l<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${St.ALPHA.GENERATE} with model: ${sC}`);const e=await this.request.post({endpoint:St.ALPHA.GENERATE,body:a,headers:o,stream:!0});if(!e)throw new Error("No response stream received");const t=je.fromReadableStream(e);let n="",r=null;t.on("text",e=>{n+=e}),t.on("error",e=>{r=e});const s=await t.finalMessage();if(r)throw r;return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:s.usage.input_tokens,output:s.usage.output_tokens}}}catch(e){u=e instanceof Error?e:new Error(String(e)),l++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${u.message}`),u;if(l>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),u;const n=1e3*Math.pow(2,l);dlog(`[CompactAgent] retrying API call (${l}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}throw u||new Error("Compact API call failed")}}}});function migrateHeader(e){const{content:t}=e;if(t.includes(iC))return t.includes(lC)?t:t.includes(aC)?t.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"").replace(iC,lC):t.replace(iC,lC);let n=t;return n.includes(aC)&&(n=n.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"")),dC.test(n)?n=n.replace(dC,`$1${lC}`):mC.test(n)&&(n=n.replace(mC,`$1${lC}`)),n}var fC=__esm({"src/commands/taste/utils/header-migration.ts"(){Nt(),lC=`${iC="# Taste (Continuously Learned by [CommandCode][cmd])"}\n\n${aC="[cmd]: https://commandcode.ai/"}`,cC="# Taste (Continuously Learned by CommandCode)",uC="# Taste (Continuously Learned by CommandCode.ai)",dC=/^(\s*)# Taste \(Continuously Learned by CommandCode\)(?!\.ai)/,mC=/^(\s*)# Taste \(Continuously Learned by CommandCode\.ai\)/,__name(migrateHeader,"migrateHeader")}});async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!E(n))return null;const r=await $.readFile(n,"utf-8"),s=r.trim();return s&&s!==lC&&s!==iC&&s!==uC&&s!==cC?r:null}catch(e){return null}}var yC,wC,SC=__esm({"src/utils/taste/get-taste-content.ts"(){Nt(),Ot(),fC(),__name(getTasteContent,"getTasteContent")}});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={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};if(e===Ct.ANTHROPIC){const e=await on.getValidAccessToken();e&&(n[wt.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 s="",o="";for(const e of t)if(s||"user"!==e.message.role||(s=extractMessageText(e.message.content).slice(0,wC)),o||"assistant"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,wC)),s&&o)break;if(!s||!o)return;const i=`${yC}\n\nSession description:\n<description>User: ${s}\n\n---\n\nAssistant: ${o}</description>\n\nGenerate the session title now.`,a={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:i}],model:vt,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},l=await buildAuthHeaders(),u=await r.post({endpoint:St.ALPHA.GENERATE,body:a,headers:l,stream:!0}),d=je.fromReadableStream(u);let m="";d.on("text",e=>{m+=e}),await d.finalMessage(),m=m.trim(),m&&(await n.saveSessionTitle(m),dlog("Session",`Title generated: ${m}`))}var bC,EC,CC,vC=__esm({"src/chat/title-generator.ts"(){Nt(),dn(),CE(),en(),nr(),ar(),$n(),Ot(),yC="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",wC=1e3,__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle")}}),TC={};__export(TC,{ContextEngine:()=>CC});var kC,_C=__esm({"src/chat/context-engine.ts"(){Nt(),Zo(),dn(),gi(),hi(),Ci(),Jo(),Gs(),JE(),ME(),eC(),OE(),YE(),$E(),CE(),Vr(),ji(),ts(),bE(),Jl(),Ot(),en(),nr(),ar(),qE(),gC(),hC(),SC(),$n(),vC(),vE(),bC=new LE("ContextEngine"),EC=200,CC=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 Vb({baseUrl:n}),this.callbacks=e,this.sessionManager=new Yb(t),this.learningAgent=new rC({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new oC({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new Vb({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,bC.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),bC.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=Ao("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>bC.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n,r){let s=e,o=[];try{const t=await processFileReferences(e);if(s=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&&(s=`${n}\n\n${s}`);const i=Ao(r??e);t&&t.length>0&&(i.metadata={...i.metadata,images:t}),o&&o.length>0&&(i.metadata={...i.metadata,fileReferences:o}),this.callbacks.onFeedUpdate(i);const a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),s.trim()&&a.push({type:"text",text:s});const l={role:"user",content:a},u=crypto.randomUUID(),d=this.createMessageWithMeta(l,{messageId:u});this.addMessageAndSync(d),this.checkpointManager.createSnapshot({messageId:u}).catch(e=>bC.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,i).catch(e=>bC.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const m=await this.processMessages();return this.triggerTitleGeneration(),m}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){bC.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(),s=await this.callAPIWithRetry({body:n,headers:r});this.checkIfInterrupted(),this.updateContextUsage(s),await this.checkAndCompactIfNeeded();const o=s.content.filter(e=>"tool_use"===e.type),i=s.content.filter(e=>"server_tool_use"===e.type);if(e=i.length>0?this.processServerToolBlocks(s):s.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===o.length){const t=s.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===i.length){const t=Io(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>bC.error(`Failed to save messages: ${e}`))}if(0!==i.length&&this.sessionManager.saveMessages(this.messages).catch(e=>bC.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=Ao(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>bC.error(`Failed to save messages: ${e}`)),this.triggerLearningAgent();continue}}break}const a=s.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(a.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:a})),e.trim()){const t=Io(e);this.callbacks.onFeedUpdate(t)}const l=await this.executeToolBlocks({toolBlocks:o}),{toolResults:u,executedToolIds:d,permissionDenied:m}=l;if(m){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 p=[...u];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){p.push({type:"text",text:t});const e=Ao(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:p})),this.sessionManager.saveMessages(this.messages).catch(e=>bC.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&bC.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){bC.error(`Failed to load checkpoints for session ${e}: ${t}`)}const s=this.sessionManager.reconstructFeedFromMessages(t);return bC.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:s,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.sanitizeMessagesForAPI(this.messages.map(e=>e.message))}sanitizeMessagesForAPI(e){const t=[];for(const n of e){if("user"===n.role&&Array.isArray(n.content)){const e=t.length>0?t[t.length-1]:null,r=new Set;if("assistant"===e?.role&&Array.isArray(e.content))for(const t of e.content)"tool_use"===t.type&&r.add(t.id);const s=n.content.filter(e=>"tool_result"!==e.type||r.has(e.tool_use_id));s.length>0&&t.push({...n,content:s});continue}const e=t.length>0?t[t.length-1]:null;if(e&&e.role===n.role){const t=Array.isArray(e.content)?e.content:[{type:"text",text:e.content}],r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];e.content=[...t,...r];continue}t.push({...n})}return t}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};bC.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 s=0;const o=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],i=n.message.role;if(e&&t>=r&&-1!==r)o.push(n);else{if("user"===i){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){s+=estimateTokens(n.message);continue}o.push(n)}else o.push(n)}else if("assistant"===i){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)s+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?o.push({...n,message:{...n.message,content:r}}):s+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&o.push(n)}"user"!==i&&"assistant"!==i&&(s+=estimateTokens(n.message))}}this.messages=o,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,n-s);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:xE}),{messagesRemoved:t-o.length,tokensSaved:s}}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=$l.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:St.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=this.callbacks.getPermissionMode?.()||"standard",t=await getToolSchemas({mode:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let s;n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n),n===Ct.ANTHROPIC&&(s=await on.getValidAccessToken(),validateOAuthToken({token:s,provider:n}));const o={tools:t,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},i={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:o,threadId:this.sessionManager.getSessionId(),permissionMode:e};bC.debug(`calling API (${o.model}, ${this.messages.length} msgs, ${t.length} tools)`);const a=await isTasteLearningEnabled(),l={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.TASTE_LEARNING]:a.toString(),[wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(l[wt.OAUTH_TOKEN]=`Bearer ${s}`),{body:i,headers:l}}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:St.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const s=je.fromReadableStream(n);s.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let o=null;s.on("error",e=>{o="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const i=await s.finalMessage();if(o)throw o;return this.callbacks.onRetryUpdate?.(null),i}catch(e){const s=r?.(),o=s?Object.assign(new Error(s.message),{type:s.type,error:{type:s.type,message:s.message}}):e;if(t=o,this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(o))throw trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"non_retryable_api_error"}),context:{component:Br.CONTEXT_ENGINE,heading:"Non-retryable API error",code:o?.status||o?.statusCode}}),this.formatAPIError(o);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:Br.CONTEXT_ENGINE,code:o?.status||o?.statusCode,"retry.attempts":10}}),this.formatAPIError(o);trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"generate_retry_attempt"}),context:{heading:"Generate API retry",component:Br.CONTEXT_ENGINE,code:o?.status||o?.statusCode,"retry.attempt":n+1,"retry.max":10}});const i=Math.min(n,10),a=100*Math.pow(2,i),l=Math.max(a,1e3),u=Math.min(l,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:u,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,s="Insufficient credits"===t||n.includes("insufficient credits"),o=e instanceof ii||401===e?.status||e instanceof ai||403===e?.status,i=e?.type||e?.error?.type,a="rate_limit_error"===i||429===e?.status||n.includes("rate limit"),l="overloaded_error"===i||529===e?.status||n.includes("overloaded");return r||s||o||a||l}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,s=t.message;dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",s);const o=s?.toLowerCase().includes("insufficient credits");if(o)return new Error("Insufficient credits");const i=s?.toLowerCase().includes("oauth authentication required");if(i)return e;if(e instanceof ai||403===e?.status)return e;if(e instanceof ii||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 a=getSupportId();let l="";if(s)if(s.includes("Invalid 'Authorization' header"))l='Error: Authentication failed. Run "cmd login" to sign in again.';else{let e=s;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>EC&&(t=t.substring(0,EC)+"..."),l=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const o=s.toLowerCase(),i="overloaded_error"===r||o.includes("overloaded"),u="rate_limit_error"===r||o.includes("rate limit");l+=i?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":u?'\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"!==a&&(l+=`\nRequest ID: ${a}`)}else if(e.toString){const t=e.toString();l=t.length>EC?t.substring(0,EC)+"...":t}else l="Error: Unknown error occurred";return new Error(l)}async executeToolBlocks(e){const t=new Set;let n=!1;const r=[],s=[];for(const o of e.toolBlocks){this.checkIfInterrupted();const e=crypto.randomUUID(),i=Ms.includes(o.name),a=Os.includes(o.name)?this.getToolDescription(o):Promise.resolve(null);let l=null;try{i&&this.callbacks.onPermissionRequest&&(l=await a);const t=await this.checkToolPermission(o,l);if(t.needsPermission&&!t.allowed){this.handlePermissionDenied(o,e),n=!0;break}}catch(n){const r=n instanceof Error?n.message:"Permission check failed";this.showToolError(o,r,e,l),s.push({toolBlock:o,toolResult:{type:"tool_result",tool_use_id:o.id,content:`Error: ${r}`,is_error:!0}}),t.add(o.id);continue}null===l&&(l=await a),r.push({toolBlock:o,entryId:e,description:l})}const o=[];for(const{toolBlock:e,toolResult:n}of s)o.push(n),t.add(e.id);if(r.length>0){const e=await Promise.allSettled(r.map(async({toolBlock:e,entryId:t,description:n})=>{this.checkIfInterrupted();const r="edit_file"===e.name?await resolveEditStartLine({filePath:e.input.filePath,oldContent:e.input.oldValue}).catch(()=>{}):void 0,s=await this.executeSingleTool(e);return isAgentTool(e.name)||this.showToolSuccess(e,s,t,n,r),{toolBlock:e,toolResult:{type:"tool_result",tool_use_id:e.id,content:s}}}));for(let n=0;n<e.length;n++){const s=e[n],{toolBlock:i,entryId:a,description:l}=r[n];if("fulfilled"===s.status)o.push(s.value.toolResult),t.add(i.id);else{const e=s.reason instanceof Error?s.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(i.name)?t.add(i.id):(o.push({type:"tool_result",tool_use_id:i.id,content:`Error: ${e}`,is_error:!0}),t.add(i.id),this.showToolError(i,e,a,l))}}}return{toolResults:o,executedToolIds:t,permissionDenied:n}}async getToolDescription(e){try{return await Promise.race([generateToolDescription(e.name,e.input),new Promise(e=>setTimeout(()=>e(null),6e3))])}catch(t){return bC.debug(`Failed to generate description for ${e.name}: ${t instanceof Error?t.message:"Unknown error"}`),this.callbacks.onToolDescriptionError&&this.callbacks.onToolDescriptionError(e.name,t),null}}async checkToolPermission(e,t){return Ms.includes(e.name)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.name,e.input,t)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=this.callbacks.getPermissionMode?.()||"standard",n=await executeTool(e.name,e.input,{onPermissionRequest:this.callbacks.onPermissionRequest,onQuestionRequest:this.callbacks.onQuestionRequest,abortSignal:this.abortController?.signal,onFeedUpdate:this.callbacks.onFeedUpdate,permissionMode:t});this.checkIfInterrupted();const r=checkToolOutputTokensLimit(n,e.name),s=estimateTokens(r);return this.currentInteractionTokens+=s,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),r}handlePermissionDenied(e,t){const n=Ho(e.name,e.input),r={..."edit_file"===e.name?e.input:{},permissionDenied:!0},s={...No(e.name,n,r),id:t},o=Fo(s,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}showToolSuccess(e,t,n,r,s){let o="edit_file"===e.name?{...e.input,...void 0!==s?{startLine:s}:{}}: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&&(o={...o||{},isTasteFile:!0,tasteCategory:e.category})}}const i={...e.input,...o?.isTasteFile?{isTasteFile:o.isTasteFile}:{},...o?.tasteCategory?{tasteCategory:o.tasteCategory}:{}},a=Ho(e.name,i),l={...No(e.name,a,o),id:n,...r?{description:r}:{}},u=Fo(l,t);this.callbacks.onFeedUpdate(u)}showToolError(e,t,n,r){const s=Ho(e.name,e.input),o="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,i={...No(e.name,s,o),id:n,...r?{description:r}:{}},a=Fo(i,jo(t));this.callbacks.onFeedUpdate(a)}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=Io(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:s}=Ls({serverToolBlock:e,contentBlocks:n}),o=Ho(e.name,e.input),i=No(e.name,o),a=Fo(i,s?jo(r):r);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=Io(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:xE})}async checkAndCompactIfNeeded(){const e=Math.floor(xE*At.TIER_1_THRESHOLD),t=Math.floor(xE*At.TIER_2_THRESHOLD),n=Math.floor(xE*At.TIER_3_THRESHOLD);try{if(this.contextTokensUsed>n){bC.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 this.emitAutoCompactInfo(t)}if(this.contextTokensUsed>t){bC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${At.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT);return bC.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void this.emitAutoCompactInfo(e.tokensSaved)}if(this.contextTokensUsed>e){const t=this.countToolCalls(),n=At.TIER_1_KEEP_COUNT;if(t>n){bC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);bC.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){bC.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){e>0&&this.callbacks.onFeedUpdate(xo(`Auto-compacted conversation, saved ~${e.toLocaleString()} tokens.`,{isAutoCompact:!0}))}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 s=new Set(r.slice(-e).map(e=>e.id)),o=new Set(r.filter(e=>!s.has(e.id)).map(e=>e.id)),i=[];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||!o.has(e.tool_use_id)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_use"!==e.type||!o.has(e.id)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}i.push(e)}this.messages=i,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,t-n);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:xE}),{toolsRemoved:o.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return bC.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT);bC.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});bC.debug(`Summarization complete: ${r.summary.length} chars, used ${r.tokensUsed.input}/${r.tokensUsed.output} tokens`);const s=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}),o=this.contextTokensUsed,i=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[s,...t],await this.sessionManager.saveMessages(this.messages);const a=estimateTokens(s.message),l=Math.max(0,o-i+a);this.contextTokensUsed=l,this.callbacks.onContextUsageUpdate?.({current:l,limit:xE}),bC.debug(`Tier 3 summarization complete: reduced from ${o} to ~${l} tokens`)}catch(e){bC.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=At.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r],o=estimateTokens(s.message);if(t+o>e){n=r+1;break}t+=o;const i=s.message.content;Array.isArray(i)&&i.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 s=0;if(-1!==r&&("conversation"===n||"both"===n))for(let e=r;e<this.messages.length;e++)s+=estimateTokens(this.messages[e].message);const o=await this.checkpointManager.restore({messageId:t,mode:n});return!o.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-s),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:xE})),o}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}}}}),PC=__esm({"src/utils/clear-console.ts"(){Nt(),kC=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole")}});async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new Vb({baseUrl:e});return await t.get({endpoint:St.ALPHA.WHOAMI})}var AC=__esm({"src/utils/get-entity.ts"(){Nt(),ts(),bE(),Ot(),__name(getAuthenticatedEntity,"getAuthenticatedEntity")}}),xC={};async function getBillingLink({billingLink:e,setBillingLink:t}){if(e)return e;try{const e=await getAuthKey();if(!e)return;const n=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return t(e),e}if(n.org){const e=`https://commandcode.ai/${n.org.login}/settings/billing`;return t(e),e}}catch{return"https://commandcode.ai/settings/billing"}}async function handleSubmit({role:e,input:t,images:n,ideContext:r,displayMessage:s,feed:o,setFeed:i,isCmdCodeBusy:a,setIsCmdCodeBusy:l,setQueuedMessages:u,setStatus:d,setInteractionTokens:m,updateStatus:p,setUpdateStatus:g,billingLink:h,setBillingLink:f,contextEngineRef:y,isSubmittingRef:w,setInput:S,setStaticKey:b,executeBash:E}){if(!t.length)return;if(p&&g(null),m(0),"bash"===e){if(w.current)return;w.current=!0;const e=Ro(t);return i([...o,e]),S(""),await E(t,e=>{i(e)},()=>{kC(),b(e=>e+1)}),void(w.current=!1)}if(a)return u(e=>[...e,s??t]),void S("");if(w.current)return;w.current=!0,l(!0),d(Wo()),S("");let C=!1;try{y.current&&await y.current.sendMessage(t,n,r,s)}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)return void(C=!0);if(C=!0,"Insufficient credits"===e.message){d("Insufficient credits");const e=`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${await getBillingLink({billingLink:h,setBillingLink:f})}`;return void i(t=>[...t,Lo(e)])}if(e.message.startsWith("Error:"))return d("Error"),void i(t=>[...t,Lo(e.message)]);d("Error");const t=e.message||"An unexpected error occurred";i(e=>[...e,Lo(t)])}finally{l(!1),C||d("Ready..."),w.current=!1}}__export(xC,{getBillingLink:()=>getBillingLink,handleSubmit:()=>handleSubmit});var IC=__esm({"src/tui/actions/submit.ts"(){Nt(),Jo(),Qs(),AC(),Ot(),PC(),__name(getBillingLink,"getBillingLink"),__name(handleSubmit,"handleSubmit")}});Nt(),Nt();var NC=process.argv.includes("-d")||process.argv.includes("--debug");NC&&(process.env.DEBUG="true"),NC||(process.removeAllListeners("warning"),process.on("warning",()=>{})),Nt(),Nt(),Vr();var{red:RC,yellow:$C,dim:LC}=Be,MC=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:s=!0,skipTelemetry:o=!1}=e;if(n){if(o||trackError({error:sanitizeErrorForTelemetry({error:n,label:"cli_error"}),context:{component:Br.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Ue.error} ${RC(t)}`),console.log(`${Ue.error} ${RC("ERROR →")} ${n.name}`),console.log(`${Ue.info} ${RC("REASON →")} ${n.message}`),console.log(`${Ue.info} ${RC("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Ue.info} ${LC(`Request ID: ${e}`)}`),console.log(`${LC(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Ue.warning} ${$C(t)}\n`);if(!s)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:Br.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),MC({heading:ze`CRITICAL: Unhandled Promise Rejection!
252
252
  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:Br.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),MC({heading:ze`CRITICAL: Uncaught Exception!
253
- 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)})})}Vr(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Nt(),Nt(),Ot(),Qs(),Nt(),Ot();var OC="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",DC="\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 qC=getMaxLineWidth(OC),FC=getMaxLineWidth(DC),jC=qC+1,zC=FC+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var BC=__name(e=>{const t=e??getTerminalWidth();return t>=jC?OC:t>=zC?DC:UC},"getResponsiveCommandLogo"),UC="⌘ CMD\n";rr();var WC=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),QC=__name(e=>{const t=__name(e=>({r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}),"hexToRgb"),n=t(Zn.START),r=t(Zn.END);return e.split("\n").map(e=>0===e.length?e:e.split("").map((t,s)=>{const o=e.length>1?s/(e.length-1):0,i=Math.round(n.r+(r.r-n.r)*o),a=Math.round(n.g+(r.g-n.g)*o),l=Math.round(n.b+(r.b-n.b)*o);return Be.rgb(i,a,l)(t)}).join("")).join("\n")},"applyViceGradient"),GC=__name(e=>{console.log(QC(BC())),console.log(""),console.log(`${be.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),HC=__name(async e=>{const t=We.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"),VC=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.log(""),console.log(`${be.cross} Authentication failed. Please try again with: cmd login`),!1)}catch{return!1}},"attemptLogin"),KC=__name(()=>{console.log(""),console.log(`${be.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),YC=__name(()=>{console.log(""),console.log(`${be.info} Authentication cancelled. You can authenticate later with: cmd login`)},"showCancelledMessage");async function checkAuthAndPromptLogin(){try{if(await getAuthKey())return!0;GC(Mt());const{answer:e,cancelled:t}=await HC(`Would you like to sign in now? ${Be.dim("(y/n)")}: `);return t?(YC(),!1):WC(e)?(console.log(""),VC()):(KC(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}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}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin"),Nt(),Nt(),Nt(),Nt(),jr(),Nt(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var JC=["no job control","cannot set terminal process group"],XC=null;function getShellInfo(){return XC||(XC=detectUserShell()),XC}__name(getShellInfo,"getShellInfo");var ZC=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:s=process.env}=t;return new Promise(t=>{let o=!1;const i=__name(e=>{o||(o=!0,t(e))},"doResolve"),a=getShellInfo(),l="bash"===a.type||"zsh"===a.type,u=l?a.path:"/bin/bash",d=N(u,l?["-i","-c",e]:["-c",e],{cwd:r,env:{...s},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let m="",p="",g=null;n>0&&(g=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),i({stdout:m,stderr:p+(p?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(m.length+n.length>Mr){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void i({stdout:m,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}m+=n}catch(e){p+=`\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(p.length+t.length>Or)return void(p+="\n[Error output truncated: too large]");p+=t}catch(e){p+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{g&&clearTimeout(g);const n=l?p.split("\n").filter(e=>!JC.some(t=>e.includes(t))).join("\n"):p;i({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{g&&clearTimeout(g),i({stdout:m,stderr:p+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),ev=__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");Jo();var tv=__name(()=>{const[e,t]=W({isExecuting:!1,currentCommand:null});return{executeBash:V(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await ZC(e,{timeout:3e4,cwd:process.cwd()}),s=ev(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]=Fo(r,s);break}}return n}),r()}catch(t){const s=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]=Fo(r,`Error: ${s}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function useUiOverlays(){const[e,t]=W(!1),[n,r]=W(!1),[s,o]=W(!1),[i,a]=W(!1),[l,u]=W(!1),[d,m]=W(!1),[p,g]=W(!1),[h,f]=W(!1),[y,w]=W(!1),[S,b]=W(!1),[E,C]=W(!1),[v,T]=W(!1),[k,_]=W(!1),[P,A]=W(0),[x,I]=W("off");return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:s,setShowTasteConfig:o,showSkillsConfig:i,setShowSkillsConfig:a,showProviderSelector:l,setShowProviderSelector:u,showModelSelector:d,setShowModelSelector:m,showMemorySelector:p,setShowMemorySelector:g,showMcpManager:h,setShowMcpManager:f,showLearningFeed:y,setShowLearningFeed:w,showSessionSelector:S,setShowSessionSelector:b,showAddDirModal:E,setShowAddDirModal:C,showRewindSelector:v,setShowRewindSelector:T,showLoginOverlay:k,setShowLoginOverlay:_,staticKey:P,setStaticKey:A,transcriptMode:x,setTranscriptMode:I,expandedToolOutput:"off"!==x}}function useFeed(){const[e,t]=W([]),[n,r]=W([]),[s,o]=W([]),[i,a]=W(!1),l=Q([]);return G(()=>{l.current=s},[s]),{feed:e,setFeed:t,liveAgents:n,setLiveAgents:r,queuedMessages:s,setQueuedMessages:o,isCmdCodeBusy:i,setIsCmdCodeBusy:a,queuedMessagesRef:l}}function useSession(){const[e,t]=W(crypto.randomUUID()),[n,r]=W(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:Q(null)}}function useStatus(e){const[t,n]=W("Ready..."),r=Q(!1),[s,o]=W(""),i=Q(null),[a,l]=W(null),u=Q(a),[d,m]=W(null),[p,g]=W(!1),[h,f]=W(""),[y,w]=W(null),[S,b]=W(0),[E,C]=W(null),[v,T]=W(!1),[k,_]=W(e??null);G(()=>{u.current=a},[a]),G(()=>{if(k){const e=setTimeout(()=>{_(null)},3e4);return()=>clearTimeout(e)}},[k]);const P=__name(e=>{i.current&&clearTimeout(i.current),o(e),i.current=setTimeout(()=>{o(""),i.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:s,setHintMessage:o,hintTimerRef:i,shareInfo:a,setShareInfo:l,shareInfoRef:u,billingLink:d,setBillingLink:m,showShareNotification:p,setShowShareNotification:g,unshareNotificationMessage:h,setUnshareNotificationMessage:f,retryAttempt:y,setRetryAttempt:w,interactionTokens:S,setInteractionTokens:b,contextUsage:E,setContextUsage:C,tasteLearningEnabled:v,setTasteLearningEnabled:T,updateStatus:k,setUpdateStatus:_,showHintMessage:P}}function useAuth(){const[e,t]=W(null),[n,r]=W(getConfiguredModel()),[s,o]=W(!1),[i,a]=W(null),[l,u]=W(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,isOAuthMode:s,setIsOAuthMode:o,authComponentInfo:i,setAuthComponentInfo:a,showProviderNotification:l,setShowProviderNotification:u,providerNotificationTimer:Q(null),modelNotificationTimer:Q(null)}}Nt(),__name(useUiOverlays,"useUiOverlays"),Nt(),__name(useFeed,"useFeed"),Nt(),__name(useSession,"useSession"),Nt(),__name(useStatus,"useStatus"),Nt(),nr(),__name(useAuth,"useAuth"),Nt(),Nt(),Nt(),Ot();var nv=class extends Re{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 L.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 L.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await L.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 L.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"),s=`Bash(${e.split(" ")[0]}:*)`;try{let e;await L.mkdir(n,{recursive:!0});try{const t=await L.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(s)||e.permissions.allow.push(s),await L.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},rv=__name((e={})=>{const[t,n]=W(null),[r,s]=W(null),[o,i]=W(!1);return G(()=>{const t=e.projectRoot||process.cwd(),r=new nv(t);return r.on("permission-request",(t,n)=>{s(t),i(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{s(t),i(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:V(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:V(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:V(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),s(null),i(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),s(null),i(!1)}},[t]),clearSessionPermissions:V(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:V(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:V((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:V(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:o,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r="auto-accept"===("boolean"==typeof t?t?"auto-accept":"standard":t),s=["create","edit","delete","execute","shellCommands"];for(const e of s)n.setAutoApprove(e,r)}function usePermissionMode({initialPermissionMode:e,dangerouslySkipPermissions:t=!1,setPendingPermission:n,setStatus:r,contextEngineRef:s}){const[o,i]=W(()=>e||(t?"auto-accept":"standard")),a=Q(o);G(()=>{a.current=o},[o]);const{requestShellPermission:l,service:u,respondToPrompt:d,clearSessionPermissions:m,setEnabled:p}=rv({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{n({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),s.current&&r("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{n({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),s.current&&r("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?r("Permission granted"):r("Permission denied")},"onPermissionResponse")});return G(()=>{u&&applyAutoAcceptMode({enabled:o,service:u})},[o,u]),{permissionMode:o,setPermissionMode:i,permissionModeRef:a,permissionsService:u,respondToPrompt:d,clearSessionPermissions:m}}function usePendingOps(){const[e,t]=W(null),[n,r]=W(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function useOnboarding(){const[e,t]=W(!1),[n,r]=W(!1),[s,o]=W(!0),[i,a]=W(!1),[l,u]=W(!1),[d,m]=W(null),[p,g]=W(!1);return{showTrustPrompt:e,setShowTrustPrompt:t,projectTrusted:n,setProjectTrusted:r,checkingProject:s,setCheckingProject:o,showTasteOnboarding:i,setShowTasteOnboarding:a,onboardingComplete:l,setOnboardingComplete:u,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:m,autoLearnTaste:p,setAutoLearnTaste:g,tasteOnboardingCheckedRef:Q(!1)}}function useExit(){const[e,t]=W(!1),[n,r]=W(null),s=Q(null),o=Q(0),i=Q(null),a=V(()=>{s.current=null,r(null),i.current&&(clearTimeout(i.current),i.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:s,lastExitKeyTimeRef:o,exitConfirmationTimeoutRef:i,resetPendingExitKey:a}}function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:t,description:`Terminate process on ${t}`}}function buildShellPermissionRequest(e,t){const n=e.args,r=Array.isArray(n)?n.join(" "):"string"==typeof n?n:"";return{command:"string"==typeof e.command?e.command:"",args:"string"==typeof n?n:Array.isArray(n)?n.join(" "):void 0,workingDirectory:"string"==typeof e.directory?e.directory:void 0,description:t??`Execute shell command: ${String(e.command??"")} ${r}`}}function getFileAction(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function buildFilePermissionRequest(e,t){const n="edit_file"===e?t.oldValue:void 0,r="edit_file"===e?t.newValue:void 0;return{action:getFileAction(e),filePath:String(t.filePath??t.file_path??t.path??t.absolutePath??"unknown"),description:"string"==typeof t.description?t.description:`${e} operation`,oldContent:"string"==typeof n?n:void 0,newContent:"string"==typeof r?r:void 0}}function useContextEngine({sessionId:e,sessionLoaded:t,showSessionSelector:n,projectTrusted:r,setFeed:s,setLiveAgents:o,setQueuedMessages:i,queuedMessagesRef:a,setStatus:l,pinnedStatusRef:u,setRetryAttempt:d,setInteractionTokens:m,setContextUsage:p,setCurrentProvider:g,shareInfoRef:h,permissionsService:f,permissionModeRef:y,setPendingQuestion:w,contextEngineRef:S}){const b=V(t=>({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;if(!t||"running"!==n)return t&&n&&"running"!==n?(o(t=>t.filter(t=>t.id!==e.id)),void s(t=>[...t,e])):void s(t=>[...t,e]);o(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]})},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...a.current];return a.current=[],i([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{m(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{p(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{d(e)},"onRetryUpdate"),onProviderChange:__name(e=>{g(e)},"onProviderChange"),onStatusUpdate:__name(e=>{u.current=!0,l(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{const r=t??{};if(!f)return!0;if("shell_command"===e){const e=buildShellPermissionRequest(r,n);return(await f.requestShellPermission(e)).allowed}if("kill_shell"===e){const e=createKillShellPermissionRequest(r);return(await f.requestShellPermission(e)).allowed}const s=buildFilePermissionRequest(e,r);return(await f.requestPermission(s)).allowed},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{w({params:e,resolve:t,reject:n}),l("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const n=h.current;return n?{sessionId:t??e,secret:n.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>y.current,"getPermissionMode")}),[f,e]);return G(()=>{S.current||!r||n||t||(S.current=new CC(b(),e))},[e,n,t,r,b,S]),{createContextEngineCallbacks:b}}Nt(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),__name(usePermissionMode,"usePermissionMode"),Nt(),__name(usePendingOps,"usePendingOps"),Nt(),__name(useOnboarding,"useOnboarding"),Nt(),__name(useExit,"useExit"),Nt(),_C(),__name(createKillShellPermissionRequest,"createKillShellPermissionRequest"),__name(buildShellPermissionRequest,"buildShellPermissionRequest"),__name(getFileAction,"getFileAction"),__name(buildFilePermissionRequest,"buildFilePermissionRequest"),__name(useContextEngine,"useContextEngine"),Nt(),Nt(),Nt(),$n();var sv=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(h.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await $.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 $.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await $.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 $.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await $.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await $.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(){return this.cleanupPromise||(this.cleanupPromise=this.performCleanup().finally(()=>{this.cleanupPromise=null})),this.cleanupPromise}async performCleanup(){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 sv}__name(createHistoryManager,"createHistoryManager"),CE(),Zo(),ar(),nr(),Nt(),Ot(),fC();var ov=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await $.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await $.access(r);const e=await $.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await $.writeFile(r,t,"utf-8")}catch{await $.writeFile(r,lC+"\n\n","utf-8")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await $.access(n),!0}catch{return!1}}};mo(),nr(),PC(),Nt(),_C(),Jo(),PC(),Nt(),Ot(),Jl(),bE(),ts();var{setText:iv}=Qe;async function loadShareInfo({contextEngineRef:e,setShareInfo:t}){const n=e.current?.getSessionManager();if(n){const e=await n.loadShareInfo();e&&t({url:e.url,secret:e.secret})}}async function handleShareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setShowShareNotification:s,contextEngineRef:o}){if(e){if(t)return await iv(t.url),r(""),s(!0),void setTimeout(()=>{s(!1)},3e3);try{r("Creating share link...");const t=o.current?.getMessages()||[],i=$l.sanitizeMessages(t,global.COMMAND_CODE_CWD||process.cwd()),a=new Vb({baseUrl:getApiBaseUrl()}),l=await a.post({endpoint:St.ALPHA.SHARE.CREATE,body:{sessionId:e,messages:i}});n({url:l.url,secret:l.secret});const u=o.current?.getSessionManager();u&&await u.saveShareInfo({url:l.url,secret:l.secret}),await iv(l.url),r(""),s(!0),setTimeout(()=>{s(!1)},5e3)}catch(e){r(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else r("No active session to share")}async function handleUnshareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setUnshareNotificationMessage:s,contextEngineRef:o}){if(e){if(!t)return s("NOT SHARED: Session is not currently shared"),void setTimeout(()=>s(""),5e3);try{r("Removing share link...");const i=new Vb({baseUrl:getApiBaseUrl()});await i.delete({endpoint:St.ALPHA.SHARE.DELETE,body:{sessionId:e,secret:t.secret}});const a=o.current?.getSessionManager();a&&await a.deleteShareInfo(),s("UNSHARED: Sharing has stopped"),r(""),n(null),setTimeout(()=>{s("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;r(t),setTimeout(()=>r(""),5e3)}}else r("No active session to unshare")}async function handleSelectSession({selectedSessionId:e,sessionLoadIdRef:t,contextEngineRef:n,setFeed:r,setLiveAgents:s,setSessionId:o,setShowSessionSelector:i,setSessionLoaded:a,setPermissionMode:l,setStaticKey:u,setShareInfo:d,createContextEngineCallbacks:m}){const p=crypto.randomUUID();t.current=p;try{r([]),s([]),n.current=null,l("standard"),o(e),i(!1),a(!0),n.current=new CC(m(e),e);const{feedEntries:g,corruptedLines:h,totalLines:f}=await n.current.loadSession(e);if(t.current!==p)return;await loadShareInfo({contextEngineRef:n,setShareInfo:d});const y=[];if(0===g.length&&f>0&&y.push(Lo(`Session could not be loaded. ${f} lines could not be parsed.`)),0===g.length&&0===f&&y.push(xo("Session loaded but contains no messages.")),g.length>0&&(h>0&&y.push(xo(`Warning: ${h} message(s) could not be loaded.`)),y.push(...g)),t.current!==p)return;r(y),kC(),u(e=>e+1)}catch(e){if(t.current!==p)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";r([Lo(`Failed to load session: ${n}. Starting fresh session.`)]),i(!1),a(!1),o(crypto.randomUUID())}}async function handleNewSession({contextEngineRef:e,setFeed:t,setLiveAgents:n,setSessionId:r,setShowSessionSelector:s,setSessionLoaded:o,setPermissionMode:i}){t([]),n([]),e.current=null,i("standard"),r(crypto.randomUUID()),s(!1),o(!1)}function useStartup({resume:e,continueLatest:t,trust:n,initialPrompt:r,stdout:s,feedState:o,sessionState:i,statusState:a,authState:l,onboarding:u,uiOverlays:d,permissionState:m,contextEngineRef:p,isSubmittingRef:g,initialPromptSubmittedRef:h,historyManagerRef:f,executeBash:y,createContextEngineCallbacks:w,setInput:S}){const b=V(async()=>{try{const e=await isTasteLearningEnabled();a.setTasteLearningEnabled(e),e&&await ov.initializeProject()}catch{}},[a.setTasteLearningEnabled]),E=V(async()=>{const e=await getConfiguredProvider();l.setCurrentProvider(e);const t=await isOAuthEnforced();l.setIsOAuthMode(t)},[l.setCurrentProvider,l.setIsOAuthMode]),C=V(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(()=>{})},[]),v=V(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:i.sessionLoadIdRef,contextEngineRef:p,setFeed:o.setFeed,setLiveAgents:o.setLiveAgents,setSessionId:i.setSessionId,setShowSessionSelector:d.setShowSessionSelector,setSessionLoaded:i.setSessionLoaded,setPermissionMode:m.setPermissionMode,setStaticKey:d.setStaticKey,setShareInfo:a.setShareInfo,createContextEngineCallbacks:w})},[i,o,d,m,a,p,w]),T=V(async()=>{if(t){const e=await Yb.listSessions();return void(e.length>0&&v(e[0].id))}e&&d.setShowSessionSelector(!0)},[t,e,v,d]);G(()=>{(async()=>{await Yb.isProjectInitialized()?(u.setProjectTrusted(!0),u.setCheckingProject(!1),b(),E(),C(),await T()):n?(await Yb.initializeProject(),u.setProjectTrusted(!0),u.setCheckingProject(!1),b(),E(),C(),await T()):isDirectoryEmpty()?(await Yb.initializeProject(),u.setProjectTrusted(!0),u.setCheckingProject(!1),b(),E(),C()):(u.setShowTrustPrompt(!0),u.setCheckingProject(!1))})()},[e,t,n]),G(()=>{if(!u.projectTrusted)return;const e=createHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[u.projectTrusted]),G(()=>{if(!s)return;const e=__name(()=>{d.showLearningFeed||(kC(),d.setStaticKey(e=>e+1))},"handleResize");return s.on("resize",e),()=>{s.off("resize",e)}},[s]),G(()=>{r&&u.projectTrusted&&!u.checkingProject&&p.current&&!d.showSessionSelector&&!h.current&&(h.current=!0,handleSubmit({role:"user",input:r,feed:o.feed,setFeed:o.setFeed,isCmdCodeBusy:o.isCmdCodeBusy,setIsCmdCodeBusy:o.setIsCmdCodeBusy,setQueuedMessages:o.setQueuedMessages,setStatus:a.setStatus,setInteractionTokens:a.setInteractionTokens,updateStatus:a.updateStatus,setUpdateStatus:a.setUpdateStatus,billingLink:a.billingLink,setBillingLink:a.setBillingLink,contextEngineRef:p,isSubmittingRef:g,setInput:S,setStaticKey:d.setStaticKey,executeBash:y}))},[r,u.projectTrusted,u.checkingProject,d.showSessionSelector]);const k=Q(null);k.current={feed:o.feed,setFeed:o.setFeed,isCmdCodeBusy:o.isCmdCodeBusy,setIsCmdCodeBusy:o.setIsCmdCodeBusy,setQueuedMessages:o.setQueuedMessages,setStatus:a.setStatus,setInteractionTokens:a.setInteractionTokens,updateStatus:a.updateStatus,setUpdateStatus:a.setUpdateStatus,billingLink:a.billingLink,setBillingLink:a.setBillingLink,contextEngineRef:p,isSubmittingRef:g,setInput:S,setStaticKey:d.setStaticKey,executeBash:y,role:"",input:""};const _=V(async({role:e,input:t,images:n,ideContext:r})=>handleSubmit({...k.current,role:e,input:t,images:n,ideContext:r}),[]);return{loadTasteStatus:b,loadCurrentProvider:E,initializeMcpInBackground:C,onSubmit:_}}__name(loadShareInfo,"loadShareInfo"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),__name(handleSelectSession,"handleSelectSession"),__name(handleNewSession,"handleNewSession"),IC(),__name(useStartup,"useStartup"),Nt(),dn(),Jo(),un(),Nt(),Ot(),$n(),Nt();var av={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return av[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Ne(t);return e.join(f.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 $.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(t,n=process.cwd()){try{const r=getGlobalProjectSettingsPath(n),s=e.dirname(r);await $.mkdir(s,{recursive:!0}),await $.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),ZE.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 $.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"),Nt(),$n(),tC(),Ot(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),Nt(),$n();var lv=e.join(h.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=_(e,{encoding:"utf8"}),n=Ge.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 $.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const s=await $.readdir(t);for(const o of s){if(!/^\d{4}$/.test(o))continue;const s=e.join(t,o);if(!(await $.stat(s)).isDirectory())continue;const i=await $.readdir(s);for(const t of i){if(!/^\d{2}$/.test(t))continue;const i=e.join(s,t);if(!(await $.stat(i)).isDirectory())continue;const a=await $.readdir(i);for(const s of a){if(!/^\d{2}$/.test(s))continue;const a=e.join(i,s);if(!(await $.stat(a)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${o}/${t}/${s}`});const l=(await $.readdir(a)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(a,t));r.push(...l)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const s=[];for(let o=0;o<e.length;o+=n){const i=e.slice(o,o+n),a=await Promise.all(i.map(t));for(const e of a)null!==e&&s.push(e);r?.(Math.min(o+n,e.length),e.length)}return s}async function findCodexSessions(t,n,r=0){const s=t||process.cwd(),o=[];dlog(`[Codex] scanning for project: ${s}`);const i=await findAllSessionFiles(lv,n);if(0===i.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${i.length} session files to scan`),n?.({phase:"reading",totalFiles:i.length,processedFiles:0,matchedSessions:0});let a=0;const l=await processFilesInBatches(i,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===s)try{const r=await $.stat(t),s=e.basename(t,".jsonl");return{id:n.id||s,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)=>{a=o.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:a})});o.push(...l);const u=r>0?o.slice(0,r):o;return dlog(`[Codex] matched ${u.length} sessions for project`),n?.({phase:"complete",totalFiles:i.length,processedFiles:i.length,matchedSessions:u.length}),u.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 $.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=e?.learnedSessions||{},n=e?.skippedSessions||{},r={};for(const e of new Set([...Object.keys(t),...Object.keys(n)]))r[e]=[...t[e]||[],...n[e]||[]];const s=await findNewSessions(r),o=(s["claude-code"]?.length||0)+(s.codex?.length||0);return o>0?(dlog(`[Onboarding] found ${o} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:o,hasTasteContent:!0,agentSessions:buildAgentSessionsList(s)}):(isOnboardingDone(e)?dlog(`[Onboarding] ${e?.skipped?"user skipped":"already completed"}, no new sessions`):dlog("[Onboarding] no sessions to learn from, skipping"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:isOnboardingDone(e),agentSessions:[]})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[]}}}async function getSessionFilesFromDir(e){try{return(await $.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"]||[],s=t.codex||[];try{const t=e.join(h.homedir(),".claude","projects");await $.access(t);const s=getProjectDirName(process.cwd()),o=(await $.readdir(t)).filter(e=>e===s);for(const s of o){const o=e.join(t,s);if((await $.stat(o)).isDirectory()){const e=await getSessionFilesFromDir(o);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=>!s.includes(e)));dlog(`[Sessions] codex: ${n.codex?.length||0} new, ${s.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]||[];if(n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.skippedSessions?.[e]){const r=new Set(t);n.tasteOnboarding.skippedSessions[e]=n.tasteOnboarding.skippedSessions[e].filter(e=>!r.has(e)),0===n.tasteOnboarding.skippedSessions[e].length&&delete n.tasteOnboarding.skippedSessions[e]}n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0;try{const t=e.tasteOnboarding.learnedSessions||{},n=await findNewSessions(t);e.tasteOnboarding.skippedSessions||(e.tasteOnboarding.skippedSessions={});for(const[t,r]of Object.entries(n))if(r.length>0){const n=e.tasteOnboarding.skippedSessions[t]||[];e.tasteOnboarding.skippedSessions[t]=Array.from(new Set([...n,...r]))}}catch{dlog("[Onboarding] failed to record skipped sessions, skip flag still set")}await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:s}){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})`),s(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:s,onboarding:o,uiOverlays:i,skipOnboarding:a}){G(()=>{if(n.shouldExit){r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),s.providerNotificationTimer.current&&clearTimeout(s.providerNotificationTimer.current),s.modelNotificationTimer.current&&clearTimeout(s.modelNotificationTimer.current);try{e()}catch{process.exit(0)}}},[n.shouldExit,e]),G(()=>()=>{r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),s.providerNotificationTimer.current&&clearTimeout(s.providerNotificationTimer.current),s.modelNotificationTimer.current&&clearTimeout(s.modelNotificationTimer.current)},[]),G(()=>{(async()=>{if("anthropic"===s.currentProvider&&s.isOAuthMode)try{await on.getValidAccessToken()||r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}catch{r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[s.currentProvider,s.isOAuthMode]),G(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(Wo())},7e3);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),G(()=>{a||triggerTasteOnboarding({projectTrusted:o.projectTrusted,onboardingComplete:o.onboardingComplete,isOnboardingMode:o.showTasteOnboarding,tasteOnboardingCheckedRef:o.tasteOnboardingCheckedRef,setIsOnboardingMode:o.setShowTasteOnboarding})},[o.projectTrusted,o.onboardingComplete,o.showTasteOnboarding,a]),G(()=>{if(o.showTasteOnboarding&&!o.tasteOnboardingEntryId){const e=Mo();o.setTasteOnboardingEntryId(e.id),t.setFeed(t=>[...t,e])}!o.showTasteOnboarding&&o.tasteOnboardingEntryId&&(t.setFeed(e=>e.filter(e=>e.id!==o.tasteOnboardingEntryId)),o.setTasteOnboardingEntryId(null))},[o.showTasteOnboarding,o.tasteOnboardingEntryId])}__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(triggerTasteOnboarding,"triggerTasteOnboarding"),__name(useLifecycle,"useLifecycle"),Nt(),PC(),CE(),Jo(),Nt(),ln(),ar(),PC(),Ot(),Nt();var cv=" ";function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showProviderSelector:n,showModelSelector:r,showMemorySelector:s,showMcpManager:o,showLearningFeed:i,showRewindSelector:a,showLoginOverlay:l,showAddDirModal:u,authComponentInfo:d,setShowLearningFeed:m,setShowModelSelector:p,setStaticKey:g,transcriptMode:h,setTranscriptMode:f,isCmdCodeBusy:y,liveAgents:w,queuedMessagesRef:S,setInput:b,setQueuedMessages:E,setFeed:C,setLiveAgents:v,setIsCmdCodeBusy:T,setRetryAttempt:k,setStatus:_,pendingExitKey:P,setPendingExitKey:A,pendingExitKeyRef:x,lastExitKeyTimeRef:I,exitConfirmationTimeoutRef:N,resetPendingExitKey:R,pendingPermission:$,setPendingPermission:L,pendingQuestion:M,setPendingQuestion:O,setShouldExit:D,contextEngineRef:q,handleToggleAutoAccept:F,handleDoubleEscapeEmpty:j,respondToPrompt:z,createErrorEntry:B}){const U=__name(()=>{if(!q.current)return;q.current.interrupt(!0);const e=w.length>0;if(T(!1),k(null),v([]),_("Interrupted by user"),!e){const e=B("Interrupted by user");C(t=>[...t,e])}if(S.current.length>0){const e=S.current.join("\n");b(t=>t?e+"\n"+t:e),E([]),S.current=[]}},"handleInterrupt");Z((w,S)=>{if(S.shift&&S.tab||""===w)F();else if(e||t||n||r||s||o||d||i||a||l||u)P&&R();else{if(""===w||S.ctrl&&"c"===w){if(y&&q.current)return void U();const e=Date.now(),t=e-I.current;return I.current=e,"ctrl-c"===x.current&&t<2e3?(N.current&&(clearTimeout(N.current),N.current=null),void D(!0)):(b(()=>""),x.current="ctrl-c",A("ctrl-c"),N.current&&clearTimeout(N.current),void(N.current=setTimeout(()=>{x.current=null,A(null),N.current=null},2e3)))}if(S.ctrl&&"t"===w)return kC(),m(!i),void g(e=>e+1);if(getIsExpandToolShortcut(S,w))return kC(),f("off"===h?"limited":"off"),void g(e=>e+1);if(S.ctrl&&"e"===w&&"off"!==h)return kC(),f("limited"===h?"full":"limited"),void g(e=>e+1);if(S.meta&&"p"===w||isAltP(w))p(!0);else if(S.escape){if(M)return M.reject(new Error("Question cancelled by user")),O(null),void _("Question cancelled");if($)return z({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),$.resolve(!1),L(null),void _("Permission denied");y&&q.current&&U()}}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:s,pendingOps:o,permissionState:i,statusState:a,authState:l,contextEngineRef:u,loadTasteStatus:d,loadCurrentProvider:m,setInput:p}){const g=V(()=>{i.setPermissionMode(e=>{let t="standard";if("standard"===e&&(t="auto-accept"),"auto-accept"===e&&(t="plan"),"auto-accept"===t&&o.pendingPermission){const e={label:"Yes",value:"yes",description:"Allow this action",scope:void 0};i.respondToPrompt(e),o.pendingPermission.resolve(!0),o.setPendingPermission(null)}return"plan"===t&&o.pendingPermission&&(o.pendingPermission.resolve(!1),o.setPendingPermission(null)),t})},[i.setPermissionMode,i.respondToPrompt,o.pendingPermission,o.setPendingPermission]),h=V(()=>{const e=!t.isCmdCodeBusy&&!o.pendingPermission&&!o.pendingQuestion,n=u.current?.hasCheckpoints()??!1;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,o.pendingPermission,o.pendingQuestion,r.setShowRewindSelector]),f=V(s=>{if(n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),kC(),s?.skipped){const e=xo("",{isTasteSkip:!0});t.setFeed(t=>[...t,e])}r.setStaticKey(e=>e+1),e&&r.setShowSessionSelector(!0)},[e,n,r,t]),y=V(async()=>{try{if(await Yb.initializeProject(),n.setShowTrustPrompt(!1),e)return console.log("No conversations found to resume."),void s.setShouldExit(!0);n.setProjectTrusted(!0),d(),m()}catch(e){console.error("Failed to initialize project:",e),n.setShowTrustPrompt(!1),s.setShouldExit(!0)}},[e,n,s,d,m]),w=V(()=>{s.setShouldExit(!0)},[s.setShouldExit]);return useKeyboard({showTasteConfig:r.showTasteConfig,showSkillsConfig:r.showSkillsConfig,showProviderSelector:r.showProviderSelector,showModelSelector:r.showModelSelector,showMemorySelector:r.showMemorySelector,showMcpManager:r.showMcpManager,showLearningFeed:r.showLearningFeed,showRewindSelector:r.showRewindSelector,showLoginOverlay:r.showLoginOverlay,showAddDirModal:r.showAddDirModal,authComponentInfo:l.authComponentInfo,setShowLearningFeed:r.setShowLearningFeed,setShowModelSelector:r.setShowModelSelector,setStaticKey:r.setStaticKey,transcriptMode:r.transcriptMode,setTranscriptMode:r.setTranscriptMode,isCmdCodeBusy:t.isCmdCodeBusy,liveAgents:t.liveAgents,queuedMessagesRef:t.queuedMessagesRef,setInput:p,setQueuedMessages:t.setQueuedMessages,setFeed:t.setFeed,setLiveAgents:t.setLiveAgents,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setRetryAttempt:a.setRetryAttempt,setStatus:a.setStatus,pendingExitKey:s.pendingExitKey,setPendingExitKey:s.setPendingExitKey,pendingExitKeyRef:s.pendingExitKeyRef,lastExitKeyTimeRef:s.lastExitKeyTimeRef,exitConfirmationTimeoutRef:s.exitConfirmationTimeoutRef,resetPendingExitKey:s.resetPendingExitKey,pendingPermission:o.pendingPermission,setPendingPermission:o.setPendingPermission,pendingQuestion:o.pendingQuestion,setPendingQuestion:o.setPendingQuestion,setShouldExit:s.setShouldExit,contextEngineRef:u,handleToggleAutoAccept:g,handleDoubleEscapeEmpty:h,respondToPrompt:i.respondToPrompt,createErrorEntry:Lo}),{handleToggleAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:w}}__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Nt(),Nt(),Ot(),Jo(),ir(),Nt();var uv='You are an expert code reviewer. Do follow these steps:\n\nGather PR context using the GitHub CLI:\n1. When no PR number is given, list open PRs with `gh pr list` and ask which one to review\n2. Fetch PR metadata via `gh pr view <number>`\n3. Retrieve the changeset with `gh pr diff <number>`\n4. One go gather context: Run gh pr view <number> && echo "---DIFF---" && gh pr diff <number>\n5. Analyze the changes and provide a thorough code review that includes:\n\t- Overview of the PR is doing\n\t- Analysis of the code quality and style\n\t- Give specific suggestions for improvement\n\t- Highlight any potential bugs/issues or risks\n\t- Score PR on a scale of 1-5 based on overall table with quality and readiness for merging\nKeep your review concise, less wordy, but thorough.\nFocus on:\n- Correctness of code\n- Following project conventions\n- Performance issues and implications\n- Test coverage\n- Security considerations\n\nBe less wordy. If you make a table, don\'t go over 60pts.\nFormat your review in sections and bullets.';function buildReviewPrompt({prNumber:e}){const t=e.trim();return t?`${uv}\n\nReview PR number: ${t}`:`${uv}\n\nReview PR number: `}function loadCustomCommands(){const e=[],n=t.join(process.cwd(),".commandcode","commands"),r=t.join(f.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,s=""){if(S.existsSync(n))try{const o=S.readdirSync(n,{withFileTypes:!0});for(const i of o){const o=t.join(n,i.name);if(i.isDirectory())loadCommandsFromDirectory(o,r,s?`${s}/${i.name}`:i.name);else if(i.isFile()&&i.name.endsWith(".md")){const n=t.basename(i.name,".md"),a=S.readFileSync(o,"utf-8").trim();e.push({name:n,source:r,content:a,subdirectory:s})}}}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}__name(buildReviewPrompt,"buildReviewPrompt"),Nt(),Nt(),Ot(),Nt(),Ot(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),ir(),Nt();var dv=["Code","Code - Insiders","VSCodium","Cursor"],mv="Code",pv={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},gv=__name(e=>m(e).href,"formatPathForTerminal"),hv=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),fv=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),yv=__name(({home:t,configSegments:n,variants:r})=>{for(const s of r){const r=fv({home:t,configSegments:n,variant:s});if(w.existsSync(e.dirname(r)))return s}return null},"findExistingVariant"),wv=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Sv(t.when)},"isTerminalShiftEnterBinding"),Sv=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),bv=__name(e=>{const t=He(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),Ev=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),Cv=__name(({error:e,content:t})=>{const n=e.message;return Ev(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"),vv=__name(e=>{let t="",n=!1,r=!1;for(let s=0;s<e.length;s++){const o=e[s];if(n)t+=o,r?r=!1:"\\"===o?r=!0:'"'===o&&(n=!1);else if('"'!==o){if(","===o){let t=s+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=o}else n=!0,t+=o}return t},"removeTrailingCommas"),Tv=__name(e=>{try{const t=He(e),n=vv(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:Cv({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),kv=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:gv(t)}),"createSuccessResult"),_v=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:gv(t)}),"createErrorResult"),Pv=__name(()=>{const t=h.homedir(),n=h.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=hv(n);if(!r)return fv({home:t,configSegments:[".config"],variant:mv});const s=yv({home:t,configSegments:r,variants:dv});return fv({home:t,configSegments:r,variant:s??mv})},"getVSCodeKeybindingsPath"),Av=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)wv(n)&&(n.command===pv.command&&n.args?.text===pv.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),xv=__name(t=>{try{if(!w.existsSync(t)){const n=e.dirname(t);return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=w.readFileSync(t,"utf-8");if(bv(n))return{rawContent:n,keybindings:[]};const r=Tv(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:_v({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):_v({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return _v({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),Iv=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(pv,null,2);if(bv(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return _v({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const s=e.lastIndexOf("}",r);return-1===s?_v({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,s+1)+",\n"+n+e.substring(s+1)},"generateNewContent");function setupVSCodeTerminal(){const e=Pv();try{const t=xv(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,s=Av(r);if(s.hasConflicting)return _v({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(s.hasCompatible)return kv({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const o=Iv({rawContent:n,keybindingsPath:e});return"string"!=typeof o?o:(w.writeFileSync(e,o,"utf-8"),kv({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return _v({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"),jr(),rr();var Nv=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear",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.MCP="/mcp",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.REVIEW="/review",e.PR_COMMENTS="/pr-comments",e))(Nv||{}),Rv=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/provider","/model","/memory","/init","/agents","/mcp","/compact","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/pr-comments"]),$v=[{command:"/add-dir",description:"Add directory to workspace context"},{command:"/agents",description:"Manage agent configurations"},{command:"/clear",description:"Clear the conversation history (reset, new)"},{command:"/compact",description:"Compact the conversation history"},{command:"/exit",description:"Exit Command Code"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/help",description:"Show available shortcuts"},{command:"/ide",description:"Install extension to fetch IDE context"},{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/memory",description:"Manage Command Code memory"},{command:"/model",description:"Switch between Command Code models"},{command:"/pr-comments",description:"Fetch all PR comments for current branch"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/resume",description:"Resume a past conversation"},{command:"/review",description:"Review a pull request (optional PR number)"},{command:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/unshare",description:"Stop sharing conversation"}],Lv=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[s,o]=W(0),[i,a]=W(0),{stdout:l}=X(),u=l?.columns??80,d=Math.max(20,u-22-2-1-2),m=H(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...$v.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!r)return e;const t=r.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let s=0;return n.startsWith("/"+t)?s+=100:n.includes(t)&&(s+=50),r.includes(t)&&(s+=25),{...e,score:s}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[r]),p=H(()=>{const e=i,t=Math.min(e+8,m.length);return m.slice(e,t)},[m,i]);return G(()=>{o(0),a(0)},[r]),Z((r,l)=>{if(l.escape)n();else if(l.upArrow)o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t});else if(l.downArrow)o(e=>{const t=Math.min(m.length-1,e+1);return t>=i+8&&a(Math.max(0,t-8+1)),t});else{if(l.return){const t=m[s];return void(t&&e(t.command))}if(l.tab||l.rightArrow){const e=m[s];return void(e&&t(e.command))}}}),0===m.length?B.createElement(K,{flexDirection:"column",paddingLeft:2},B.createElement(Y,{color:Ln.DIM},"No commands found")):(m.length,B.createElement(K,{flexDirection:"column",paddingLeft:1},B.createElement(K,{columnGap:2},B.createElement(K,{flexDirection:"column",width:22},p.map((e,t)=>{const n=i+t;return B.createElement(Y,{key:n,color:s===n?Ln.WHITE:Ln.DIM,wrap:"truncate"},e.command)})),B.createElement(K,{flexDirection:"column"},p.map((e,t)=>{const n=i+t;return B.createElement(Y,{key:n,color:s===n?Ln.WHITE:Ln.DIM,wrap:"truncate"},truncateString({text:e.description,maxChars:d}))})))))},"CommandMenu");qE(),Nt(),Nt(),ar(),rr();var Mv=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),Ov=__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"),Dv=__name(({icon:e,label:t,children:n})=>B.createElement(Y,null,B.createElement(Y,{color:Ln.CYAN},e," "),B.createElement(Y,{dimColor:!0},t.padEnd(12)),n),"Row"),qv=__name(({title:e})=>B.createElement(Y,null,B.createElement(Y,{color:Ln.GRAY},"───"),B.createElement(Y,{color:Ln.WHITE}," ",e," "),B.createElement(Y,{color:Ln.GRAY},"─".repeat(35))),"Header"),Fv=__name(({title:e,marginTop:t=0,children:n})=>B.createElement(K,{flexDirection:"column",marginTop:t},B.createElement(qv,{title:e}),B.createElement(K,{flexDirection:"column",paddingY:1},n)),"Section"),jv=__name(({cpuCount:e,totalMem:t})=>B.createElement(Fv,{title:"System Information"},B.createElement(Dv,{icon:be.bullet,label:"Date"},B.createElement(Y,null,formatDate())),B.createElement(Dv,{icon:be.pointer,label:"Platform"},B.createElement(Y,{color:Ln.GREEN},Mv(h.platform())),B.createElement(Y,{dimColor:!0}," ","(",h.platform(),", ",h.arch(),")")),B.createElement(Dv,{icon:be.triangleUp,label:"Hostname"},B.createElement(Y,null,h.hostname())),B.createElement(Dv,{icon:be.bullet,label:"User"},B.createElement(Y,{color:Ln.YELLOW},h.userInfo().username)),B.createElement(Dv,{icon:be.bullet,label:"CPUs"},B.createElement(Y,{color:Ln.MAGENTA},e," cores")),B.createElement(Dv,{icon:be.bullet,label:"Memory"},B.createElement(Y,{color:Ln.CYAN},t," GB")),B.createElement(Dv,{icon:be.play,label:"Uptime"},B.createElement(Y,null,Ov(h.uptime()))),B.createElement(Dv,{icon:be.arrowRight,label:"Home"},B.createElement(Y,{dimColor:!0},h.homedir())),B.createElement(Dv,{icon:be.pointer,label:"Shell"},B.createElement(Y,null,process.env.SHELL||"N/A")),B.createElement(Dv,{icon:be.bullet,label:"Node"},B.createElement(Y,{color:Ln.GREEN},process.version))),"SystemInfoSection"),zv=__name(({cpus:e})=>B.createElement(Fv,{title:"CPU Details",marginTop:1},e.map((e,t)=>B.createElement(Dv,{key:t,icon:be.bullet,label:`Core ${t}`},B.createElement(Y,null,e.model.trim()),B.createElement(Y,{color:Ln.YELLOW}," @ ",e.speed," MHz")))),"CPUDetailsSection"),Bv=__name(({networkInterfaces:e})=>B.createElement(Fv,{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)=>B.createElement(Dv,{key:`${e}-${n}`,icon:be.bullet,label:e},B.createElement(Y,{color:Ln.GREEN},t.address))):null})),"NetworkSection"),Uv=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>B.createElement(K,{flexDirection:"column"},B.createElement(Y,null,"System Information"),B.createElement(Y,null,"─".repeat(40)),B.createElement(Y,null,"Date ",formatDate()),B.createElement(Y,null,"Platform ",Mv(h.platform())," (",h.platform(),","," ",h.arch(),")"),B.createElement(Y,null,"Hostname ",h.hostname()),B.createElement(Y,null,"User ",h.userInfo().username),B.createElement(Y,null,"CPUs ",e.length," cores"),B.createElement(Y,null,"Memory ",t," GB"),B.createElement(Y,null,"Uptime ",Ov(h.uptime())),B.createElement(Y,null,"Home ",h.homedir()),B.createElement(Y,null,"Shell ",process.env.SHELL||"N/A"),B.createElement(Y,null,"Node ",process.version),r&&B.createElement(B.Fragment,null,B.createElement(Y,null,"\n","CPU Details"),B.createElement(Y,null,"─".repeat(40)),e.map((e,t)=>B.createElement(Y,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),B.createElement(Y,null,"\n","Network"),B.createElement(Y,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>B.createElement(Y,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Wv=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>B.createElement(K,{flexDirection:"column"},B.createElement(jv,{cpuCount:e.length,totalMem:t}),r&&B.createElement(zv,{cpus:e}),r&&B.createElement(Bv,{networkInterfaces:n})),"StyledInfo"),Qv=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=te();G(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=h.cpus(),s=h.networkInterfaces(),o=Math.round(h.totalmem()/1024/1024/1024);return t?B.createElement(Uv,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e}):B.createElement(Wv,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e})},"InfoUI"),Gv={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},Hv=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),Vv=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(Hv("__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"),Kv=__name(()=>{const e=Vv();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&Gv[t]?Gv[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),Yv=__name(()=>{if("win32"===f.platform()){const e=process.env.COMSPEC;return e?a(e):process.env.SHELL?a(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=I(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=a(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?a(e):"N/A"},"getShellName"),Jv=__name(()=>{const e=Vv();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),Xv=__name(()=>{try{const e=I("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:Mv(f.platform()),terminal:Kv(),shell:Yv(),version:Xv(),ide:Jv()}}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?"":""}`}function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",s=!1,o="";for(let e=0;e<t.length;e++){const i=t[e];'"'!==i&&"'"!==i||s?i===o&&s?(s=!1,o=""):" "!==i||s?r+=i:(r.trim()&&n.push(r.trim()),r=""):(s=!0,o=i)}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 s=n.substring(0,r),o=n.substring(r+1).trim();return{commandName:s,rawArguments:o,positionalArgs:parsePositionalArguments({input:o})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let s=t;return s=s.replace(/\$ARGUMENTS/g,n),s=s.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:s}}async function handleCompactCommand({contextEngineRef:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:s,setStaticKey:o}){if(e.current)if(e.current.isRequestInProgress())t(e=>[...e,xo("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{r(!0),n("Compacting conversation...");const i=await e.current.manualCompact();kC(),o(e=>e+1);let a="Compacted conversation.";i.didCompact||(a="Conversation is already compact."),i.didCompact&&i.tokensSaved>0&&(a=`Compacted conversation, saved ~${i.tokensSaved.toLocaleString()} tokens.`),t(e=>[...e,xo(a)]),r(!1),n("Ready..."),s({current:e.current.getContextTokensUsed()||0,limit:xE})}catch(e){const s=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;t(e=>[...e,Lo(s)]),r(!1),n("Ready...")}else t(e=>[...e,xo("No active conversation to compact.")])}function handleRewindCommand({contextEngineRef:e,setFeed:t,setShowRewindSelector:n}){e.current?e.current.hasCheckpoints()?n(!0):t(e=>[...e,xo("No checkpoints available. Start sending messages to create checkpoints.")]):t(e=>[...e,xo("No active conversation to rewind.")])}async function handleRewindSelect({messageId:e,mode:t,contextEngineRef:n,setFeed:r,setStatus:s,setShowRewindSelector:o,setStaticKey:i,setInput:a}){if(o(!1),n.current)try{const o=n.current.listCheckpoints().find(t=>t.messageId===e);s("Restoring checkpoint...");const l=await n.current.restoreToCheckpoint({messageId:e,mode:t});if(l.success){const e=n.current.getSessionManager(),t=n.current.getMessages();r(e.reconstructFeedFromMessages(t)),kC(),i(e=>e+1),o?.userPrompt&&a(o.userPrompt);const u=[];l.filesRestored>0&&u.push(`${l.filesRestored} file${l.filesRestored>1?"s":""} restored`),l.filesDeleted>0&&u.push(`${l.filesDeleted} file${l.filesDeleted>1?"s":""} deleted`),l.messagesRemoved>0&&u.push(`${l.messagesRemoved} message${l.messagesRemoved>1?"s":""} removed`);const d=u.length>0?`Restored to checkpoint: ${u.join(", ")}.`:"Restored to checkpoint.";return r(e=>[...e,xo(d)]),void s("Ready...")}r(e=>[...e,Lo(`Failed to restore: ${l.error}`)]),s("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;r(e=>[...e,Lo(t)]),s("Ready...")}}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}async function handleLoginCommand({setFeed:e,setShowLoginOverlay:t}){const n=Lt();if(await getAuthKey(n)){let t="";try{const e=await loadCredentials();t=e?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const n=t&&"API Key"!==t&&"Manual API Key"!==t?` as ${t}`:"";return void e(e=>[...e,xo(`Already logged in${n}`)])}t(!0)}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:s,contextEngineRef:o}){if(n(!1),!e)return r(e=>[...e,Lo(t)]),void s("Ready...");r(e=>[...e,xo(t)]),o.current&&o.current.refreshRequest(),s("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,xo("Authentication cancelled.")]),n("Ready...")}async function handleLogoutCommand({setFeed:e,contextEngineRef:t}){const n=await performLogout();if(!n.success)return void e(e=>[...e,Lo(`Logout failed: ${n.error}`)]);if(t.current&&t.current.refreshRequest(),!n.wasAuthenticated)return void e(e=>[...e,xo("Not currently authenticated.")]);const r=n.warnings.length>0?`Successfully logged out from Command Code. Warnings: ${n.warnings.join(", ")}`:"Successfully logged out from Command Code.";e(e=>[...e,xo(r)])}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),Nt(),__name(createOSC8Link,"createOSC8Link"),Nt(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),PC(),Nt(),Jo(),PC(),$E(),__name(handleCompactCommand,"handleCompactCommand"),Nt(),Jo(),PC(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Nt(),Jo(),Qs(),Jr(),xs(),Ot(),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Nt(),Sl(),$n(),nr();var Zv=Ve(x);function getVsixPath(){try{const e=t.dirname(u(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return S.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),dl.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await Zv(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp("commandcode.commandcode-vscode@([\\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 Zv(`${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}}__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled");var eT={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"};async function ensureExtensionInstalled(){if(process.env.CI)return;const e=sl();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:Be.green("✔"),installed:Be.green("✔"),needs_reload:Be.yellow("◌"),failed:Be.red("✖"),not_in_ide:Be.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=>Be.dim(` ${e}`)),""]}async function runIDESetup(){const e=sl(),t=e?eT[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new dl,r=await n.connect(500);if(n.disconnect(),r)return{status:"connected",ide:t};const{installed:s}=await checkInstalled(e);return s?{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."]}}async function handleHelpCommand({setFeed:e}){const{createSystemEntry:t}=await Promise.resolve().then(()=>(Jo(),Yo));e(e=>[...e,t("KEYBOARD SHORTCUTS\nCOMMANDS")])}async function handleTerminalSetupCommand({setFeed:e}){const t=Ao(`/${Tt.TERMINAL_SETUP}`),n=setupVSCodeTerminal(),r=Oo(n.message,!n.success,n.details);e(e=>[...e,t,r])}async function handleIDESetupCommand({setFeed:e}){const t=await runIDESetup(),n=Do(t.status,t.ide,t.details);e(e=>[...e,n])}async function handleClearCommand({setFeed:e,setLiveAgents:t,setShareInfo:n,setShowShareNotification:r,setUnshareNotificationMessage:s,setStaticKey:o,setContextUsage:i,setInteractionTokens:a,contextEngineRef:l,setSessionId:u,createContextEngineCallbacks:d,clearSessionPermissions:m}){if(e([]),t([]),kC(),n(null),r(!1),s(""),l.current){const e=l.current.getSessionManager();e&&await e.deleteShareInfo(),l.current=null;const t=crypto.randomUUID();u(t),m();const{ContextEngine:n}=await Promise.resolve().then(()=>(_C(),TC));l.current=new n(d(t),t)}o(e=>e+1),i(null),a(0)}async function handleInitCommand({setFeed:e}){try{const t=process.cwd(),n=`Created AGENTS.md at ${await initProjectMemory(t)}. You can now edit it with /memory or open it in your editor.`;e(e=>[...e,xo(n)])}catch(t){const n=`Error: Failed to initialize AGENTS.md: ${t instanceof Error?t.message:"Unknown error"}`;e(e=>[...e,xo(n)])}}async function handleFeedbackCommand({setFeed:e},t){const n=buildGitHubIssueUrl(t);try{await ie(n,{wait:!1,background:!0}),e(e=>[...e,xo(`Opened ${createOSC8Link(n,"GitHub issue")} in your browser`)])}catch{const{createSystemEntry:t,createErrorEntry:r}=await Promise.resolve().then(()=>(Jo(),Yo));e(e=>[...e,r("Failed to open browser"),t(createOSC8Link(n,"Open GitHub issue manually"))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const s=Mo();n(s.id),r(e=>[...e,s])}async function handleCommand(e,t){if(e.startsWith("/resume:")){const n=e.substring(8);return await handleSelectSession({selectedSessionId:n,sessionLoadIdRef:t.sessionLoadIdRef,contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setLiveAgents:t.setLiveAgents,setSessionId:t.setSessionId,setShowSessionSelector:t.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:t.setPermissionMode,setStaticKey:t.setStaticKey,setShareInfo:t.setShareInfo,createContextEngineCallbacks:t.createContextEngineCallbacks}),{status:"handled"}}const n=parseCommandInput({input:e});if(!n)return{status:"unknown"};const{commandName:r,rawArguments:s,positionalArgs:o}=n;if(Rv.has(r)&&s.trim().length>0)return{status:"unknown"};if("/exit"===r)return t.setShouldExit(!0),{status:"handled"};if("/clear"===r)return await handleClearCommand(t),{status:"handled"};if("/help"===r)return await handleHelpCommand(t),{status:"handled"};if("/share"===r)return await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/unshare"===r)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/taste"===r)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===r)return handleLearnCommand(t),{status:"handled"};if("/skills"===r)return t.setShowSkillsConfig(!0),{status:"handled"};if("/provider"===r)return isInternalTeamFlagEnforced()?(t.setShowProviderSelector(!0),{status:"handled"}):(t.setStatus("Provider selection not available"),{status:"handled"});if("/model"===r)return t.setShowModelSelector(!0),{status:"handled"};if("/memory"===r)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===r)return t.setShowSessionSelector(!0),{status:"handled"};if("/init"===r)return await handleInitCommand(t),{status:"handled"};if("/agents"===r)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===r)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===r)return await handleCompactCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setContextUsage:t.setContextUsage,setStaticKey:t.setStaticKey}),{status:"handled"};if("/rewind"===r)return handleRewindCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/login"===r)return await handleLoginCommand({setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay}),{status:"handled"};if("/logout"===r)return await handleLogoutCommand({setFeed:t.setFeed,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/feedback"===r)return await handleFeedbackCommand(t),{status:"handled"};if("/terminal-setup"===r)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===r)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===r)return t.setShowAddDirModal(!0),{status:"handled"};if("/review"===r){const e=s.trim(),{handleSubmit:n}=await Promise.resolve().then(()=>(IC(),xC));return await n({input:buildReviewPrompt({prNumber:s}),role:"user",displayMessage:e?`/review ${e}`:"/review",feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}if("/pr-comments"===r)return await handleSubmit({input:"Fetch and display all comments from the current GitHub pull request.\n\n Run these commands in order:\n\n 1. `gh pr view --json number,headRepository` — if this fails, reply \"No comments found.\" and stop.\n 2. `gh api --paginate '/repos/{owner}/{repo}/issues/NUMBER/comments' --jq '.[] | {body,\n user: .user.login, id, created_at}' > /tmp/pr-NUMBER-issue-comments.json`\n 3. `gh api --paginate '/repos/{owner}/{repo}/pulls/NUMBER/comments' --jq '.[] | {body,\n diff_hunk: (.diff_hunk | split(\"\n\") | .[-5:] | join(\"\n\")), path, line, user: .user.login,\n in_reply_to_id, id, created_at}' > /tmp/pr-NUMBER-review-comments.json`\n\n If both return empty, reply \"No comments found.\"\n\n `{owner}` and `{repo}` are gh template variables — write them literally, never substitute. Always\n use `--jq` (not piped `| jq`).\n\n Read the temp JSON files to build output comments directly in markdown using the format:\n\n ## PR Comments\n\n - @author (date):\n > body\n\n ## Review Comments\n\n - @author path#line:\n ```diff (replace ```suggestion code blocks with ```diff to avoid rendering errors)\n [diff_hunk]\n ```\n > body [replies indented by in_reply_to_id]\n\n Number the comments in the order they were created (created_at).\n No explanatory text, no horizontal rules. No extra space in the end.",role:"user",displayMessage:"/pr-comments",feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"};const i=getCustomCommandContent(r);if(i){const e=processCommandTemplate({template:i,rawArguments:s,positionalArgs:o}),{handleSubmit:n}=await Promise.resolve().then(()=>(IC(),xC));return await n({input:e.content,role:"user",feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}return{status:"unknown"}}function useCommandCtx({feedState:e,sessionState:t,statusState:n,uiOverlays:r,onboarding:s,exitState:o,permissionState:i,contextEngineRef:a,isSubmittingRef:l,executeBash:u,createContextEngineCallbacks:d,setInput:m}){const p=H(()=>({feed:e.feed,setFeed:e.setFeed,setLiveAgents:e.setLiveAgents,setQueuedMessages:e.setQueuedMessages,setStatus:n.setStatus,setInteractionTokens:n.setInteractionTokens,setContextUsage:n.setContextUsage,setStaticKey:r.setStaticKey,updateStatus:n.updateStatus,setUpdateStatus:n.setUpdateStatus,billingLink:n.billingLink,setBillingLink:n.setBillingLink,shareInfo:n.shareInfo,setShareInfo:n.setShareInfo,setShowShareNotification:n.setShowShareNotification,setUnshareNotificationMessage:n.setUnshareNotificationMessage,setShowTasteConfig:r.setShowTasteConfig,setShowSkillsConfig:r.setShowSkillsConfig,setShowProviderSelector:r.setShowProviderSelector,setShowModelSelector:r.setShowModelSelector,setShowMemorySelector:r.setShowMemorySelector,setShowAgentsConfig:r.setShowAgentsConfig,setShowMcpManager:r.setShowMcpManager,setShowRewindSelector:r.setShowRewindSelector,setShowAddDirModal:r.setShowAddDirModal,setShowLoginOverlay:r.setShowLoginOverlay,setShowTasteOnboarding:s.setShowTasteOnboarding,setAutoLearnTaste:s.setAutoLearnTaste,setTasteOnboardingEntryId:s.setTasteOnboardingEntryId,sessionId:t.sessionId,setSessionId:t.setSessionId,sessionLoadIdRef:t.sessionLoadIdRef,sessionLoaded:t.sessionLoaded,setSessionLoaded:t.setSessionLoaded,setShowSessionSelector:r.setShowSessionSelector,setPermissionMode:i.setPermissionMode,contextEngineRef:a,clearSessionPermissions:i.clearSessionPermissions,createContextEngineCallbacks:d,setShouldExit:o.setShouldExit,setInput:m,isSubmittingRef:l,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:u}),[e,t,n,r,s,o,i,a,l,u,d,m]),g=Q(p);return g.current=p,{commandCtx:p,onCommand:V(e=>handleCommand(e,g.current),[])}}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:s,setShowProviderNotification:o,providerNotificationTimer:i}){try{const a=getProviderConfig(e);if(a?.requiresAuth&&a.checkAuth&&!await a.checkAuth()&&a.authComponent)return void r({provider:e,Component:a.authComponent});await updateUserConfig({provider:e}),t(e),n(!1),s(`Provider set to ${getProviderDisplayName(e)}`),i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),s("Failed to set provider"),n(!1)}}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:s,setShowProviderNotification:o,providerNotificationTimer:i}){e&&(t(null),n(!1),r(e.provider),s(`${getProviderDisplayName(e.provider)} authentication successful`),i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},5e3))}function handleAuthCancel({setAuthComponentInfo:e}){e(null)}function getModelDisplayName(e){const t=Object.values(kt).find(t=>t.id===e);return t?t.name:e}async function handleModelSelect({modelId:e,setCurrentModel:t,setShowModelSelector:n,setStatus:r,modelNotificationTimer:s,setShowModelNotification:o}){try{await setSelectedModel({model:e}),t(e),n(!1),r(`Model set to ${getModelDisplayName(e)}`),s.current&&clearTimeout(s.current),o(!0),s.current=setTimeout(()=>{o(!1),s.current=null},5e3)}catch(e){console.error("Failed to set model:",e),r("Failed to set model"),n(!1)}}function handleModelCancel({setShowModelSelector:e}){e(!1)}__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup"),IC(),__name(handleHelpCommand,"handleHelpCommand"),__name(handleTerminalSetupCommand,"handleTerminalSetupCommand"),__name(handleIDESetupCommand,"handleIDESetupCommand"),__name(handleClearCommand,"handleClearCommand"),__name(handleInitCommand,"handleInitCommand"),__name(handleFeedbackCommand,"handleFeedbackCommand"),__name(handleLearnCommand,"handleLearnCommand"),__name(handleCommand,"handleCommand"),__name(useCommandCtx,"useCommandCtx"),Nt(),Nt(),ir(),nr(),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel"),Nt(),Ot(),nr(),__name(getModelDisplayName,"getModelDisplayName"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel");var tT=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l}){const u=Q({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l});return u.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l},{onSelectSession:V(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a}=u.current;handleSelectSession({selectedSessionId:e,sessionLoadIdRef:n.sessionLoadIdRef,contextEngineRef:i,setFeed:t.setFeed,setLiveAgents:t.setLiveAgents,setSessionId:n.setSessionId,setShowSessionSelector:s.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,setPermissionMode:o.setPermissionMode,setStaticKey:s.setStaticKey,setShareInfo:r.setShareInfo,createContextEngineCallbacks:a})},[]),onNewSession:V(()=>{const{feedState:e,sessionState:t,uiOverlays:n,permissionState:r,contextEngineRef:s}=u.current;handleNewSession({contextEngineRef:s,setFeed:e.setFeed,setLiveAgents:e.setLiveAgents,setSessionId:t.setSessionId,setShowSessionSelector:n.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:r.setPermissionMode})},[]),onRewindSelect:V(({messageId:e,mode:t})=>{const{feedState:n,statusState:r,uiOverlays:s,contextEngineRef:o,setInput:i}=u.current;handleRewindSelect({messageId:e,mode:t,contextEngineRef:o,setFeed:n.setFeed,setStatus:r.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:i})},[]),onRewindCancel:V(()=>{handleRewindCancel({setShowRewindSelector:u.current.uiOverlays.setShowRewindSelector})},[]),onLoginComplete:V((e,t)=>{const{feedState:n,statusState:r,uiOverlays:s,contextEngineRef:o}=u.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:s.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus,contextEngineRef:o})},[]),onLoginCancel:V(()=>{const{feedState:e,statusState:t,uiOverlays:n}=u.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),handleProviderSelect:V(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:r.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:n.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer})},[]),handleProviderCancel:V(()=>{handleProviderCancel({setShowProviderSelector:u.current.uiOverlays.setShowProviderSelector})},[]),handleModelSelect:V(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleModelSelect({modelId:e,setCurrentModel:t.setCurrentModel,setShowModelSelector:r.setShowModelSelector,setStatus:n.setStatus,modelNotificationTimer:t.modelNotificationTimer,setShowModelNotification:tT})},[]),handleModelCancel:V(()=>{handleModelCancel({setShowModelSelector:u.current.uiOverlays.setShowModelSelector})},[]),handleAuthSuccess:V(()=>{const{authState:e,statusState:t,uiOverlays:n}=u.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:n.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:t.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer})},[]),handleAuthCancel:V(()=>{handleAuthCancel({setAuthComponentInfo:u.current.authState.setAuthComponentInfo})},[])}}__name(useMainActionCallbacks,"useMainActionCallbacks"),Nt(),Nt(),Nt();var nT=__name(({staticKey:e})=>B.createElement(J,{items:[{staticKey:e}],key:e},()=>B.createElement(Y,{key:e},"\0")),"Responsive");Nt(),Ot(),rr();var rT=__name(({onTrust:e,onExit:t})=>{const{exit:n}=te(),[r,s]=W(1),o=process.cwd().replace(process.env.HOME||"","~");return Z((o,i)=>{i.upArrow||i.downArrow?s(1===r?2:1):i.return?1===r?e():(t(),n()):"1"===o?e():("2"===o||i.escape||i.ctrl&&"c"===o)&&(t(),n())}),B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.YELLOW,padding:1},B.createElement(Y,{color:Ln.YELLOW,bold:!0},"Do you trust the files in this folder?"),B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY},o)),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),B.createElement(K,{marginTop:1},B.createElement(Y,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{color:1===r?Ln.CYAN:Ln.GRAY},1===r?be.pointer:" "," 1. Yes, proceed")),B.createElement(K,null,B.createElement(Y,{color:2===r?Ln.CYAN:Ln.GRAY},2===r?be.pointer:" "," 2. No, exit"))))},"TrustPrompt"),sT=U(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return B.createElement(B.Fragment,null,B.createElement(nT,{staticKey:e}),B.createElement(rT,{onTrust:t,onExit:n}))},"TrustView"));Nt(),Nt(),CE(),jr(),rr();var oT=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=te(),[r,s]=W([]),[o,i]=W(0),[a,l]=W(!0),[u,d]=W(0),m=30;G(()=>{p()},[]);const p=__name(async()=>{l(!0);const e=await Yb.listSessions();s(e),l(!1)},"loadSessions");if(Z((t,s)=>{s.upArrow?i(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):s.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=u+m&&d(t-m+1),t}):s.return?r.length>0&&e(r[o].id):(s.escape||s.ctrl&&"c"===t)&&n()}),a)return B.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(Y,{color:Ln.GRAY},"Loading sessions..."));const g=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(n/36e5),o=Math.floor(n/864e5),i=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:s<24?`${s} hour${s>1?"s":""} ago`:o<7?`${o} day${o>1?"s":""} ago`:1===i?"1 week ago":`${i} weeks ago`},"formatRelativeTime"),h=__name(e=>truncateString({text:e,maxChars:Nr}),"truncateMessage");if(0===r.length)return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.GRAY},"No sessions available"));const f=r.slice(u,u+m),y=u;return B.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.DIM},"Showing ",u+1,"-",Math.min(u+m,r.length)," ","of ",r.length," sessions",u>0&&" (↑ for more)",u+m<r.length&&" (↓ for more)")),B.createElement(K,{columnGap:2,marginBottom:1},B.createElement(K,{width:7},B.createElement(Y,{color:Ln.GRAY}," ")),B.createElement(K,{width:13},B.createElement(Y,{color:Ln.GRAY},"Modified")),B.createElement(K,{width:11},B.createElement(Y,{color:Ln.GRAY},"# Messages")),B.createElement(K,{width:20},B.createElement(Y,{color:Ln.GRAY},"Git Branch")),B.createElement(K,null,B.createElement(Y,{color:Ln.GRAY},"Summary"))),B.createElement(K,{columnGap:2},B.createElement(K,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`sel-${n}`,color:o===n?Ln.CYAN:Ln.GRAY},o===n?`${be.pointer} ${n+1}.`:` ${n+1}.`)})),B.createElement(K,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`mod-${e.id}`,color:o===n?Ln.WHITE:Ln.GRAY},g(e.lastModified))})),B.createElement(K,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`msg-${e.id}`,color:o===n?Ln.WHITE:Ln.GRAY},e.messageCount)})),B.createElement(K,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`branch-${e.id}`,color:o===n?Ln.WHITE:Ln.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),B.createElement(K,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`summary-${e.id}`,color:o===n?Ln.WHITE:Ln.GRAY},h(e.firstMessage))}))))},"SessionTable"),iT=U(__name(function SessionView2({onSelectSession:e,onNewSession:t}){return B.createElement(oT,{onSelectSession:e,onNewSession:t})},"SessionView"));Nt(),Nt(),vn(),rr();var aT=__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"),lT=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r,hideReview:s=!1})=>{if(s&&1===e.length)return null;const o=[];if(e.forEach((s,i)=>{const a=i===t&&!r,l=n.has(i);let u,d;a?(u=be.bullet,d=Ln.CYAN):l?(u=be.tick,d=Ln.GREEN):(u=be.circle,d=Ln.GRAY),o.push(B.createElement(Y,{key:i},B.createElement(Y,{color:d},u),B.createElement(Y,{color:a?Ln.CYAN:void 0}," ",s.header),i<e.length-1?B.createElement(Y,{dimColor:!0}," | "):null))}),!s){const e=r;o.push(B.createElement(Y,{key:"review"},B.createElement(Y,{dimColor:!0}," | "),B.createElement(Y,{color:e?Ln.CYAN:Ln.GRAY},e?be.bullet:be.circle),B.createElement(Y,{color:e?Ln.CYAN:void 0,bold:e}," ","Review")))}return B.createElement(K,null,o)},"TabIndicator"),cT=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,s]=W(0),[o,i]=W(new Map),a=Q(new Map),[l,u]=W(""),[d,m]=W(new Set),[p,g]=W(null),[h,f]=W(!1),[y,w]=W(!1),[S,b]=W(!1),[E,C]=W(null),[v,T]=W(!1),k=e[r],_=k?.multiSelect??!1,P=o.get(r),A=k?[...k.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],x=A.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),I=new Map(x.map((e,t)=>[e.label,A[t]])),N=__name(e=>{"submit"===e.value?D():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),R=__name(()=>{if(!P||0===P.length)return 0;const e=P[0],t=k.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),$=__name(e=>{if(!h)if(_){const t=aT(e.value,k.options.length-1);if(null===t)return;const n=k.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=aT(e.value,k.options.length-1);if(null===t)return;f(!0);const n=k.options[t]?.label||"";O([n])}},"handleSelect"),L=__name(()=>{if(h)return;f(!0);const e=Array.from(d);O(e)},"handleMultiSelectDone"),M=__name(()=>{if(!h&&l.trim())if(_){const e=new Set(k.options.map(e=>e.label));m(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(l.trim()),n})}else f(!0),O([l.trim()])},"handleOtherSubmit"),O=__name(t=>{a.current.set(r,t);const o=new Map(a.current);i(o);const l=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);u(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;l(e),s(e),f(!1),b(!1),C(null),T(!1)}else if(e.every((e,t)=>o.has(t))){if(n&&1===e.length)return void D();m(new Set),u(""),w(!0),f(!1)}else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(l(t),s(t)),f(!1),b(!1),C(null),T(!1)}},"finishQuestion"),D=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),q=__name(t=>{w(!1),s(t),T(!1),b(!1),C(null);const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}},"editQuestion"),F=__name(t=>{if(t<0||t>=e.length)return;_&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),f(!1),b(!1),C(null),T(!1);const n=e[t],o=a.current.get(t);if(n?.multiSelect&&o){m(new Set(o));const e=o.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==o?.length)u("");else{const e=o[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}s(t)},"navigateToQuestion"),j=__name(()=>{if(!p||!_)return;if("done"===p.value)return;const e=aT(p.value,k.options.length-1);if(null===e)return;const t=k.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return Z((t,s)=>{if(" "===t&&_&&!S&&j(),"d"!==t||!_||S||y||L(),!y&&!h){if(s.downArrow&&!S&&!v&&!n&&p&&x.length>0&&p.value===x[x.length-1]?.value&&b(!0),s.upArrow&&!S&&!v&&p&&x.length>0&&p.value===x[0]?.value&&(_?T(!0):n||(b(!0),C(x.length-1))),s.upArrow&&S){b(!1),C(x.length-1);const e=x[x.length-1];e&&g(e)}if(s.downArrow&&S)if(b(!1),_)T(!0);else{C(0);const e=x[0];e&&g(e)}if(s.upArrow&&v&&(T(!1),b(!0)),s.downArrow&&v){T(!1),C(0);const e=x[0];e&&g(e)}s.return&&v&&_&&L()}if(h||S||v||(y?s.leftArrow&&q(e.length-1):s.leftArrow&&r>0?F(r-1):s.rightArrow&&(r<e.length-1?F(r+1):(_&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),w(!0)))),s.escape&&!h)if(y)w(!1);else if(S){b(!1);const e=E??x.length-1;C(e);const t=x[e];t&&g(t)}else if(v){T(!1);const e=x[x.length-1];e&&g(e)}}),k||y?y?B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(lT,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>B.createElement(K,{key:t,marginBottom:1,flexDirection:"column"},B.createElement(Y,{dimColor:!0},t+1,". ",e.question),B.createElement(Y,{color:Ln.GREEN}," ",o.get(t)?.join(", ")||"No answer"))),B.createElement(Ke,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:N,initialIndex:0,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.CYAN},e?be.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(Y,{color:t?Ln.CYAN:Ln.WHITE},e)}),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},be.arrowLeft," to go back and edit"))):B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(lT,{questions:e,currentIndex:r,answeredQuestions:new Set(o.keys()),isReviewPage:!1,hideReview:n})),B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0},k.question)),S||v?B.createElement(K,{flexDirection:"column"},x.map((e,t)=>{const n=I.get(e.label),r=_&&n&&d.has(n.label),s=!_&&n&&P?.includes(n.label),o=r||s;return B.createElement(K,{key:t,flexDirection:"column"},B.createElement(K,null,B.createElement(Y,null," "),B.createElement(Y,{color:o?Ln.GREEN:Ln.WHITE}," ",t+1,"."," "),_&&(o?B.createElement(Y,{color:Ln.GREEN},"[",be.tick,"]"," "):B.createElement(Y,{dimColor:!0},"[ ] ")),B.createElement(Y,{color:o?Ln.GREEN:Ln.WHITE},n?.label||""),!_&&o&&B.createElement(Y,{color:Ln.GREEN}," ",be.tick)),n?.description&&B.createElement(K,null,B.createElement(Y,null," "),B.createElement(Y,{dimColor:!0},_?" ":" ",n.description)))})):B.createElement(Ke,{key:`${r}-${E??"default"}`,items:x,initialIndex:E??R(),onSelect:$,onHighlight:g,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.CYAN},e?be.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=I.get(e),r=_&&n&&d.has(n.label),s=!_&&n&&P?.includes(n.label),o=r||s,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return B.createElement(K,{flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{color:t?Ln.CYAN:o?Ln.GREEN:Ln.WHITE}," ",a,"."," "),_&&(o?B.createElement(Y,{color:Ln.GREEN},"[",be.tick,"]"," "):B.createElement(Y,{dimColor:!0},"[ ] ")),B.createElement(Y,{color:t?Ln.CYAN:o?Ln.GREEN:Ln.WHITE},l),!_&&o&&B.createElement(Y,{color:Ln.GREEN}," ",be.tick)),n?.description&&B.createElement(Y,{dimColor:!0},_?" ":" ",n.description))}}),!n&&B.createElement(K,null,B.createElement(Y,{color:Ln.CYAN},S?be.pointer:" "),B.createElement(Y,{color:S?Ln.CYAN:void 0}," ",x.length+1,"."," "),_&&(d.has(l.trim())?B.createElement(Y,{color:Ln.GREEN},"[",be.tick,"] "):B.createElement(Y,{dimColor:!0},"[ ] ")),B.createElement(TextInput,{value:l,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=l.trim();u(t),_&&m(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:M,placeholder:"Type something...",focus:S,stripBracketedPaste:!0})),_&&B.createElement(K,null,B.createElement(Y,{color:Ln.CYAN},v?be.pointer:" "),B.createElement(Y,{color:v?Ln.CYAN:void 0,bold:v}," ",r===e.length-1?"Submit":"Next")),e.length>1&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function QuestionView({pendingQuestion:e,setPermissionMode:t,setPendingQuestion:n,setStatus:r,setStaticKey:s}){return B.createElement(K,{marginY:1},B.createElement(cT,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,onResponse:o=>{if(e.params.exitPlanMode){const e=o.answers[0]?.selectedOptions[0]||"";e.startsWith("Yes, auto-accept")?(t("auto-accept"),kC(),s(e=>e+1)):e.startsWith("Yes, exit")&&(t("standard"),kC(),s(e=>e+1))}if(e.params.enterPlanMode){const e=o.answers[0]?.selectedOptions[0];e?.startsWith("Yes")&&(t("plan"),kC(),s(e=>e+1))}e.resolve(o),n(null),r("Answers submitted")}}))}PC(),__name(QuestionView,"QuestionView"),Nt(),Nt(),Ot(),rr(),Nt(),Jo(),en(),ar(),rr(),Nt(),rr();var uT=class extends Xe{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)}hr(){return"\n"+Be.dim("───")+"\n"}blockquote(e){return"object"==typeof e&&(e=this.parser.parse(e.tokens)),this.o.blockquote(e.trim()).split("\n").map(e=>`│ ${e}`).join("\n")+"\n\n"}listDepth=0;list(e,t=!1,n=""){let r;this.listDepth++;try{r=super.list(e,t,n),r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),1===this.listDepth&&(r=r.replace(/^ /gm,""))}finally{this.listDepth--}return r}},dT=new Je;dT.setOptions({renderer:new uT({strong:Be.bold,em:Be.italic,del:Be.dim.strikethrough,codespan:Be.hex(Yn.CODE),code:Be.hex(Yn.CODE),heading:Be.bold,firstHeading:Be.bold.hex(Yn.HEADING).underline,link:Be.hex(Ln.CYAN),href:Be.hex(Ln.CYAN).underline,blockquote:Be.hex(Ln.GRAY).italic,table:Be.reset,tableOptions:{style:{head:[Ln.CYAN],border:[Ln.GRAY]}},hr:Be.reset,paragraph:Be.reset,html:Be.hex(Ln.GRAY),showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var mT=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const s=H(()=>{if(!e)return"";const t=[],n=e.replace(mT,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=dT.parse(n);if("string"!=typeof r)return e;return r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").replace(/^(\s*)\* /gm,"$1- ").replace(/\n{3,}/g,"\n\n").trim()}catch{return e}},[e]);return B.createElement(Y,{color:t,dimColor:n,wrap:r},s)}__name(Markdown,"Markdown"),jr();var pT=" │ ";function computeSimilarity({strA:e,strB:t}){const n=e.trim(),r=t.trim();if(n===r)return 1;if(!n||!r)return 0;const s=Object.create(null);for(let e=0;e<n.length;e++){const t=n[e];s[t]=(s[t]??0)+1}let o=0;for(let e=0;e<r.length;e++){const t=r[e],n=s[t];n&&(o++,s[t]=n-1)}return 2*o/(n.length+r.length)}function buildSimilarityMatrix(e,t,n){const r=new Float64Array(e.length*n);for(let s=0;s<e.length;s++)for(let o=0;o<n;o++)r[s*n+o]=computeSimilarity({strA:e[s],strB:t[o]});return r}function collectSimilarityCandidates(e,t,n){const r=[];for(let s=0;s<t;s++)for(let t=0;t<n;t++){const o=e[s*n+t];o>=.3&&r.push({score:o,removedIdx:s,addedIdx:t})}return r}function buildLinePairs(e,t){const n=e.length,r=t.length,s=new Map;if(n*r>200){const e=Math.min(n,r);for(let t=0;t<e;t++)s.set(t,t);return s}const o=collectSimilarityCandidates(buildSimilarityMatrix(e,t,r),n,r);o.sort((e,t)=>t.score-e.score);const i=new Set,a=new Set;for(const{removedIdx:e,addedIdx:t}of o)i.has(e)||a.has(t)||(s.set(e,t),i.add(e),a.add(t));return s}function groupAdjacentChanges(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(!r.added&&!r.removed){const e=r.value.split("\n");""===e.at(-1)&&e.pop(),t.push({type:"context",contextLines:e,removedLines:[],addedLines:[]}),n++;continue}const s=[],o=[];for(;n<e.length&&(e[n].added||e[n].removed);){const t=e[n].value.split("\n");""===t.at(-1)&&t.pop(),e[n].removed?(s.push(...t),n++):(o.push(...t),n++)}t.push({type:"change",contextLines:[],removedLines:s,addedLines:o})}return t}function renderWordSegments({wordChanges:e,type:t,dimDiff:n}){const r="removed"===t?Fn.REMOVED_HIGHLIGHT_BG:Fn.ADDED_HIGHLIGHT_BG,s=[];let o=0;for(const i of e){if("removed"===t&&i.added)continue;if("added"===t&&i.removed)continue;const e="removed"===t?i.removed:i.added,a=i.value.replace(/\s/g," "),l=`${t}-${o++}-${e?"highlighted":"unchanged"}`;e?s.push(B.createElement(Y,{key:l,backgroundColor:r,dimColor:n},a)):s.push(B.createElement(Y,{key:l,color:Ln.WHITE,dimColor:n},a))}return s}function renderContextLine({line:e,lineNum:t,lineNumWidth:n,dimDiff:r,nodeKey:s}){return B.createElement(K,{key:s,width:"100%"},B.createElement(Y,{color:Fn.LINE_NUM,dimColor:r}," "+t.toString().padStart(n)),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:r},pT),B.createElement(Y,{color:Ln.WHITE,dimColor:r}," ",e.replace(/\s/g," ")))}function renderContextGroup({lines:e,leadCount:t,trailCount:n,lineNumWidth:r,dimDiff:s,counters:o}){const i=[];if(t+n>=e.length){for(const t of e)i.push(renderContextLine({line:t,lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;return i}for(let n=0;n<t;n++)i.push(renderContextLine({line:e[n],lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;const a=e.length-t-n;a>0&&(o.oldLineNum+=a,o.newLineNum+=a,i.push(B.createElement(K,{key:"sep-"+o.nodeKey++},B.createElement(Y,{color:Fn.LINE_NUM,dimColor:s}," ".repeat(r+1)),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:s},pT),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:s},`⋮ ${a} line${1===a?"":"s"}`))));for(let t=e.length-n;t<e.length;t++)i.push(renderContextLine({line:e[t],lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;return i}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:s=!1,marginLeft:o=2,startLine:i=1,dimDiff:a=!1,maxLines:l}){const u=Ye.diffLines(e,t);let d=0,m=0;for(const e of u)e.added&&(d+=e.count||1),e.removed&&(m+=e.count||1);const p=u.reduce((e,t)=>e+(t.added?0:t.count||1),0),g=u.reduce((e,t)=>e+(t.removed?0:t.count||1),0),h=Math.max(3,(i+p-1).toString().length,(i+g-1).toString().length),f=groupAdjacentChanges(u),y=[],w={oldLineNum:i,newLineNum:i,nodeKey:0};for(let e=0;e<f.length;e++){const t=f[e];if("context"===t.type){const n=t.contextLines,r=e>0&&"change"===f[e-1].type,s=e<f.length-1&&"change"===f[e+1].type;if(!r&&!s){w.oldLineNum+=n.length,w.newLineNum+=n.length;continue}const o=r?Math.min(3,n.length):0,i=s?Math.min(3,Math.max(0,n.length-o)):0;y.push(...renderContextGroup({lines:n,leadCount:o,trailCount:i,lineNumWidth:h,dimDiff:a,counters:w}));continue}const{removedLines:n,addedLines:r}=t,s=buildLinePairs(n,r),o=new Map,i=new Map;for(const[e,t]of s){const s=Ye.diffWordsWithSpace(n[e],r[t]);o.set(e,s),i.set(t,s)}for(let e=0;e<n.length;e++){const t=o.get(e);y.push(B.createElement(K,{key:"rm-"+w.nodeKey++,width:"100%",backgroundColor:Fn.REMOVED_BG},B.createElement(Y,{color:Fn.REMOVED_TEXT,dimColor:a}," "+w.oldLineNum.toString().padStart(h)),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:a},pT),B.createElement(Y,{color:Fn.REMOVED_TEXT,dimColor:a},"- "),t?renderWordSegments({wordChanges:t,type:"removed",dimDiff:a}):B.createElement(Y,{color:Fn.REMOVED_TEXT,dimColor:a},n[e].replace(/\s/g," ")))),w.oldLineNum++}for(let e=0;e<r.length;e++){const t=i.get(e);y.push(B.createElement(K,{key:"add-"+w.nodeKey++,width:"100%",backgroundColor:Fn.ADDED_BG},B.createElement(Y,{color:Fn.ADDED_TEXT,dimColor:a}," "+w.newLineNum.toString().padStart(h)),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:a},pT),B.createElement(Y,{color:Fn.ADDED_TEXT,dimColor:a},"+ "),t?renderWordSegments({wordChanges:t,type:"added",dimDiff:a}):B.createElement(Y,{color:Fn.ADDED_TEXT,dimColor:a},r[e].replace(/\s/g," ")))),w.newLineNum++}}const S=void 0!==l&&y.length>l,b=S?y.slice(0,l):y;return{diffContent:B.createElement(K,{flexDirection:"column"},s&&!r&&B.createElement(Y,{color:Ln.GRAY},"Updated"," ",B.createElement(Y,{color:Ln.WHITE,bold:!0},n)," ","with ",B.createElement(Y,{color:Bn.SUCCESS},d)," ","addition",1!==d?"s":""," and"," ",B.createElement(Y,{color:Bn.ERROR},m)," removal",1!==m?"s":""),r&&B.createElement(Y,{color:Ln.RED},"Rejected update to",B.createElement(Y,{color:Ln.RED},` ${n}`)),B.createElement(K,{flexDirection:"column",marginLeft:o,marginRight:o+4,width:(process.stdout.columns||80)-2*o-8},b)),isTruncated:S,totalLines:y.length}}function formatTodosForDisplay(e){const t=Vo(e);return t?B.createElement(K,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?be.checkboxOn:be.checkboxOff;let r,s=!1;switch(e.status){case"completed":r=Bn.SUCCESS,s=!0;break;case"in_progress":r=Bn.IN_PROGRESS;break;default:r=Ln.WHITE}return B.createElement(K,{key:e.id||t,flexDirection:"row"},B.createElement(K,{width:2},B.createElement(Y,{color:r},n)),B.createElement(Y,{color:r,bold:"in_progress"===e.status,strikethrough:s},e.content))})):B.createElement(Y,null,e)}function computeDisplayInput({input:e,isAgent:t,isShell:n,expandedOutput:r}){if(!e)return e;if(t){const t=e.split(/[.\n]/)[0];return t?t+(e.includes(".")||e.includes("\n")?".":""):e}return n&&!r?truncateCommand({command:e}):e}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:s}){if(e)return{symbolColor:Ln.YELLOW,symbol:be.arrowRight};if(t)return{symbolColor:Ln.RED,symbol:be.nodejs};if(n)return{symbolColor:Dn,symbol:"✻"};if(r&&s){const e=Vo(s),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?Bn.SUCCESS:Bn.WARNING,symbol:be.nodejs}}return{symbolColor:Bn.SUCCESS,symbol:be.nodejs}}function renderToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,output:s,expandedOutput:o,expandKey:i}){if(e){const e=s?Math.max(1,Math.round(s.length/500)):1;return B.createElement(B.Fragment,null,B.createElement(Y,{color:Dn},`Thought for ${e} second${1!==e?"s":""}`," "),!o&&B.createElement(Y,{dimColor:!0},"(",`${i}+o to expand`,")"))}return t?B.createElement(B.Fragment,null,B.createElement(K,{flexShrink:0},B.createElement(Y,{backgroundColor:On.BADGE_BG,color:On.BADGE_FG,bold:!0},`${cv}Taste${cv}`)),B.createElement(Y,null," ","Using your taste"," ",n?"package of ":"packages",n&&B.createElement(Y,{bold:!0},n))):B.createElement(K,{flexShrink:0},B.createElement(Y,{backgroundColor:jn.BG,color:jn.FG,bold:!0},`${cv}${r}${cv}`))}function renderAgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:s}){const o=`${formatTime2(r)} | ${formatTokens(s)}`;return"running"===e?B.createElement(Y,{color:Ln.GRAY},"Running (",o,")"):"interrupted"===e||"Interrupted by user"===n?B.createElement(Y,{color:Ln.RED,wrap:"wrap"},"Interrupted by user"):"error"===e||t?B.createElement(Y,{color:Ln.RED,wrap:"wrap"},n," (",o,")"):B.createElement(B.Fragment,null,B.createElement(Y,{wrap:"wrap"},"Done"),B.createElement(Y,{color:Ln.GRAY}," (",o,")"))}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,hasError:r,expandKey:s}){if(n||r)return e;const o=dedentText(e),{text:i,isTruncated:a,remainingLines:l}=truncateToVisualLines({output:o,maxVisualLines:"Question"===t?_r:kr,maxChars:"Question"===t?1/0:Ir});if(!a||"Question"===t)return i;const u=l>0?`... +${l} lines (${s}+o to expand)`:`... (${s}+o to expand)`;return B.createElement(B.Fragment,null,i,B.createElement(Y,{dimColor:!0},"\n",u))}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:s,expandKey:o}){const i=n?void 0:Pr,{diffContent:a,isTruncated:l,totalLines:u}=generateDiff({filePath:e,showMetadata:!0,oldValue:t.oldValue,newValue:t.newValue,startLine:"number"==typeof t.startLine?t.startLine:1,dimDiff:r,permissionDenied:r,maxLines:i});return B.createElement(K,{flexDirection:"column"},a,l&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"… (",u-Pr," more lines) (",`${o}+o to expand`,")")),r&&s&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.RED,wrap:"wrap"},s)))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,metadata:r,output:s,expandedOutput:o,isPermissionDenied:i,input:a,hasError:l,name:u,expandKey:d}){return e?formatTodosForDisplay(s):t?o?B.createElement(K,{width:"100%",flexDirection:"column"},B.createElement(Y,null," "),B.createElement(Y,{color:Dn,wrap:"wrap",italic:!0},s)):null:n&&r?.oldValue&&r?.newValue?renderEditFileDiff({input:a,metadata:r,expandedOutput:o,isPermissionDenied:i,output:s,expandKey:d}):B.createElement(K,{width:"100%"},B.createElement(Y,{color:l?Ln.RED:"",wrap:"wrap"},renderTruncatedOutput({output:s,name:u,expandedOutput:o,hasError:l,expandKey:d})))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:s=!1,metadata:o,expandedOutput:i=!1}){const a="thinking…"===e,l="TODOS"===e,u="Edit"===e,d=!0===o?.isTasteFile,m=o?.tasteCategory,p=!0===o?.permissionDenied,g=!a&&!l&&!d,{name:h}=detectTerminal(),f="iTerm2"===h?"shift":"ctrl",y=!0===o?.isAgent,w=computeDisplayInput({input:t,isAgent:y,isShell:"Shell"===e,expandedOutput:i}),S=!a&&w&&!d,b=o?.status,E=o?.tokensUsed||0,C="number"==typeof o?.elapsedSeconds?Math.floor(o.elapsedSeconds):0,{symbolColor:v,symbol:T}=resolveSymbol({isPending:r,hasError:s,isThinking:a,isTodos:l,output:n});return B.createElement(K,null,a&&B.createElement(Y,{color:v},T),B.createElement(K,{flexDirection:"column",marginLeft:a?1:0},B.createElement(K,null,renderToolHeader({isThinking:a,isTasteFile:d,tasteCategory:m,name:e,output:n,expandedOutput:i,expandKey:f}),S&&B.createElement(Y,null," ",B.createElement(Markdown,null,`(${w})`))),y&&("running"===b||n)&&B.createElement(K,{columnGap:1,marginLeft:g?1:0},g&&B.createElement(Y,null,"⎿"," "),renderAgentStatus({agentStatus:b,hasError:s,output:n,elapsedSeconds:C,tokensUsed:E})),n&&!d&&!y&&B.createElement(K,{columnGap:1,marginLeft:g?1:0},g&&B.createElement(Y,null,"⎿"," "),renderOutputContent({isTodos:l,isThinking:a,isEditFile:u,metadata:o,output:n,expandedOutput:i,isPermissionDenied:p,input:t,hasError:s,name:e,expandKey:f})),r&&!y&&B.createElement(K,{columnGap:1,marginLeft:1},B.createElement(Y,null,"⎿"," "),B.createElement(Y,{color:Ln.GRAY},"Processing…"))))}__name(computeSimilarity,"computeSimilarity"),__name(buildSimilarityMatrix,"buildSimilarityMatrix"),__name(collectSimilarityCandidates,"collectSimilarityCandidates"),__name(buildLinePairs,"buildLinePairs"),__name(groupAdjacentChanges,"groupAdjacentChanges"),__name(renderWordSegments,"renderWordSegments"),__name(renderContextLine,"renderContextLine"),__name(renderContextGroup,"renderContextGroup"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(computeDisplayInput,"computeDisplayInput"),__name(resolveSymbol,"resolveSymbol"),__name(renderToolHeader,"renderToolHeader"),__name(renderAgentStatus,"renderAgentStatus"),__name(renderTruncatedOutput,"renderTruncatedOutput"),__name(renderEditFileDiff,"renderEditFileDiff"),__name(renderOutputContent,"renderOutputContent"),__name(ToolMessage,"ToolMessage"),Zo();var gT=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[s]=W(0),[o,i]=W(1);G(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&i(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=[{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}],l=__name(e=>{const t=a.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),u=__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"),d=__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"),m=__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 B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.GRAY,paddingX:1,width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,color:Ln.YELLOW},`${m()} ${"edit"===e.action?d():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&B.createElement(K,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:d(),marginLeft:0,startLine:o}).diffContent),B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0},"Do you want to ",u()," ",B.createElement(Y,{color:Ln.CYAN},d()),"?")),B.createElement(Ke,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:s,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.CYAN},e?be.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(Y,{color:t?Ln.CYAN:Ln.WHITE},e.includes("(shift+tab)")?B.createElement(B.Fragment,null,e.split("(shift+tab)")[0],B.createElement(Y,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?B.createElement(B.Fragment,null,e.split("(")[0],B.createElement(Y,{color:Ln.GRAY},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Nt(),Ot(),rr();var hT=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=W(0),s=[{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}],o=__name(e=>{const r=s.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),i=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"";return t?`${e.command} ${t}`:e.command},"getCommandDisplay");return B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.GRAY,paddingX:1,width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,color:Ln.YELLOW},"Execute Shell Command")),B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",B.createElement(Y,{color:Ln.CYAN},i()),".")),e.workingDirectory&&B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.GRAY},"Working directory: ",e.workingDirectory)),e.description&&B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0,italic:!0},e.description)),B.createElement(Ke,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:r,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.CYAN},e?be.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(Y,{color:t?Ln.CYAN:Ln.WHITE},e.includes("(shift+tab)")?B.createElement(B.Fragment,null,e.split("(shift+tab)")[0],B.createElement(Y,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt");function getKillShellRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}function getFileAction2(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:s,permissionMode:o,showHintMessage:i,allowedStatus:a,deniedStatus:l}){r(e);const u="no"!==e.value;t(u),n(null),u?(s(a),"standard"===o&&i("Use shift+tab to enable auto-accept")):s(l)}__name(getKillShellRequest,"getKillShellRequest"),__name(getFileAction2,"getFileAction"),__name(handlePermissionResponse,"handlePermissionResponse");var fT=U(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:s,showHintMessage:o,handleToggleAutoAccept:i}){const a={resolve:e.resolve,setPendingPermission:n,respondToPrompt:s,setStatus:r,permissionMode:t,showHintMessage:o};if("shell_command"===e.toolName){const t=e.params;return B.createElement(K,{marginY:1},B.createElement(hT,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"}),onToggleAutoAccept:i}))}if("kill_shell"===e.toolName){const t=getKillShellRequest(e.params);return B.createElement(K,{marginY:1},B.createElement(hT,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"}),onToggleAutoAccept:i}))}const l=e.params,u={action:getFileAction2(e.toolName),filePath:String(l.filePath??l.file_path??l.path??l.absolutePath??l.notebook_path??"unknown"),description:`Allow ${e.toolName} operation`,oldContent:"edit_file"===e.toolName&&"string"==typeof l.oldContent?l.oldContent:void 0,newContent:"edit_file"===e.toolName&&"string"==typeof l.newContent?l.newContent:void 0};return B.createElement(K,{marginY:1},B.createElement(gT,{request:u,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onToggleAutoAccept:i}))},"PermissionView"));Nt(),PC(),Nt(),tC(),Nt(),rr();var yT=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:s=0,titleColor:o=Ln.GRAY,dividerChar:i="─",dividerColor:a=Ln.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*s),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",p=r?` ${r}`:"",g=d.length+m.length+p.length,h=i.repeat(Math.max(0,u-g));return B.createElement(K,{paddingLeft:s,paddingRight:s,marginBottom:1,...l},(t||n)&&B.createElement(Y,{color:a},d),e&&B.createElement(Y,{color:o},m),B.createElement(Y,{color:a},h),r&&B.createElement(Y,{dimColor:!0},p))},"Divider");PC(),rr(),Nt(),rr();var wT=[{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}],ST=__name(({onComplete:e,onExit:t})=>{const[n,r]=W(0),[s,o]=W(!1),i=n>=wT.length;return G(()=>{if(n>=wT.length)return;if(s)return;const e=wT[n],t=setTimeout(()=>{r(e=>Math.min(e+1,wT.length))},e.duration);return()=>clearTimeout(t)},[n,s]),Z((n,s)=>{""===n||s.ctrl&&"c"===n?t?t():e():s.escape?e():i?(s.return||" "===n)&&e():" "===n?o(e=>!e):s.return&&r(e=>Math.min(e+1,wT.length))}),B.createElement(K,{flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{bold:!0},"Meet Your Coding Taste")),B.createElement(K,null,B.createElement(Y,{dimColor:!0},"Command Code learns your coding style as you work.")),B.createElement(K,null,B.createElement(Y,{dimColor:!0},"Here's how your preferences evolve in real-time:")),B.createElement(K,{flexDirection:"column",marginY:1},wT.slice(0,n).map((e,t)=>"user"===e.type?B.createElement(K,{key:t},B.createElement(Y,null,be.pointer," ",e.text)):B.createElement(K,{key:t,marginBottom:1,marginTop:0,marginLeft:1},B.createElement(K,null,B.createElement(Y,{dimColor:!0},"⎿"),B.createElement(K,{flexDirection:"column",marginLeft:2,marginTop:0},B.createElement(Y,{color:On.TEXT},e.text),e.details&&B.createElement(Y,{dimColor:!0},"Saved(",e.details,")")))))),i?B.createElement(K,{flexDirection:"column",marginY:1},B.createElement(Y,{bold:!0,color:On.TEXT},"Demo Complete!"),B.createElement(Y,null,"Command Code will now use these preferences to generate"),B.createElement(Y,null,"better suggestions tailored to your coding style. The"),B.createElement(Y,null,"more you code, the smarter it gets."),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press Enter to get started →"))):B.createElement(K,null,B.createElement(Y,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(s?" (paused)":""))))},"TasteDemoComponent"),bT=__name(({onClose:e,onExit:t})=>{const[n,r]=W(ZE.getEvents()),[s,o]=W(0);Z((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),G(()=>{const e=__name(()=>{r(ZE.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return ZE.on("new-event",e),ZE.on("cleared",t),()=>{ZE.off("new-event",e),ZE.off("cleared",t)}},[]),G(()=>{const e=__name(()=>{kC(),o(e=>e+1)},"handleResize");return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e)}},[]);const i=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),a=__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 s=n,o=null;if(r){s=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);o=`confidence: ${parseFloat(e).toString()}%`}const i={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:i,content:s,confidence:o}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),l=__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),s=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:s,diff:s-r}},"parsePercentageChange"),u=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),s=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:s,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails"),d=H(()=>(process.stdout.rows??24)-1,[s]);return B.createElement(K,{flexDirection:"column",width:"100%",height:d,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Ze,{name:"vice"},B.createElement(Y,null,BC()))),B.createElement(yT,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),B.createElement(K,{flexDirection:"column"},0===n.length?B.createElement(K,{flexDirection:"column"},B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,null,"Start using Command Code and it will begin recording your coding taste."),B.createElement(Y,{dimColor:!0},"Your preferences, patterns, and style will appear here in real-time.")),B.createElement(ne,{count:2}),B.createElement(yT,{title:"DEMO",titleColor:"white",subPrefix:!0}),B.createElement(ST,{onComplete:()=>{e()},onExit:t})):B.createElement(K,{flexDirection:"column"},n.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:s}=a(e.message),o="moved"===t?u(e.details):null,i="upgraded"===t||"downgraded"===t?l(r):null;return B.createElement(K,{key:e.id,marginBottom:1},B.createElement(K,{flexDirection:"column"},B.createElement(K,null,B.createElement(K,{flexShrink:0},B.createElement(Y,{backgroundColor:On.BADGE_BG,color:On.BADGE_FG,bold:!0},`${cv}${n}${cv}`)),o?B.createElement(Y,{dimColor:!0}," ","(",o.fullPath,")"):e.details?B.createElement(Y,{dimColor:!0}," ","(",e.details,")"):null),B.createElement(K,{marginLeft:1},B.createElement(Y,{dimColor:!0},"⎿"," "),o?B.createElement(B.Fragment,null,B.createElement(Y,null," ",o.category," ","package ("),B.createElement(Y,{dimColor:!0},o.oldPath),B.createElement(Y,null," ",be.arrowRight," ",o.newPath),B.createElement(Y,null,")")):i?B.createElement(B.Fragment,null,B.createElement(Y,null," ",i.text," ","("),B.createElement(Y,{dimColor:!0},"confidence:"," "),B.createElement(Y,{dimColor:!0},i.oldPercent,"%"),B.createElement(Y,null," ",be.arrowRight," "),B.createElement(Y,{color:i.diff>0?Ln.GREEN:Ln.RED},i.newPercent,"%"),B.createElement(Y,null,")")):B.createElement(B.Fragment,null,B.createElement(Y,null," ",r),s&&B.createElement(Y,{dimColor:!0}," ","(",s,")")))))}return B.createElement(K,{key:e.id,marginBottom:1},B.createElement(Y,{dimColor:!0},be.pointerSmall," ",e.message))}))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return B.createElement(bT,{onClose:()=>{kC(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Nt(),Nt(),rr(),PC(),nr();var ET=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,s]=W(!1),[o,i]=W(!0);G(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();s(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),Z((t,n)=>{if(!n.return&&" "!==t)return n.escape?(kC(),void e()):void 0;a()});const a=__name(async()=>{const e=!r;s(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){s(!e)}},"toggleTasteLearning");return o?B.createElement(K,{key:n,borderStyle:"single",borderColor:Ln.BLUE,padding:1,flexDirection:"column"},B.createElement(Y,{color:Ln.BLUE,bold:!0},"Taste Settings"),B.createElement(Y,{dimColor:!0},"Loading configuration...")):B.createElement(K,{key:n,borderStyle:"single",borderColor:Ln.GRAY,padding:1,flexDirection:"column"},B.createElement(Y,{bold:!0},"Taste Learning"),B.createElement(Y,{dimColor:!0},"Configure taste learning preferences for this project"),B.createElement(K,{marginTop:1}),B.createElement(K,{justifyContent:"space-between"},B.createElement(Y,null,"Taste learning",B.createElement(Y,{dimColor:!0}," - Learn from your interactions")),B.createElement(Y,{color:r?Ln.GREEN:Ln.GRAY},r?"enabled":"disabled")),B.createElement(K,{marginTop:1}),B.createElement(Y,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),B.createElement(Y,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return B.createElement(B.Fragment,null,B.createElement(nT,{staticKey:e}),B.createElement(K,{flexDirection:"column",width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"Press Esc to return to conversation")),B.createElement(ET,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}__name(TasteConfigView,"TasteConfigView"),Nt(),Nt(),gi(),PC(),Ot(),rr();var CT=__name(e=>Math.ceil(e.length/4),"estimateTokens"),vT=__name(({onClose:e})=>{const[t,n]=W([]),[r,s]=W(!0),[o,i]=W(null),[a,l]=W(0);G(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),r=[...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}))];n(r)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=t.filter(e=>"project"===e.location),d=t.filter(e=>"user"===e.location),m=[...u,...d],p=__name(async t=>{try{await et([{file:t.filePath,line:1}]),kC(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(g()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");Z((t,n)=>{if(n.escape)return kC(),void e();if(n.upArrow)l(e=>Math.max(0,e-1));else if(n.downArrow)l(e=>Math.min(m.length-1,e+1));else if(n.return){const e=m[a];e&&p(e)}});const g=__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 r?B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(Y,{color:Mn,bold:!0},"Agent Skills"),B.createElement(Y,{dimColor:!0},"Loading skills...")):o?B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(Y,{color:Ln.RED,bold:!0},"Agent Skills"),B.createElement(Y,{dimColor:!0},o),B.createElement(K,{marginTop:1}),B.createElement(Y,{dimColor:!0},"Press ",B.createElement(Y,{bold:!0},"Esc")," to close")):0===t.length?B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(Y,{color:Mn,bold:!0},"Agent Skills"),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"No skills found")),B.createElement(Y,{dimColor:!0},"Create skills in:"),B.createElement(Y,{dimColor:!0}," ~/",".commandcode","/","skills","/ (user)"),B.createElement(Y,{dimColor:!0}," ",".commandcode","/","skills","/ (project)"),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press ",B.createElement(Y,{bold:!0},"Esc")," to close"))):B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,null,B.createElement(Y,{color:Mn,bold:!0},"Skills "),B.createElement(Y,{dimColor:!0},m.length," skills")),u.length>0&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(K,null,B.createElement(Y,{color:Wn,bold:!0},"Project skills "),B.createElement(Y,{color:Wn},"(",".commandcode","/","skills",")")),u.map((e,t)=>{const n=a===t;return B.createElement(K,{key:e.value},B.createElement(Y,{color:n?Ln.GREEN:Ln.WHITE},e.label),B.createElement(Y,{dimColor:!0}," · ~",CT(e.description)," description tokens"))})),d.length>0&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(K,null,B.createElement(Y,{color:Wn,bold:!0},"User skills "),B.createElement(Y,{color:Wn},"(~/",".commandcode","/","skills",")")),d.map((e,t)=>{const n=a===u.length+t;return B.createElement(K,{key:e.value},B.createElement(Y,{color:n?Ln.GREEN:Ln.WHITE},e.label),B.createElement(Y,{dimColor:!0}," · ~",CT(e.description)," description tokens"))})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0,italic:!0},"Esc to close")))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t}){return B.createElement(B.Fragment,null,B.createElement(nT,{staticKey:e}),B.createElement(K,{flexDirection:"column",width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"Press Esc to return to conversation")),B.createElement(vT,{onClose:()=>t(!1),staticKey:e})))}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:s}=e;return s<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),s=e.replace(/\\/g,"/");if(s.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${s.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:s};const o=s.lastIndexOf("/");return-1===o?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:s.slice(0,o+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),s=n.startsWith(".")||r.includes("/.");return S.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!s||!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?"[Del] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}__name(SkillsConfigView,"SkillsConfigView"),Nt(),Nt(),rr(),vn(),zt(),Nt(),zt(),__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 TT=__name(({onClose:e})=>{const[t,n]=W(""),[r,s]=W(null),[o,i]=W([]),[a,l]=W(getAdditionalDirectories()),[u,d]=W({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,p]=W(0);G(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),p(0)},[t]),G(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{s(null)},5e3);return()=>clearTimeout(e)},[r]);const g=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(s({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):s({tone:"warning",text:t.message}):s({tone:"error",text:t.message})},"submitPath"),h=__name(e=>{if(!removeAdditionalDirectory(e))return s({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());s({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),l(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");Z((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&o[u.suggestionIndex]?void g(o[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])h(a[u.activeDirIndex]);else{if(r.tab&&o.length>0){const e=o[u.suggestionIndex]??o[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),s(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:o.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:o.length,activeDirCount:a.length}))}}}),G(()=>{"suggestions"===u.zone&&p(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:o.length}))},[u,o.length]),G(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=o.length?{...e,zone:"input",suggestionIndex:Math.max(0,o.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[o.length,a.length]);const f=o.slice(m,m+8),y=getFooterText({focusZone:u.zone});return B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.CYAN,paddingX:1,paddingY:0},B.createElement(Y,{bold:!0,color:Ln.CYAN},"Add directory to workspace"),B.createElement(Y,{color:Ln.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,{color:Ln.GRAY},"Added directories"),0===a.length?B.createElement(Y,{color:Ln.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return B.createElement(Y,{key:e,color:n?Ln.YELLOW:Ln.GREEN,bold:n},n?` ${be.pointer} `:" ",formatDirectoryForDisplay(e))})),B.createElement(K,{marginTop:1},B.createElement(Y,{bold:!0,color:Ln.WHITE},"Path")),B.createElement(K,null,B.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?be.pointer:" "} `,prefixColor:"input"===u.zone?Ln.CYAN:Ln.GRAY,onChange:e=>{n(e),s(null)},onSubmit:g})),!t&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:{error:Ln.RED,warning:Ln.YELLOW,success:Ln.GREEN}[r.tone]},r.text)),o.length>0&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Suggestions"),f.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return B.createElement(Y,{key:e,color:r?Ln.CYAN:Ln.GRAY,bold:r},r?` ${be.pointer} `:" ",e)})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},y)))},"AddDirModal");Nt(),Nt(),Ot(),Nt(),Nt(),Ot(),JE(),rr();var kT=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),_T=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),PT=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[s,o]=W("idle"),[i,a]=W(""),l=[...WE.map(e=>e.name),...QE.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void a("Agent configuration is incomplete");o("saving");try{const r="personal"===e.location?kT():_T();await L.mkdir(r,{recursive:!0});const s=`${e.agentType}.md`,o=t.join(r,s),i=Array.from(e.selectedTools).map(e=>VE[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(i),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await L.writeFile(o,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");Z((e,t)=>{r||!t.return||"idle"!==s&&"error"!==s||u()});const d=Array.from(e.selectedTools).map(e=>VE[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return B.createElement(K,{flexDirection:"column",gap:1},B.createElement(K,{flexDirection:"column"},B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Name:"),B.createElement(Y,{color:Ln.GRAY},e.agentType)),B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Location:"),B.createElement(Y,{color:Ln.GRAY},m)),B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Tools:"),B.createElement(Y,{color:Ln.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Description"),B.createElement(Y,{color:Ln.GRAY},"(Tells ","Command Code"," when to use this agent):")),B.createElement(Y,{color:Ln.GRAY},e.ccToolDefinition),B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"System Prompt:")),B.createElement(Y,{color:Ln.GRAY},e.sysPrompt),!r&&B.createElement(K,{marginTop:1},"idle"===s&&B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.GREEN,dimColor:!0},"Press"),B.createElement(Y,{color:Ln.GREEN,bold:!0},"Enter"),B.createElement(Y,{color:Ln.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===s&&B.createElement(Y,{color:Ln.YELLOW},"Saving agent..."),"saved"===s&&B.createElement(Y,{color:Ln.GREEN},be.tick," ",i),"error"===s&&B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.RED},be.cross," Error: ",i),B.createElement(Y,{color:Ln.GRAY},"Press Enter to retry"))))},"AgentSummary");JE(),rr();var AT=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[s,o]=W("menu"),i=[...WE.map(e=>e.name),...QE.map(e=>e.name)];let a=new Set;if("*"===e.tools||'"*"'===e.tools)a=new Set(i);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>KE[e]||e);a=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a},u=[{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?o("view"):"edit"===e.value?o("edit"):"delete"===e.value&&o("delete")},"handleMenuSelect");if(Z((e,n)=>{n.escape&&("menu"===s?t():o("menu")),n.return&&"view"===s&&o("menu")}),"view"===s)return B.createElement(K,{flexDirection:"column"},B.createElement(PT,{config:l,onSaveComplete:()=>o("menu"),viewOnly:!0}),B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Press Enter to go back")));if("edit"===s)return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.YELLOW},"Edit functionality coming soon..."),B.createElement(Y,{color:Ln.GRAY},"Press Esc to go back"));if("delete"===s){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],s=__name(async r=>{if("confirm-delete"===r.value)try{await L.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return B.createElement(K,{flexDirection:"column",gap:1},B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.RED},"Delete agent"),B.createElement(Y,{color:Ln.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),B.createElement(K,null,B.createElement(Ke,{items:r,onSelect:s,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},` ${t}`)})))}return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.WHITE,bold:!0},e.name),B.createElement(K,{marginTop:1},B.createElement(Ke,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},` ${t}`)})),B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");_l(),rr();var xT=__name(({handleSelect:e,createdAgentName:n})=>{const[r,s]=W([]),[o,i]=W([]),[a,l]=W([]),[u,d]=W(!0),[m,p]=W(!1),[g,h]=W(null),[y,w]=W(!1),S=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),b=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),E=__name(async(e,n)=>{try{p(!1);const r=(await L.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await L.readFile(s,"utf-8"),{data:i,content:a}=$e(o);let l=i.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:i.name||r.replace(".md",""),description:i.description||"",tools:l,sysPrompt:a.trim(),location:n,filePath:s}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");G(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([E(S(),"personal"),E(b(),"project")]),n=vl.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}`}));s(e),i(t),l(n),d(!1)},"loadAgents")()},[m]);const C=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{C.push({label:e.name,value:e.filePath})}),o.forEach(e=>{C.push({label:e.name,value:e.filePath})});const v=r.length+o.length,T=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...o].find(e=>e.filePath===t.value);e&&(h(e),w(!0))}},"handleAgentSelect");if(u)return B.createElement(Y,{color:Ln.GRAY},"Loading agents...");if(y&&g){const e=g.filePath.startsWith("__builtin__:");return B.createElement(AT,{agent:g,onBack:()=>{w(!1),h(null)},setRevalidateAgent:p,isReadOnly:e})}const k=__name(({isSelected:e,label:t})=>{const n=C.find(e=>e.label===t),s=n?.value||"",i=r[0]?.filePath===s,a=o[0]?.filePath===s;return B.createElement(K,{flexDirection:"column"},i&&r.length>0&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY,bold:!0},"User agents")),a&&o.length>0&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY,bold:!0},"Project agents")),B.createElement(K,null,B.createElement(Y,{color:Ln.WHITE},e?">":" "),B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY}," ",t)))},"CustomItemComponent");return B.createElement(K,{flexDirection:"column"},B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Agents"),v>0?B.createElement(Y,{color:Ln.GRAY}," ","(",v," agent",v>1?"s":"",")"):B.createElement(Y,{color:Ln.GRAY}," (No custom agents)")),n&&B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{color:Ln.GREEN,dimColor:!0},"Created agent: ",n)),B.createElement(Ke,{items:C,onSelect:T,indicatorComponent:()=>null,itemComponent:k}),a.length>0&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(Y,{color:Ln.GRAY,bold:!0},"Default agents"),a.map(e=>B.createElement(Y,{key:e.filePath,color:Ln.GRAY}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Create specialized subagents that Command Code can delegate to."),B.createElement(Y,{color:Ln.GRAY},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Nt(),Ot(),rr(),JE(),Nt(),Nt(),Ot(),rr();var IT=__name(({onSelect:e})=>B.createElement(Ke,{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})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},` ${t}`)}),"LocationSelector");Nt(),vn(),Ot(),JE(),_n(),Nn(),Pl(),rr();var NT=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:s,onSysPromptChange:o,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=W(!1),[p,g]=W(!1),h=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?o(e):t.cleanedContent&&o(t.cleanedContent))}o(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?o(e):t.cleanedContent&&o(t.cleanedContent))}},[d,o]),f=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||p){if(!p||t.isPasteEnd){if(p&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[p,i]);return"agentType"===e?B.createElement(B.Fragment,null,B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(VE).some(e=>Ne(e)===Ne(t))||Object.keys(VE).some(e=>Ne(e)===Ne(t)))&&B.createElement(Y,{color:Ln.RED},be.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Ne(t))&&B.createElement(Y,{color:Ln.RED},be.warning," This name is reserved. Reserved names:"," ",Cl.join(", "))),B.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Ne(t);Object.values(VE).some(t=>Ne(t)===e)||Object.keys(VE).some(t=>Ne(t)===e)||isReservedAgentName(e)||a()},onChange:s,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?B.createElement(B.Fragment,null,B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.WHITE},"Enter the system prompt for your agent:"),B.createElement(Y,{color:Ln.GRAY},"Be comprehensive for best results.")),B.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:h,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.WHITE},"When should ","Command Code"," use this agent?"),B.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:f,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Nt(),rr();var RT=__name(({onSelect:e})=>B.createElement(Ke,{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})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},` ${t}`)}),"MethodSelector");Nt(),vn(),Nt(),rr();var $T=["·","○","◇","☆","✧","☆","◇","○","⌘"],LT=[12,5,4,4,4,4,4,5,16],MT=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<LT.length;e++)if(n+=LT[e],t<n)return $T[e];const r=t-58;n=0;for(let e=0;e<MT.length;e++)if(n+=MT[e],r<n)return $T[7-e];return $T[0]}function ShimmerText({text:e,offset:t}){const n=__name(e=>{const n=e-(t-5);return n>=0&&n<Jn.length?Jn[n]:Xn},"getCharColor");return B.createElement(Y,null,e.split("").map((e,t)=>B.createElement(Y,{key:t,color:n(t)},e)))}function CMDIcon({frame:e}){return B.createElement(Y,{color:Mn,bold:!0},getWaveSymbol(e)+" ")}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`}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon"),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");var OT=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,s]=W(0),[o,i]=W(0),a=Q(n);a.current=n;const l=getTerminalWidth();G(()=>{const e=setInterval(()=>{s(e=>(e+1)%88),i(e=>{const t=a.current;if(e===t)return e;const n=t-e,r=e+Math.sign(n)*Math.max(1,Math.ceil(Math.abs(n)/10));return n>0?Math.min(r,t):Math.max(r,t)})},80);return()=>clearInterval(e)},[]);const u=r%(e.length+10),d=l>70,m=l>40&&l<=70;return B.createElement(K,{width:l,height:1,paddingLeft:0,marginLeft:0},B.createElement(CMDIcon,{frame:4*r}),B.createElement(K,{marginRight:1},B.createElement(ShimmerText,{text:e,offset:u})),d?B.createElement(B.Fragment,null,B.createElement(K,{columnGap:1},B.createElement(Y,{dimColor:!0},`(${formatTime3(t)}`),B.createElement(Y,{dimColor:!0},"•"),B.createElement(Y,{color:Ln.GRAY},be.arrowDown),B.createElement(Y,{dimColor:!0},`${formatToken(Math.round(o))}`),B.createElement(Y,{dimColor:!0},"•"),B.createElement(K,{columnGap:1},B.createElement(Y,{bold:!0,color:Ln.GRAY},"esc"),B.createElement(Y,{dimColor:!0},"to interrupt)")))):m?B.createElement(K,{columnGap:1},B.createElement(Y,{dimColor:!0},`(${formatToken(Math.round(o))})`)):B.createElement(B.Fragment,null))},"Status");Nn(),_n(),rr();var DT=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:s})=>{const[o,i]=W(!1),[a,l]=W(0),[u,d]=W(0);G(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=V(()=>{0!==e.trim().length&&n()},[e,n]),p=V(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||o){if(!o||n.isPasteEnd){if(o&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[o,t]);return B.createElement(K,{flexDirection:"column"},r?B.createElement(K,null,B.createElement(CMDIcon,{frame:u}),B.createElement(Y,{color:Ln.WHITE},"Generating agent from description...")):B.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:p,onSubmit:m}),s&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.RED},`${be.warning} ${s}`)))},"RecommendedFlow");Nt(),JE(),rr();var qT=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[s,o]=W(!1),[i,a]=W(0),l=H(()=>[...WE.map(e=>e.name),...QE.map(e=>e.name)],[]),u=H(()=>[{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))}].filter(e=>e.tools.length>0),[l]),d=H(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),s?(u.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:"}),l.forEach(t=>{e.push({type:"tool",value:t})})):(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[s,u,e,l]),m=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=u.find(e=>e.name===t.value),s=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${s?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${VE[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),p=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return Z((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?p.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=p.length?0:t});else if(l.return||" "===e){const e=p[i];if(e){const i=d[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(o(!s),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),B.createElement(K,{flexDirection:"column"},m.map((e,t)=>{const n=p.findIndex(t=>t.value===e.value),r=-1!==n&&n===i;if("divider"===e.type)return B.createElement(K,{key:`divider-${t}`},B.createElement(Y,{color:Ln.GRAY}," ",e.label));if("spacer"===e.type)return B.createElement(K,{key:`spacer-${t}`,height:1});if("label"===e.type)return B.createElement(K,{key:`label-${t}`},B.createElement(Y,{color:Ln.GRAY}," ",e.label));const s="continue"===e.type;return B.createElement(K,{key:`item-${t}`},B.createElement(Y,{color:r?Ln.WHITE:Ln.GRAY,bold:s&&r},r?">":" "," ",e.label))}),B.createElement(K,{marginTop:1},e.size===l.length&&B.createElement(Y,{color:Ln.GRAY},"All tools selected"),e.size>0&&e.size<l.length&&B.createElement(Y,{color:Ln.GRAY},e.size," tools selected"),0===e.size&&B.createElement(Y,{color:Ln.GRAY},"No tools selected")))},"ToolsSelector");ar(),dn(),ts(),bE(),hi(),un(),nr();var FT=__name(({onComplete:e})=>{const[t,n]=W("location"),[r,s]=W(!1),[o,i]=W(null),[a,l]=W("agentType"),u=H(()=>[...WE.map(e=>e.name),...QE.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,p]=W(d()),g=__name(t=>{n("location"),l("agentType"),p(d()),e(t)},"resetToDefaults"),h=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),f=__name(e=>{p({...m,location:e}),n("method")},"handleLocationSelect"),y=__name(e=>{p({...m,method:e}),n("configuration")},"handleMethodSelect"),w=__name(async()=>{try{i(null),s(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===Ct.ANTHROPIC&&(r=await on.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const o={[wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(o[wt.OAUTH_TOKEN]=`Bearer ${r}`);const a=getApiBaseUrl(),l=new Vb({baseUrl:a}),u=await l.post({headers:o,endpoint:St.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});p({...m,agentType:Ne(u.agentName),sysPrompt:u.systemPrompt,ccToolDefinition:u.toolDescription}),n("tools")}catch(e){e instanceof oi&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?i(nn):i("An error occurred while generating the agent. Please try again.")}finally{s(!1)}},"handleRecommendedSubmit"),S=__name(()=>{p({...m,agentType:Ne(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),b=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),E=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),C=__name(()=>{n("summary")},"handleToolsComplete"),v=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),p({...m,selectedTools:t})},"handleToggleTool"),T=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.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(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),p({...m,selectedTools:n})},"handleToggleCategory");return B.createElement(K,{flexDirection:"column",gap:1},B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Create new agent"),B.createElement(Y,{color:Ln.GRAY},h())),B.createElement(K,null,"location"===t&&B.createElement(IT,{onSelect:f}),"method"===t&&B.createElement(RT,{onSelect:y}),"configuration"===t&&"recommended"===m.method&&B.createElement(DT,{description:m.recommendedMethodDescription,onChange:e=>p({...m,recommendedMethodDescription:e}),loading:r,errorMessage:o,onSubmit:w}),"configuration"===t&&"manual"===m.method&&B.createElement(K,{flexDirection:"column",gap:1},B.createElement(NT,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>p({...m,agentType:e}),onSysPromptChange:e=>p({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>p({...m,ccToolDefinition:e}),onAgentTypeSubmit:S,onSysPromptSubmit:b,onCCToolDefinitionSubmit:E})),"tools"===t&&B.createElement(qT,{selectedTools:m.selectedTools,onToggleTool:v,onToggleCategory:T,onComplete:C}),"summary"===t&&B.createElement(PT,{config:m,onSaveComplete:g})))},"AgentNew");rr();var jT=__name(({onCancel:e})=>{const[t,n]=W(null),[r,s]=W(null),o=__name(e=>{n(e.value),s(null)},"handleSelect");return Z((t,n)=>{n.escape&&e()}),B.createElement(K,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:Ln.GRAY,borderStyle:"single",flexDirection:"column"},null===t&&B.createElement(xT,{handleSelect:o,createdAgentName:r}),"create_new_agent"===t&&B.createElement(FT,{onComplete:e=>{s(e),n(null)}}))},"AgentsConfig");rr(),Nt(),Nt(),Ot(),bE(),ts(),dn(),CE(),$n(),en(),nr(),ar();var zT=null;function getRequest2(){return zT||(zT=new Vb({baseUrl:getApiBaseUrl()})),zT}function extractText(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t="";for(const n of e){const e=n;"text"===e.type&&e.text&&(t+=e.text)}return t}async function buildAuthHeaders2(){const e=await getConfiguredProvider(),t=await isOAuthEnforced();let n;e===Ct.ANTHROPIC&&(n=await on.getValidAccessToken(),validateOAuthToken({token:n,provider:e}));const r={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(r[wt.OAUTH_TOKEN]=`Bearer ${n}`),r}function buildConversationSummary(e){return e.slice(-6).filter(e=>"user"===e.message.role||"assistant"===e.message.role).map(e=>{const t="user"===e.message.role?"User":"Command Code",n=extractText(e.message.content).slice(0,300).replace(/\s+\S*$/,"").replace(/\n+/g," ").trim();return n?`${t}: ${n}`:null}).filter(e=>null!==e).join("\n")}function hasAssistantMessage(e){return e.some(e=>"assistant"===e.message.role)}async function predictNextPrompt({messages:e,sessionId:t}){if(!hasAssistantMessage(e))return null;const n=buildConversationSummary(e);if(!n)return null;const r=`Conversation:\n${n}\n\nSuggestion:`;try{const e=getRequest2(),n=await buildAuthHeaders2(),s={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],system:'Suggest what the user might naturally type next into Command Code.\n\nLook at the user\'s recent messages and original request. Predict what THEY would type — not what you think they should do. The test: would they think "I was just about to type that"?\n\nRules:\n- Write ONLY the suggestion, no quotes, no labels, no explanation\n- 2-12 words, match the user\'s style\n- Be specific: "run the tests" beats "continue"\n- Stay silent (reply with nothing) if the next step isn\'t obvious from what the user said\n\nNEVER suggest:\n- Evaluative responses ("looks good", "thanks")\n- Questions ("what about...?")\n- Assistant-voice ("Let me...", "I\'ll...", "Here\'s...")\n- New ideas they didn\'t ask about\n- Multiple sentences\n\nExamples:\n- User asked "fix the bug and run tests", bug is fixed → "run the tests"\n- After code written → "try it out"\n- Command Code offers options → the one the user would likely pick\n- Command Code asks to continue → "yes" or "go ahead"\n- Task complete, obvious follow-up → "commit this" or "push it"\n- After error or misunderstanding → nothing',messages:[{role:"user",content:r}],model:vt,max_tokens:30,temperature:.7,stream:!0},threadId:t||crypto.randomUUID()},o=new AbortController,i=e.post({endpoint:St.ALPHA.GENERATE,body:s,headers:n,stream:!0,signal:o.signal});let a;const l=new Promise((e,t)=>{a=setTimeout(()=>{o.abort(),t(new Error("Timeout"))},5e3)});let u;try{u=await Promise.race([i,l])}finally{clearTimeout(a)}if(!u)return dlog("[PromptPredictor] no response stream"),null;const d=je.fromReadableStream(u);let m="";d.on("text",e=>{m+=e}),await d.finalMessage();const p=m.trim().replace(/^["']|["']$/g,"").replace(/\n.*$/,"");if(!p)return null;const g=p.replace(/[.?!]+$/,"").trim();return g?(dlog(`[PromptPredictor] predicted: "${g}"`),g):null}catch(e){return dlog(`[PromptPredictor] failed: ${e instanceof Error?e.message:String(e)}`),null}}__name(getRequest2,"getRequest"),__name(extractText,"extractText"),__name(buildAuthHeaders2,"buildAuthHeaders"),__name(buildConversationSummary,"buildConversationSummary"),__name(hasAssistantMessage,"hasAssistantMessage"),__name(predictNextPrompt,"predictNextPrompt"),$n();var BT=['Try "how to log errors?"','Try "text diagram how <@file> works?"','Try "add tests for <@file>"','Try "refactor this to use async/await"','Try "what does this function do?"','Try "find all usages of <function>"','Try "fix the TypeScript errors"','Try "explain the architecture"','Try "write docs for <@file>"','Try "optimize this for performance"','Try "review this code for bugs"','Try "how does <feature> work?"'];function getRandomSuggestion(){const e=Math.floor(Math.random()*BT.length);return BT[e]??BT[0]??""}function usePredictedPlaceholder({contextEngineRef:e,isCmdCodeBusy:t}){const[n,r]=W(()=>(e.current?.getMessages().length??0)>0?"":getRandomSuggestion()),[s,o]=W(!1),i=Q(t);return G(()=>{const n=i.current;if(i.current=t,dlog(`[usePredictedPlaceholder] wasBusy: ${n}, isCmdCodeBusy: ${t}`),!n||t)return;if(!e.current)return;const s=e.current.getMessages(),a=e.current.getSessionId();dlog(`[usePredictedPlaceholder] Triggering prediction with ${s.length} messages`),r(""),o(!1);let l=!1;return predictNextPrompt({messages:s,sessionId:a}).then(e=>{dlog(`[usePredictedPlaceholder] Prediction result: ${e}`),e&&!l&&(r(e),o(!0))}).catch(e=>{dlog(`[usePredictedPlaceholder] Prediction error: ${e}`)}),()=>{l=!0}},[t,e]),{placeholder:n,isPrediction:s,onAccepted:V(()=>{r(""),o(!1)},[])}}function useTerminalWidth(){const{stdout:e}=X(),[t,n]=W(()=>e.columns??80);return G(()=>{const t=__name(()=>n(e.columns??80),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}__name(getRandomSuggestion,"getRandomSuggestion"),__name(usePredictedPlaceholder,"usePredictedPlaceholder"),Nt(),__name(useTerminalWidth,"useTerminalWidth"),Nt(),Nt(),vn(),Ot(),_n(),ln(),Nt();var UT=n(y(),"commandcode-images"),WT={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{E(UT)||C(UT,{recursive:!0});const r=WT[e.mediaType]||".png",s=`image-${t}-${Date.now()}${r}`,o=n(UT,s),i=Buffer.from(e.data,"base64");return v(o,i),o}catch{return null}}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,detectedContent:n,setInput:r,setDetectedImages:s,setDetectedContent:o,incrementInputKey:i}=e,a=V((e,t)=>{s(t=>[...t,e]),r(t),i()},[s,r,i]),l=Q(!1),u=Q(""),d=Q(null),m=Q(""),p=V(async(e,t)=>{let s=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectDroppedImageFile(s);if(l)return void a(l,t);const u=await detectClipboardImage();if(u)return void a(u,t);let d=s;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#${n.length+1}]`;o(e=>[...e,d]),r(t+e)}else r(t+d);i()}},[a,n.length,o,r,i]),g=V(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(l.current){const e=u.current,t=m.current;u.current="",m.current="",l.current=!1,d.current=null,e&&await p(e,t)}},500)},[p]);return{handlePaste:V(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return l.current&&(l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)),await p(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!l.current)return l.current=!0,m.current=n.textBeforePaste??t,u.current=n.pastedContent??n.cleanedContent,g(),!0;if(l.current&&!n.isPasteEnd)return void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current)),g(),!0;if(l.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current));const e=u.current,t=m.current;return u.current="",m.current="",l.current=!1,await p(e,t),!0}if(n.isPasteEnd&&!n.isPasteStart&&!l.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return a(e,t),!0}return!1},[t,p,g,a]),resetPasteState:V(()=>{l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:V(()=>l.current,[])}}__name(saveTempImage,"saveTempImage"),ar(),Nt(),Nn(),_n(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),Nn(),Nt(),Nt();var QT=["code --wait","cursor --wait","nano"],GT=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return GT.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 I(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of QT)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var HT=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 HT;t=ensureWaitFlag(t);const r=n(y(),`commandcode-${Date.now()}.md`);return await M(r,e),new Promise((e,n)=>{const s=t.split(" ").filter(e=>e.length>0),o=s[0],i=s.slice(1),a=N(o,[...i,r],{stdio:"inherit"});a.on("close",async()=>{try{const t=await O(r,"utf-8");await D(r),e(t.trimEnd())}catch(e){n(e)}}),a.on("error",async e=>{try{await D(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[s,o]=W(!1),[i,a]=W(null),l=V(async()=>{if(!s){o(!0),a(null);try{const s=e.replace(/\n+$/,""),o=await openInEditor2(s);t(o),n(e=>e+1),r?.()}catch(e){a(e instanceof HT?"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{o(!1)}}},[e,t,r,s]),u=V(()=>{a(null)},[]);return{isEditorOpen:s,editorError:i,handleOpenInEditor:l,clearEditorError:u}}__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"),Nt(),Nt(),Nt(),Nt(),Ot(),$n(),lr(),yr(),Nt(),Ot();var VT=t.join(f.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(VT);S.existsSync(e)||S.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!S.existsSync(VT))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=S.readFileSync(VT,"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(),S.writeFileSync(VT,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"),lr();var KT=Ve(x),YT=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=I("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return YT.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(tt.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&tt.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&tt.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:s,updateAvailable:o}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:s,updateAvailable:o}}async function executeUpdate(e){try{return await KT(`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(!tt.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=Ie(`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 s=n||await checkForUpdateAvailable();return s?.updateAvailable?(r?.(s.latestVersion),await executeUpdate(s.latestVersion)?{success:!0,updateInfo:s}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:s})):{success:!1}}function getCurrentGitBranch(){try{return I("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()}}__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");var JT=new Set(["OPEN","MERGED","CLOSED"]),XT=null;function getCachedPRInfo(e){if(XT&&XT.branch===e){if(!(Date.now()-XT.timestamp>3e5))return XT.result;XT=null}}function setPRCache(e,t){XT={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((s,o)=>{R(e,[...t],{encoding:n,timeout:r},(e,t)=>{e?o(e):s(t.trim())})})}function parsePRResponse(e){try{const t=JSON.parse(e);return t.number&&t.url&&t.state&&JT.has(t.state)?{number:t.number,title:t.title||"",url:t.url,state:t.state}:null}catch{return null}}__name(getCachedPRInfo,"getCachedPRInfo"),__name(setPRCache,"setPRCache"),__name(execFileAsync,"execFileAsync"),__name(parsePRResponse,"parsePRResponse");var ZT=__name(async()=>{const e=getCurrentGitBranch();if(!e)return null;if("main"===e||"master"===e)return null;const t=getCachedPRInfo(e);if(void 0!==t)return t;try{const t=parsePRResponse(await execFileAsync({cmd:"gh",args:["pr","view","--json","number,title,url,state"],encoding:"utf-8",timeout:3e3}));return setPRCache(e,t),t}catch{return setPRCache(e,null),null}},"detectPR"),ek=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=W(null),s=Q(!1);return G(()=>{if(!t||s.current)return;let e=!0;return s.current=!0,ZT().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=nt(),r=n(e,".gitignore");if(E(r))try{const e=b(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}rr(),Nt(),rr(),__name(loadGitignore,"loadGitignore");var tk=__name(({onSelectFile:e,onClose:t,searchQuery:i=""})=>{const[a,l]=W(process.cwd()),[u,d]=W([]),[m,p]=W(0),[g,h]=W(0),f=i.trim()?15:10,y=V((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const o=n(t,e);try{const e=T(o),i=[];return e.forEach(e=>{const a=n(o,e);try{const e=k(a),n=s(t,a);if(r.ignores(n))return;i.push({name:n,path:a,isDirectory:e.isDirectory()})}catch{}}),i.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),i.slice(0,50)}catch{}}if(e.includes("/")){const o=e.split("/"),i=o.pop()||"",a=n(t,o.join("/"));try{const e=T(a),o=[],l=i.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!i||u.includes(l)){const i=n(a,e);try{const e=k(i),n=s(t,i);if(r.ignores(n))return;o.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),o.slice(0,50)}catch{}}const o=[],i=e.toLowerCase(),a=__name((e,l=0)=>{if(!(l>8))try{T(e).forEach(u=>{const d=n(e,u);try{const e=k(d),n=s(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(i)||m.includes(i))&&o.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==u&&a(d,l+1)}catch(e){}})}catch(e){}},"searchRecursively");return a(t),o.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),s=n===i,o=r===i;if(s&&!o)return-1;if(!s&&o)return 1;const a=n.split("/").pop()||"",l=r.split("/").pop()||"",u=a.includes(i),d=l.includes(i);if(u&&!d)return-1;if(!u&&d)return 1;const m=e.name.split("/").length,p=t.name.split("/").length;return m!==p?m-p:e.name.localeCompare(t.name)}),o.slice(0,50)},[]),w=V(e=>{try{const t=T(e),o=[],i=process.cwd(),a=loadGitignore(i);"/"!==e&&o.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=k(r),n=s(i,r);if(a.ignores(n))return;o.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(o),p(0),h(0)}catch{}},[]);G(()=>{if(i.trim()){const e=y(i);d(e),p(0),h(0)}else w(a)},[a,w,i,y]),Z((n,r)=>{if(r.escape)t();else if(r.upArrow)p(e=>{const t=Math.max(0,e-1);return t<g&&h(t),t});else if(r.downArrow)p(e=>{const t=Math.min(u.length-1,e+1);return t>=g+f&&h(t-f+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!i.trim()&&l(o(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const S=u.slice(g,g+f);return B.createElement(K,{flexDirection:"column",paddingLeft:1},B.createElement(K,{marginBottom:1,flexDirection:"column"},B.createElement(Y,{color:Ln.DIM},i.trim()?`Searching for: "${i}"`:`Files: ${a}`),B.createElement(Y,{color:Ln.DIM},i.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===S.length?B.createElement(Y,{color:Ln.DIM},i.trim()?`No files found matching "${i}"`:"No files found in this directory"):S.map((e,t)=>{const n=g+t,r=e.name,s=n===m;return B.createElement(Y,{key:e.path,color:s?Ln.GREEN:Ln.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Nt(),Ot(),ir(),rr(),Nt(),rr();var nk=__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?Ln.RED:e>=70?Ln.YELLOW:Ln.DIM,"getColor"),s=`context: ${n}% left before auto-compact`;return B.createElement(K,{paddingRight:1},B.createElement(Y,{color:r(t)},s))},"ContextUsage");Nt(),tC(),jr(),rr();var rk=__name(()=>{const[e,t]=W("continuous learning"),n=Q([]),r=Q(0),s=Q(null),o=Q(!1);G(()=>{const e=__name(e=>"analyzing"===e.type?(o.current=!0,n.current=[],r.current=0,s.current&&(clearTimeout(s.current),s.current=null),void t(e.message)):o.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(o.current=!1,void(n.current.length>0?(r.current=0,i()):t("continuous learning"))):void 0,"handleNewEvent"),i=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const o="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;s.current=setTimeout(()=>{r.current++,i()},o)},"cycleThroughNextEvent");return ZE.on("new-event",e),()=>{ZE.off("new-event",e),s.current&&clearTimeout(s.current)}},[]);const i=`${be.bullet} taste: `,a=i.length+e.length+9>Rr;let l=e;return l=truncateString(a?{text:e,maxChars:Rr}:{text:e,maxChars:Rr-i.length-9-10}),B.createElement(K,{paddingRight:3},!a&&B.createElement(Y,{color:On.TEXT},i),B.createElement(Y,null,l),!a&&B.createElement(Y,{dimColor:!0}," (ctrl+t)"))},"LearningFeedMini");Nt(),rr();var sk=__name(({mode:e,pendingExitKey:t})=>t?B.createElement(Y,{dimColor:!0},"Press Ctrl+C again to exit"):"auto-accept"===e?B.createElement(K,{flexDirection:"row"},B.createElement(Y,{color:Hn},"» accept edits on "),B.createElement(Y,{dimColor:!0},"(shift+tab)")):"plan"===e?B.createElement(K,{flexDirection:"row"},B.createElement(Y,{color:Gn},"plan mode "),B.createElement(Y,{dimColor:!0},"(shift+tab)")):B.createElement(Y,{color:Ln.DIM},"? for shortcuts"),"ModeIndicator");Nt(),rr(),Nt();var ok=__name(({url:e,text:t,dimColor:n=!1,color:r})=>{const s=`]8;;${e}${t}]8;;`;return B.createElement(Y,{dimColor:n,color:r},s)},"TerminalLink"),ik=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?Vn.OPEN:Vn.MERGED;return B.createElement(B.Fragment,null,t&&B.createElement(Y,{dimColor:!0}," · "),B.createElement(Y,{color:n},"PR "),B.createElement(ok,{url:e.url,text:`#${e.number}`,dimColor:!0}))},"PRLinkBadge"),ak=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?B.createElement(B.Fragment,null,t&&B.createElement(Y,{dimColor:!0}," · "),B.createElement(Y,{color:"connected"===e.type?Ln.GREEN:Ln.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),lk=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:s,tasteLearning:o,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:p,isBashMode:g,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w})=>{const S=e>=60;return B.createElement(B.Fragment,null,B.createElement(K,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r||l?B.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(K,{flexDirection:"row",columnGap:0},n&&!l?B.createElement(Y,{color:Un},t):B.createElement(sk,{mode:r,pendingExitKey:l}),!l&&B.createElement(ik,{prInfo:s}),!l&&B.createElement(ak,{indicator:a})),S&&B.createElement(K,{flexDirection:"column",alignItems:"flex-end"},o&&B.createElement(rk,null),i&&B.createElement(nk,{usage:i}))):B.createElement(B.Fragment,null,B.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(sk,{mode:r}),S&&o&&B.createElement(rk,null)),B.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(K,{flexDirection:"row",columnGap:0},B.createElement(Y,{color:n?Un:void 0,dimColor:!n},t),B.createElement(ik,{prInfo:s}),B.createElement(ak,{indicator:a})),S&&i&&B.createElement(nk,{usage:i}))),(u||d||p&&m)&&B.createElement(K,{flexDirection:"row",columnGap:1},u&&B.createElement(Y,null,be.tick," ","Command Code"," updated:"," ",B.createElement(Y,{dimColor:!0},"v",u.updatedFrom),B.createElement(Y,{dimColor:!0}," ",be.arrowRight," "),B.createElement(Y,null,"v",u.updatedTo)),!u&&d&&B.createElement(Y,{color:Ln.YELLOW,dimColor:!0},be.info," Update available:"," ",d.currentVersion," ",be.arrowRight," ",d.latestVersion),p&&m&&B.createElement(Y,{color:Ln.GREEN,dimColor:!0},be.bullet," Provider:"," ",getProviderDisplayName(m)))),g&&B.createElement(K,{paddingLeft:2},B.createElement(Y,{color:Ln.GREEN},"! for bash mode")),f&&h&&B.createElement(K,{paddingLeft:2},B.createElement(Y,{color:Mn},"SHARED: ",h.url," (copied to clipboard)")),y&&B.createElement(K,{paddingLeft:2},B.createElement(Y,{color:y.includes("NOT SHARED")?Ln.RED:Mn},y)),w&&B.createElement(K,{paddingLeft:2},B.createElement(Y,{color:Mn},w)))},"BottomIndicator");Nt(),CE(),jr(),rr();var ck=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=W([]),[s,o]=W(0),[i,a]=W(!0);G(()=>{l()},[]);const l=__name(async()=>{a(!0);const e=await Yb.listSessions();r(e.slice(0,30)),a(!1)},"loadSessions");if(Z((r,i)=>{i.escape?t():i.upArrow?o(e=>Math.max(0,e-1)):i.downArrow?o(e=>Math.min(n.length-1,e+1)):i.return&&n.length>0&&s<n.length&&e(n[s].id)}),i)return B.createElement(K,{flexDirection:"column",paddingLeft:2},B.createElement(Y,{color:Ln.GRAY},"Loading sessions..."));if(0===n.length)return B.createElement(K,{flexDirection:"column",paddingLeft:2},B.createElement(Y,{color:Ln.GRAY},"No previous sessions found"),B.createElement(Y,{color:Ln.DIM,dimColor:!0},"Press ESC to go back"));const u=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(n/36e5),o=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:s<24?`${s}h ago`:`${o}d ago`},"formatRelativeTime"),d=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),m=__name(e=>truncateString({text:d(e),maxChars:Nr}),"truncateMessage"),p=__name(e=>e.title?d(e.title):m(e.firstMessage),"getSessionSummary");return B.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},B.createElement(Y,{color:Ln.CYAN,bold:!0},"Resume Session"),B.createElement(Y,{color:Ln.DIM,dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),B.createElement(K,{marginTop:1}),B.createElement(K,{columnGap:2,marginBottom:1},B.createElement(K,{width:5},B.createElement(Y,{color:Ln.GRAY}," ")),B.createElement(K,{width:13},B.createElement(Y,{color:Ln.GRAY},"Modified")),B.createElement(K,{width:20},B.createElement(Y,{color:Ln.GRAY},"Git Branch")),B.createElement(K,{width:11},B.createElement(Y,{color:Ln.GRAY},"# Messages")),B.createElement(K,null,B.createElement(Y,{color:Ln.GRAY},"Summary"))),B.createElement(K,{columnGap:2},B.createElement(K,{flexDirection:"column",width:5},n.map((e,t)=>B.createElement(Y,{key:`sel-${t}`,color:s===t?Ln.WHITE:Ln.GRAY},s===t?`${be.pointer} ${t+1}.`:` ${t+1}.`))),B.createElement(K,{flexDirection:"column",width:13},n.map((e,t)=>B.createElement(Y,{key:`mod-${e.id}`,color:s===t?Ln.WHITE:Ln.GRAY},u(e.lastModified)))),B.createElement(K,{flexDirection:"column",width:20},n.map((e,t)=>B.createElement(Y,{key:`branch-${e.id}`,color:s===t?Ln.WHITE:Ln.GRAY,wrap:"truncate-end"},e.gitBranch||"-"))),B.createElement(K,{flexDirection:"column",width:11},n.map((e,t)=>B.createElement(Y,{key:`msg-${e.id}`,color:s===t?Ln.WHITE:Ln.GRAY},e.messageCount))),B.createElement(K,{flexDirection:"column"},n.map((e,t)=>B.createElement(Y,{key:`summary-${e.id}`,color:s===t?Ln.WHITE:Ln.GRAY,wrap:"truncate-end"},p(e))))))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],s=0;for(let o=0;o<e;o++){const e=`[Image #${o+1}]`.length,i=e+(r.length>0?1:0);r.length>0&&s+i>t?(n.push(r),r=[o],s=e):(r.push(o),s+=i)}return r.length>0&&n.push(r),n}function shouldSelectImageOnUpArrow({isOnFirstLine:e,imageCount:t,selectedImageIndex:n,historyIndex:r}){return e&&t>0&&-1===n&&-1===r}function nextImageIndex({currentIndex:e,imageCount:t}){return e===t-1?0:e+1}function prevImageIndex({currentIndex:e,imageCount:t}){return 0===e?t-1:e-1}function removeImageAt({images:e,index:t}){const n=e.filter((e,n)=>n!==t);return{remainingImages:n,nextSelectedIndex:n.length>0?n.length-1:-1}}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const s=`[Image #${e+1}]`,o=n?createOSC8Link(`file://${n}`,s,!1):s;return B.createElement(Y,null,r?" ":"",t?B.createElement(Y,{inverse:!0},s):o)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:s}){if(0===e.length)return null;const o=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:s}),i=Math.max(1,r-(o.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return B.createElement(K,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>B.createElement(K,{key:r,flexDirection:"row"},B.createElement(K,{flexShrink:0,marginRight:1},0===r&&B.createElement(Y,{color:Ln.DIM},o)),B.createElement(K,{flexDirection:"row"},e.map((e,r)=>B.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Nt(),rr(),Nt(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Nt(),Sl();var uk=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,s]=W(null),[o,i]=W(!1),a=Q(!1),l=Q(null),[u,d]=W(!1),[m,p]=W("connected"),g=Q(null),h=Q(null),f=V((e,t)=>{h.current&&(clearTimeout(h.current),h.current=null),p(e),d(!0),void 0!==t&&(h.current=setTimeout(()=>{d(!1)},t))},[]),y=V(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),w=V(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new dl,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=g.current;if(null===r?n&&f("connected",3e3):r!==n&&(n?f("connected",2e3):f("disconnected",5e3)),g.current=n,i(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),s(r)}else s(null)}catch{!0===g.current&&f("disconnected",5e3),g.current=!1,i(!1),s(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[f]);G(()=>{if(!t||n)return;w(!0);const e=setInterval(()=>w(!1),500);return()=>{clearInterval(e),y(),l.current?.disconnect(),l.current=null}},[t,n,w,y]);const S={visible:u,message:"connected"===m?`IDE ${be.tick}`:"IDE disconnected",type:m};return{context:r,connected:o,refresh:w,connectionIndicator:S}},"useVSCodeContext");Nt();var dk=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:s}=e.activeFile;t.push(`File: ${n} (${r}, line ${s.line})`)}if(e.selection){const{text:n,startLine:r,endLine:s}=e.selection,o=e.activeFile?.language??"";t.push(`Selected lines ${r}-${s}:`),t.push(`\`\`\`${o}`);const i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"&lt;/ide-context&gt;");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Nt();var mk=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),pk=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const s=e?t?.activeFile:null;if(s?.relativePath){const e=s.relativePath.split("/").pop()||"",t=n<80?15:n<120?25:40;return`In ${e.length>t?e.slice(0,t-1)+"…":e}`}return"? for shortcuts"},"getIndicatorText"),gk=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var hk=__name(()=>B.createElement(K,{flexDirection:"column",paddingLeft:1},B.createElement(Y,{color:Ln.DIM,bold:!0},"Available Shortcuts:"),B.createElement(K,{columnGap:4},B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.DIM},"! for bash mode"),B.createElement(Y,{color:Ln.DIM},"/ for commands"),B.createElement(Y,{color:Ln.DIM},"@ for file paths"),B.createElement(Y,{color:Ln.DIM},"shift + tab to toggle auto-accept")),B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.DIM},"double tap esc to clear input"),B.createElement(Y,{color:Ln.DIM},"ctrl + j / shift + ⏎ for newline"),B.createElement(Y,{color:Ln.DIM},"ctrl + g to open in editor"),B.createElement(Y,{color:Ln.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),fk=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",isPlaceholderPrediction:i=!1,onPlaceholderAccepted:a,showFileList:l,setShowFileList:u,fileSearchQuery:d,setFileSearchQuery:m,onCommand:p,contextUsage:g,tasteLearning:h=!1,tasteUsage:f=!1,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,permissionMode:k="standard",onToggleAutoAccept:_,hintMessage:P,historyManager:A,pendingExitKey:x=null,onOverlayVisibilityChange:I,onDoubleEscapeEmpty:N,onAltP:R,isProcessing:$=!1,ideContextEnabled:L=!0})=>{const[M,O]=W(0),[D,q]=W(!1),[F,j]=W(!1),[z,U]=W(!1),[J,ee]=W(!1),[te,ne]=W(""),[re,se]=W(!1),oe=Q(0),ie=Q(0),[ae,le]=W([]),[ce,ue]=W([]),[de,me]=W(-1),[pe,ge]=W(""),he=Q(!1),fe=Q(!1),[ye,we]=W(-1),[Se,Ee]=W(""),Ce=Q(0),{isEditorOpen:ve,editorError:Te,handleOpenInEditor:ke,clearEditorError:_e}=useExternalEditor({input:e,setInput:n,setInputKey:O,onEditorClose:__name(()=>{he.current=!1},"onEditorClose")}),{handlePaste:Pe,resetPasteState:Ae,isPasting:xe}=useBracketedPaste({input:e,detectedContent:ae,setInput:n,setDetectedImages:ue,setDetectedContent:le,incrementInputKey:__name(()=>O(e=>e+1),"incrementInputKey")}),{context:Ie,connected:Ne,refresh:Re,connectionIndicator:$e}=uk({enabled:L,paused:$}),{stdout:Le}=X(),Me=Le?.columns??80,{pr:Oe}=ek();G(()=>{const e=l||J||re;I?.(e)},[l,J,re,I]);const De=V(()=>{ue([]),me(-1)},[]),qe=V(()=>{n(""),j(!1),ee(!1),ne(""),se(!1),le([]),De(),ge(""),Ae(),we(-1),Ee(""),O(e=>e+1)},[n,Ae,De]),Fe=V(()=>{he.current=!0,n(e+"\n"),O(e=>e+1),setTimeout(()=>{he.current=!1},0)},[e,n]);Z(async(t,r)=>{if(-1!==de&&r.leftArrow)return void me(prevImageIndex({currentIndex:de,imageCount:ce.length}));if(-1!==de&&r.rightArrow)return void me(nextImageIndex({currentIndex:de,imageCount:ce.length}));if(r.upArrow){if(l||J||re)return;const t=e.indexOf("\n"),r=-1===t||Ce.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ce.length,selectedImageIndex:de,historyIndex:ye}))return void me(ce.length-1);if(-1!==de&&me(-1),0!==e.length&&-1===ye&&!r)return;const s=A?.count()??0;if(0===s)return;-1===ye&&Ee(e);const o=Math.min(ye+1,s-1);return void(o!==ye&&(we(o),n(A?.getAt(o)||""),O(e=>e+1)))}if(r.downArrow){if(l||J||re)return;if(-1===ye)return;const t=e.lastIndexOf("\n");if(!(-1===t||Ce.current>t))return;const r=ye-1;return we(r),n(-1===r?Se:A?.getAt(r)||""),void O(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void De();if(r.tab&&!r.shift&&0===e.length&&i&&o&&o.length>0&&!l&&!J&&!re)return he.current=!0,n(o),O(e=>e+1),a?.(),void setTimeout(()=>{he.current=!1},0);if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return he.current=!0,void ke();if(getIsExpandToolShortcut(r,t))return he.current=!0,n(e),O(e=>e+1),void setTimeout(()=>{he.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:xe()}))return fe.current=!0,Fe(),void setTimeout(()=>{fe.current=!1},0);if(r.meta&&r.backspace)return void qe();if(r.meta&&"w"===t)return he.current=!0,void qe();const s=r.ctrl&&"v"===t||gk.includes(t),u=r.meta&&"v"===t;if(s||u){if(s&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();return r&&(ue(e=>[...e,r]),n(t),O(e=>e+1)),void(he.current=!0)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return U(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==de&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ce,index:de});return ue([...e]),void me(t)}if(r.escape){if(-1!==de)return void me(-1);if(J)return;if(re)return se(!1),n(pe),void O(e=>e+1);const t=Date.now();return t-oe.current<500?(e.length>0?qe():N?.(),oe.current=0,ie.current=0):(oe.current=t,D||F||(ie.current=t)),q(!1),void j(!1)}D&&(r.backspace||r.delete)&&0===e.length&&q(!1)}});const je=V(async t=>{if(ve)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void R?.();const s=processBracketedPaste(t);if((s.isPasteStart||s.isPasteEnd||xe())&&await Pe(t))return;if(he.current)return void(he.current=!1);-1!==ye&&we(-1);const o=1===t.length,i=t.slice(-1);if(o){if("?"===i&&!D)return q(!0),n(""),void O(e=>e+1);if("!"===i&&!F)return q(!1),j(!0),n(""),void O(e=>e+1)}if("/"!==i||J||"/"!==t||(ee(!0),ne("")),J&&!t.startsWith("/")&&(ee(!1),ne("")),J&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(ee(!1),ne("")):ne(e)}"@"!==i||l||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(u(!0),m(""));const a=t.lastIndexOf("@");if(t.length<e.length&&-1!==a&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(a+1),n=!e.includes(" "),r=a>0?t[a-1]:"";n&&isPrecededByWhitespace(r)&&(u(!0),m(e))}if(l)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)u(!1),m("");else{const n=t.substring(e+1);m(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);m(e),u(!1)}else m(n)}}D&&(t!==e||t.length<e.length)&&q(!1),Te&&_e(),0===t.length&&(j(!1),ee(!1),ne(""),se(!1),De(),le([]),m(""),ge(""),Ae()),n(t)},[D,e,n,l,u,J,F,ce,ye,Pe,Ae,R,Te,_e,ve,De]),ze=V(async()=>{if(Re(),ie.current=0,D)return void q(!1);let n=e.trim();if(!F&&n.startsWith("/")&&p&&"handled"===(await p(n)).status)return A?.add(n),j(!1),ee(!1),ne(""),De(),le([]),we(-1),void Ee("");n.length>0&&A?.add(n),we(-1),Ee("");let r=[];const s=ce.length>0,o=ae.length>0;if(!F&&s&&(r=[...ce]),!F&&o){let e=n;ae.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:F?"bash":"user",images:r,ideContext:Ie?dk(Ie):void 0}),j(!1),ee(!1),ne(""),De(),le([])},[t,p,D,e,F,ce,ae,A,Re,De]),Be=V(t=>{const r=s(process.cwd(),t);let o;if(l&&""!==d){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),u(!1),m(""),O(e=>e+1)},[n,u,e,l,d,m]),Ue=V(()=>{u(!1),m("")},[u,m]),We=V(t=>{if("/resume"===t)A?.add(t),we(-1),Ee(""),ge(e),ee(!1),ne(""),se(!0),n(""),O(e=>e+1);else{const e=Object.values(Nv).includes(t);ee(!1),ne(""),e?(A?.add(t),we(-1),Ee(""),n(""),O(e=>e+1),p&&p(t)):(n(t+" "),O(e=>e+1))}},[p,n,e,A]),Qe=V(e=>{ee(!1),ne(""),n(e+" "),O(e=>e+1)},[n]),Ge=V(()=>{ee(!1),ne(""),n(""),we(-1),Ee(""),O(e=>e+1)},[n]),He=V(e=>{se(!1),n(""),ge(""),we(-1),Ee(""),O(e=>e+1),p&&p(`/resume:${e}`)},[p,n]),Ve=V(()=>{se(!1),n(pe),we(-1),Ee(""),O(e=>e+1)},[pe,n]),Ke=V(e=>{Ce.current=e},[]),Ye=H(()=>{const t=Oe&&("OPEN"===Oe.state||"MERGED"===Oe.state);return"auto-accept"===k||"plan"===k||Ne||t?!D&&!re:!D&&0===e.length&&!F&&!re},[D,e,F,re,k,Ne,Oe]),Je=Q(new Map),Xe=H(()=>ce.map((e,t)=>{if(Je.current.has(e))return Je.current.get(e)??null;const n=saveTempImage(e,t+1);return Je.current.set(e,n),n}),[ce]),Ze=__name(()=>D||l||J||re||z?0:Ye||x||F?3:4,"getBottomMargin");return B.createElement(K,{width:"100%",flexDirection:"column",marginBottom:Ze()},!re&&B.createElement(K,{flexDirection:"column",width:"100%"},B.createElement(ImageRowsDisplay,{detectedImages:ce,selectedImageIndex:de,imageTempPaths:Xe,termWidth:Me,inHistory:-1!==ye}),B.createElement(Y,{color:F?Ln.GREEN:Ln.GRAY},be.line.repeat(Me)),B.createElement(TextInput,{key:M,value:e,placeholder:ve?"Save and close the editor to continue...":o,onChange:je,onSubmit:()=>{if(!fe.current)return Date.now()-ie.current<100?(ie.current=0,void Fe()):void(l||J||re||ve||ze());fe.current=!1},showCursor:!ve&&r&&-1===de,onCursorChange:Ke,prefix:`${F?"!":be.pointer} `,prefixColor:F?Ln.GREEN:Ln.WHITE}),B.createElement(Y,{color:F?Ln.GREEN:Ln.GRAY},be.line.repeat(Me))),D&&B.createElement(hk,null),z&&B.createElement(K,{paddingTop:1},B.createElement(Y,{color:Ln.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),l&&B.createElement(tk,{onSelectFile:Be,onClose:Ue,searchQuery:d}),J&&B.createElement(Lv,{onSelectCommand:We,onInsertCommand:Qe,onClose:Ge,searchQuery:te}),re&&B.createElement(ck,{onSelectSession:He,onClose:Ve}),(Ye||x)&&B.createElement(lk,{termWidth:Me,indicatorText:pk(Ne,Ie,Me),isIDEIndicator:mk(Ne,Ie),permissionMode:k,prInfo:Oe,tasteLearning:h,contextUsage:g,connectionIndicator:$e,pendingExitKey:x,updateStatus:E,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,isBashMode:F,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:b}),Te&&B.createElement(K,{paddingLeft:1,flexDirection:"column"},B.createElement(Y,{color:Ln.YELLOW},Te)))},"InputBox");Nt(),jr(),rr();var yk=__name(({messages:e})=>0===e.length?null:B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(K,{marginBottom:0},B.createElement(Y,{color:qn,dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>B.createElement(K,{key:t},B.createElement(Y,{dimColor:!0},be.pointerSmall," "),B.createElement(Y,{dimColor:!0},truncateString({text:e,maxChars:80}))))),"QueuedMessages"),wk=B.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:s,setInput:o,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:p=0,contextUsage:g,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,permissionMode:k,onToggleAutoAccept:_,hintMessage:P,historyManager:A,pendingExitKey:x,onResetPendingExitKey:I,onDoubleEscapeEmpty:N,retryAttempt:R,onAltP:$,placeholder:L="Ask your question...",isPlaceholderPrediction:M=!1,onPlaceholderAccepted:O})=>{const[D,q]=W(0),F=Q(s);return G(()=>{x&&s!==F.current&&s.length>0&&I?.(),F.current=s},[s,x,I]),G(()=>{if(!t)return void q(0);const e=setInterval(()=>{q(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),B.createElement(K,{flexDirection:"column"},B.createElement(yk,{messages:e}),B.createElement(K,{flexDirection:"row",justifyContent:"space-between"},B.createElement(K,{flexDirection:"column"},(t||n.isExecuting)&&null===R&&B.createElement(OT,{tokens:p,timeElapsed:D,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),P&&B.createElement(K,{marginLeft:1},B.createElement(Y,{dimColor:!0}," ","⎿"," ","Tip: ",P)))),B.createElement(fk,{input:s,setInput:o,onSubmit:i,placeholder:L,isPlaceholderPrediction:M,onPlaceholderAccepted:O,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:g,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,permissionMode:k,onToggleAutoAccept:_,hintMessage:P,historyManager:A,pendingExitKey:!x||t||n.isExecuting?null:x,onDoubleEscapeEmpty:N,onAltP:$,isProcessing:t}))});Nt(),ns(),ls(),sr(),ir();var Sk=__name(({onComplete:e,onCancel:t})=>{const[n,r]=W(!1),[s,o]=W(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:p}=useAuthFlow({onSuccess:__name((t,n)=>{const s=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";o(s),isInternalTeamFlagEnforced()?r(!0):e(!0,s?`Logged in as ${s}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return Z((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,s?`Logged in as ${s}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");p()}}),n?B.createElement(er,{onSuccess:()=>{e(!0,s?`Logged in as ${s} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,s?`Logged in as ${s}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,s?`Logged in as ${s}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):B.createElement(ss,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");async function discoverOAuthMetadata(e){const t=new d(e),n=`${t.protocol}//${t.host}`;try{const e=`${n}/.well-known/oauth-authorization-server`,t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(e.authorization_endpoint&&e.token_endpoint)return{authorizationEndpoint:e.authorization_endpoint,tokenEndpoint:e.token_endpoint,registrationEndpoint:e.registration_endpoint,scopes:e.scopes_supported}}}catch(e){dlog("[MCP] OAuth discovery endpoint not available",e)}try{const e=`${n}/.well-known/openid-configuration`,t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(e.authorization_endpoint&&e.token_endpoint)return{authorizationEndpoint:e.authorization_endpoint,tokenEndpoint:e.token_endpoint,registrationEndpoint:e.registration_endpoint,scopes:e.scopes_supported}}}catch(e){dlog("[MCP] OIDC discovery not available",e)}return null}async function checkServerAuthRequirements(e){try{const t=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"initialize",id:0,params:{protocolVersion:Ds,capabilities:{},clientInfo:qs}})});return 401===t.status||403===t.status?{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}:{requiresAuth:!1}}catch(e){return{requiresAuth:!1,error:`Server unreachable: ${e instanceof Error?e.message:String(e)}`}}}async function registerOAuthClient({registrationEndpoint:e,clientName:t,redirectUris:n}){try{const r=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:t,redirect_uris:n,token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]})});if(r.ok){const e=await r.json();return{clientId:e.client_id,clientSecret:e.client_secret}}}catch(e){dlog("[MCP] OAuth client registration failed",e)}return null}Nt(),rr(),Nt(),Vs(),Hs(),eo(),Ys(),to(),uo(),mo(),po(),Nt(),mo(),po(),Js(),co(),Nt(),so(),Hs(),$n(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient");var bk=__name(({onClose:e})=>{const[t,n]=W([]),[r,s]=W(!0),[o,i]=W(0),[a,l]=W("list"),[u,d]=W(null);G(()=>{m()},[]);const m=__name(async()=>{s(!0);try{const e=await listMcpServers(),t=getMcpConnectionManager().getConnectedServers(),r=await Promise.all(e.map(async e=>{const n=t.find(t=>t.name===e.name);let r,s,o="disconnected";return n&&"connected"===n.status?(o="connected",r=n.tools.length):n&&"error"===n.status?(o="error",s=n.error):e.config.oauth&&(o=await hasTokens(e.name)?"authenticated":"requires_auth"),{name:e.name,config:e.config,scope:e.scope,status:o,toolCount:r,error:s}}));n(r)}catch{}finally{s(!1)}},"loadServers"),p=H(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),g=p[o]??null;Z((t,n)=>{n.ctrl&&"c"===t?e():n.escape?"actions"===a||"confirm-remove"===a?(l("list"),d(null)):e():"list"===a&&(n.upArrow&&(i(e=>Math.max(0,e-1)),d(null)),n.downArrow&&(i(e=>Math.min(p.length-1,e+1)),d(null)),n.return&&g&&(l("actions"),d(null)))});const h=__name(e=>{switch(e){case"connected":return B.createElement(Y,{color:Ln.GREEN},be.tick);case"authenticated":return B.createElement(Y,{color:Ln.CYAN},be.tick);case"requires_auth":return B.createElement(Y,{color:Ln.YELLOW},be.warning);case"error":return B.createElement(Y,{color:Ln.RED},be.cross);default:return B.createElement(Y,{color:Ln.GRAY},be.circle)}},"getStatusIcon"),f=__name(e=>{switch(e.status){case"connected":return"connected"+(void 0!==e.toolCount?` · ${e.toolCount} tools`:"");case"authenticated":return"authenticated · not connected";case"requires_auth":return"requires authentication";case"error":return e.error||"error";default:return"not connected"}},"getStatusText"),y=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),w=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),S=__name(async e=>{if(g)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)"remove"!==e.value||l("confirm-remove");else{if(!g.config.oauth)return void d({text:"No OAuth configured for this server",color:Ln.YELLOW});d({text:`Authenticating ${g.name}...`,color:Ln.CYAN,loading:!0});try{const e={authorizationUrl:g.config.oauth.authorizationUrl,tokenUrl:g.config.oauth.tokenUrl,clientId:g.config.oauth.clientId,clientSecret:g.config.oauth.clientSecret,scopes:g.config.oauth.scopes},t=await performOAuthFlow(g.name,e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`${be.tick} Authenticated with ${g.name}`,color:Ln.GREEN});try{const e=getMcpConnectionManager();await e.reconnectServer(g.name)}catch{}await m()}else d({text:`${be.cross} Auth failed: ${t.error}`,color:Ln.RED})}catch(e){d({text:`${be.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:Ln.RED})}}else{d({text:`Connecting ${g.name}...`,color:Ln.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.reconnectServer(g.name),d({text:`${be.tick} Connected to ${g.name}`,color:Ln.GREEN}),await m()}catch(e){d({text:`${be.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:Ln.RED})}}else d({text:"Already authenticated",color:Ln.GREEN});else d({text:"Already connected",color:Ln.GREEN});else l("list")},"handleActionSelect"),b=__name(async e=>{if(g)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===g.status&&await e.disconnectServer(g.name),await removeMcpServer({name:g.name,scope:g.scope}),l("list"),await m(),i(e=>Math.min(e,Math.max(0,p.length-2)))}catch(e){d({text:`${be.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:Ln.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Mn,bold:!0},"Manage MCP servers"),B.createElement(Y,{dimColor:!0},"Loading..."));if("confirm-remove"===a&&g)return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.RED,bold:!0},"Remove ",g.name,"?"),B.createElement(Y,{dimColor:!0},"This will remove the server from ",g.scope," config."),B.createElement(K,{marginTop:1},B.createElement(Ke,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:b,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY}," ",t)})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&g){const e=[];return"connected"===g.status?e.push({label:"Connected",value:"connected"}):e.push({label:"Connect",value:"connect"}),g.config.oauth&&("authenticated"===g.status||"connected"===g.status?e.push({label:"Authenticated",value:"authenticated"}):e.push({label:"Authenticate",value:"auth"})),e.push({label:"Remove",value:"remove"}),e.push({label:"Back",value:"back"}),B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Mn,bold:!0},g.name),B.createElement(K,null,h(g.status),B.createElement(Y,{dimColor:!0}," ",f(g))),B.createElement(K,{marginTop:1},B.createElement(Ke,{items:e,onSelect:S,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY}," ",t)})),u&&B.createElement(K,{marginTop:1},u.loading&&B.createElement(Y,{color:u.color},B.createElement(Se,{type:"dots"})," "),B.createElement(Y,{color:u.color},u.text)),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to go back")))}let E=null;return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Mn,bold:!0},"Manage MCP servers"),B.createElement(Y,{dimColor:!0},t.length," ",1===t.length?"server":"servers"),0===t.length?B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,{dimColor:!0},"No MCP servers configured."),B.createElement(Y,{dimColor:!0},'Use "cmd mcp add" to add a server.'),B.createElement(Y,{dimColor:!0},"Docs: https://commandcode.ai/docs/mcp")):B.createElement(K,{marginTop:1,flexDirection:"column"},p.map((e,t)=>{const n=e.scope!==E;E=e.scope;const r=t===o;return B.createElement(B.Fragment,{key:e.name},n&&B.createElement(K,{marginTop:0===t?0:1},B.createElement(Y,{bold:!0},y(e.scope)),B.createElement(Y,{dimColor:!0}," (",w(e.scope),")")),B.createElement(K,{paddingLeft:1},B.createElement(Y,{color:r?Ln.WHITE:Ln.GRAY},r?"› ":" "),B.createElement(Y,{color:r?Ln.WHITE:void 0,bold:r},e.name),B.createElement(Y,{dimColor:!0}," · "),h(e.status),B.createElement(Y,{color:"connected"===e.status?Ln.GREEN:"authenticated"===e.status?Ln.CYAN:"requires_auth"===e.status?Ln.YELLOW:Ln.GRAY}," ",f(e))))})),u&&B.createElement(K,{marginTop:1},u.loading&&B.createElement(Y,{color:u.color},B.createElement(Se,{type:"dots"})," "),B.createElement(Y,{color:u.color},u.text)),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Nt(),qE(),Ot(),un(),rr();var Ek=__name(({onClose:e})=>{const[t,n]=W([]),[r,s]=W(0),[o,i]=W(!0),[a,l]=W(null);G(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const u=__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(Z((t,n)=>{n.escape?e():n.upArrow?s(e=>Math.max(0,e-1)):n.downArrow?s(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&u(d[r]),"1"===t&&d[0]&&u(d[0]),"2"===t&&d[1]&&u(d[1]))}),o)return B.createElement(K,{paddingLeft:1,paddingTop:1},B.createElement(Y,{color:Ln.DIM},"Loading memory files..."));if(a)return B.createElement(K,{paddingLeft:1,paddingTop:1},B.createElement(Y,{color:Ln.RED},be.cross," ",a));const m=d.map((e,t)=>{const n=t+1;let r="",s="";return"project"===e.type?(r=`${n}. Project memory`,s=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,s=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:s}});return B.createElement(K,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:Ln.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},B.createElement(K,null,B.createElement(Y,{color:Ln.WHITE,bold:!0},"Select memory to edit:")),B.createElement(K,{columnGap:4,marginTop:1},B.createElement(K,{flexDirection:"column"},m.map((e,t)=>B.createElement(Y,{key:t,color:r===t?Ln.WHITE:Ln.DIM},r===t?`${sn} `:" ",e.label))),B.createElement(K,{flexDirection:"column"},m.map((e,t)=>B.createElement(Y,{key:t,color:r===t?Ln.WHITE:Ln.DIM},e.description)))))},"MemorySelector");Nt(),Nt();var Ck=rt()?"∴":"#";function AssistantMessage({content:e}){return B.createElement(K,null,B.createElement(Y,null,Ck),B.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Markdown,null,e)))}__name(AssistantMessage,"AssistantMessage"),Nt(),un(),rr();var vk={"Interrupted by user":"Interrupted by user","Insufficient credits":nn};function UserMessage({content:e,imageCount:t=0}){const n="Interrupted by user"===e,r="Insufficient credits"===e,s=e.startsWith("Error:"),o=n||r||s,i=o&&vk[e]||e;return B.createElement(K,{flexDirection:"column"},B.createElement(K,{backgroundColor:o?void 0:Qn.BG,paddingRight:1},B.createElement(Y,{color:o?Ln.RED:Qn.POINTER,bold:!o},be.pointer),B.createElement(K,{marginLeft:1},B.createElement(Y,{color:o?Ln.RED:Ln.WHITE,wrap:"wrap"},i))),t>0&&B.createElement(K,{marginLeft:1},B.createElement(Y,{dimColor:!0},"⎿"," ",Array.from({length:t},(e,t)=>`[Image #${t+1}]`).join(" "))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let s,o;return n?(s=Ln.YELLOW,o=be.arrowRight):r?(s=Ln.RED,o=be.cross):(s=Ln.GREEN,o=be.tick),B.createElement(K,null,B.createElement(Y,{color:s},o),B.createElement(K,{flexDirection:"column",marginLeft:1},B.createElement(K,null,B.createElement(Y,{color:Ln.GRAY},"$ "),B.createElement(Y,{color:s,bold:!0},e)),B.createElement(K,{columnGap:1,marginLeft:1},B.createElement(Y,null,"⎿"," "),B.createElement(Y,{color:r?Ln.RED:n?Ln.YELLOW:"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(UserMessage,"UserMessage"),Nt(),rr(),__name(BashMessage,"BashMessage"),Nt(),Nt(),Ot();rr(),Nt(),Ot();var Tk="Coding agent that continuously learns your taste of writing code.",kk=34,_k=[{key:"Shift+Tab",description:"Toggle mode (default → auto-accept → plan)"},{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:"Press Esc twice",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],Pk=[{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:"--plan",description:"Start in plan mode"},{key:"--permission-mode <mode>",description:"Set permission mode (standard, plan, auto-accept)"},{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"}],Ak=[{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 (Press Esc twice)"},{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:"/mcp",description:"Manage MCP server connections"},{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:"/review [pr]",description:"Review a pull request (optional PR number)"},{key:"/pr-comments",description:"Fetch all PR comments for current branch"},{key:"/add-dir",description:"Manage additional directory scope"},{key:"/help",description:"Display help information"},{key:"/exit",description:"Exit Command Code"}],xk=[{key:"cmd info",description:"Display system information"},{key:"cmd status",description:"Show authentication status"},{key:"cmd help",description:"Display help information"},{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 mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Ik=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Nk=[{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"}],Rk='Start with a prompt: cmd "fix the login bug"';Nt(),yr();var $k="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]:[$k]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||$k;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||$k}catch{return $k}}function HelpMessage(){const e=getInvokedCommandName(),t=H(()=>Ak.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return B.createElement(K,{flexDirection:"column",paddingY:1},B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(K,null,B.createElement(Y,{bold:!0},"Command Code"),B.createElement(Y,{color:Ln.GRAY}," v","0.17.2")),B.createElement(Y,{color:Ln.GRAY},Tk)),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Usage"),B.createElement(K,{paddingLeft:2},B.createElement(Y,null,e," <command> [options]"))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Options"),B.createElement(K,{flexDirection:"column",paddingLeft:2},Pk.map(t=>B.createElement(K,{key:t.key},B.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},t.description))))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Commands"),B.createElement(K,{flexDirection:"column",paddingLeft:2},xk.map(t=>B.createElement(K,{key:t.key},B.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},t.description))))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Slash Commands"),B.createElement(K,{flexDirection:"column",paddingLeft:2},t.map(e=>B.createElement(K,{key:e.key},B.createElement(Y,null,e.key.padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},e.description))))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Keyboard Shortcuts"),B.createElement(K,{flexDirection:"column",paddingLeft:2},_k.map(e=>B.createElement(K,{key:e.key},B.createElement(Y,null,e.key.padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},e.description))))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Examples"),B.createElement(K,{flexDirection:"column",paddingLeft:2},Nk.map(t=>B.createElement(K,{key:t.key},B.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},t.description))))),B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.CYAN},be.pointer),B.createElement(Y,{color:Ln.GRAY}," ",Rk.replace(/cmd/,e))),B.createElement(K,{flexDirection:"column"},B.createElement(Y,{bold:!0},"Links"),B.createElement(K,{flexDirection:"column",paddingLeft:2},Ik.map(e=>B.createElement(K,{key:e.key},B.createElement(Y,null,e.key.padEnd(kk)),B.createElement(Y,{color:Ln.CYAN},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?B.createElement(HelpMessage,null):B.createElement(K,{flexDirection:"column"},B.createElement(Y,{wrap:"wrap"},B.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return B.createElement(K,null,B.createElement(Y,{color:Ln.RED},t?be.pointer:be.warning),B.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?B.createElement(Y,{color:Ln.RED,wrap:"wrap"},e):B.createElement(Markdown,{color:Ln.RED},e)))}function AutoCompactMessage({content:e}){return B.createElement(K,null,B.createElement(Y,{dimColor:!0},be.info),B.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Y,{dimColor:!0},e)))}function TasteSkipMessage(){return B.createElement(K,null,B.createElement(K,{flexShrink:0},B.createElement(Y,{backgroundColor:On.BADGE_BG,color:On.BADGE_FG,bold:!0},`${cv}Taste${cv}`)),B.createElement(Y,{dimColor:!0}," ","Skipped. Run"," "),B.createElement(Y,{color:Yn.CODE},"/learn-taste"),B.createElement(Y,{dimColor:!0}," or "),B.createElement(Y,{color:Yn.CODE},"cmd learn-taste"),B.createElement(Y,{dimColor:!0}," anytime."))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?B.createElement(TasteSkipMessage,null):t?.isAutoCompact?B.createElement(AutoCompactMessage,{content:e}):B.createElement(K,null,B.createElement(Y,{dimColor:!0},be.info),B.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Y,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return B.createElement(K,{flexDirection:"column",marginBottom:0,marginTop:-1},B.createElement(K,{columnGap:1},B.createElement(Y,null,"⎿"," "),B.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Y,{color:n?Ln.YELLOW:void 0},e))),t&&B.createElement(K,{marginLeft:3},B.createElement(Y,{dimColor:!0},"See ",t)))}function IDEStatusMessage({status:e,ide:t,details:n}){return B.createElement(K,{flexDirection:"column"},B.createElement(K,null,"connected"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.GREEN},be.tick),B.createElement(Y,null," Connected to "),B.createElement(Y,{color:Ln.CYAN},t)),"installed"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.GREEN},be.tick),B.createElement(Y,null," Installed for "),B.createElement(Y,{color:Ln.CYAN},t)),"needs_reload"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.YELLOW},be.circle),B.createElement(Y,null," "),B.createElement(Y,{color:Ln.CYAN},t),B.createElement(Y,null," extension needs reload")),"failed"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.RED},be.cross),B.createElement(Y,null," Install failed")),"not_in_ide"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.YELLOW},be.circle),B.createElement(Y,null," Not in IDE"))),n?.map((e,t)=>B.createElement(Y,{key:t,dimColor:!0}," ",e)))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images.length:0;return B.createElement(UserMessage,{content:e.input,imageCount:t})}return"assistant"===e.role?B.createElement(AssistantMessage,{content:e.input}):"tool"===e.role?B.createElement(ToolMessage,{name:Qo(e.name||""),input:e.input,output:e.output||"",isPending:Bo(e),hasError:zo(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?B.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:Bo(e),hasError:zo(e)}):"system"===e.role?B.createElement(SystemMessage,{content:e.input}):"info"===e.role?B.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?B.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?B.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?B.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName(e){const t=Object.values(kt).find(t=>t.id===e);return t?t.name.toLowerCase().replace(" ","-"):e.includes("sonnet-4-6")?"sonnet-4.6":e.includes("sonnet")?"sonnet-4.5":e.includes("opus-4-6")?"opus-4.6":e.includes("opus")?"opus-4.5":"sonnet-4.6"}function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages (ctrl+e to expand more) `,r=Math.max(0,Math.floor((t-n.length)/2)),s="─".repeat(r);return B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},s,n,s))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),ir(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Jo(),Nt(),rr(),__name(ErrorMessage,"ErrorMessage"),Nt(),rr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(InfoMessage,"InfoMessage"),Nt(),rr(),__name(CommandResultMessage,"CommandResultMessage"),Nt(),rr(),__name(IDEStatusMessage,"IDEStatusMessage"),yr(),Ot(),ir(),rr(),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName,"getModelShortName"),__name(TranscriptDivider,"TranscriptDivider");var Lk=B.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:s,hiddenCount:o=0})=>{const i=o>0?{role:"transcript-divider",count:o}:null,a=[...t?["header"]:[],...i?[i]:[],...e],l=useTerminalWidth(),u=H(()=>BC(l),[l]),d=H(()=>getPackageJson().version||"0.0.0",[]),m=H(()=>getGitHeaderInfo(),[]),p=H(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),g=s?getModelShortName(s):"sonnet-4.5";return B.createElement(J,{items:a,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return B.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:l});if("header"===e)return B.createElement(K,{key:"header",marginBottom:1,flexDirection:"column"},B.createElement(Ze,{name:"vice"},B.createElement(Y,null,u.trimEnd())),B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(K,null,B.createElement(Y,{color:Wn},"# "),B.createElement(Y,{bold:!0},"Command Code"),B.createElement(Y,{color:Wn}," v",d)),B.createElement(Y,{color:Wn},"# models: ",g," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),B.createElement(K,null,B.createElement(Y,{color:Wn},"# ",p,m&&m.isLocal&&m.branch&&B.createElement(Y,{color:Wn}," (branch: ",m.branch,")")))));const t=e,n=renderFeedEntry(t,r);return B.createElement(K,{key:t.id,marginBottom:1,width:"90%"},n)})});Nt(),Jo(),ar(),rr();var Mk=U(__name(function LiveAgentStatusInner2({entry:e}){const t=Qo(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],s=r?r+(n.includes(".")||n.includes("\n")?".":""):n,o=e.metadata?.tokensUsed||0,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=W(".");return G(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),B.createElement(K,{flexDirection:"column",marginBottom:1,width:"90%"},B.createElement(K,null,B.createElement(Y,{backgroundColor:zn.BG,color:zn.FG,bold:!0},` ${t} `),s&&B.createElement(Y,null," ","(",s,")")),B.createElement(K,{columnGap:1,marginLeft:1},B.createElement(Y,null,"⎿"," "),B.createElement(Y,{color:Ln.GRAY},"Running (",formatTime2(i)," | ",formatTokens(o),")",l)),a.length>0&&B.createElement(K,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=Qo(e.name);return B.createElement(K,{key:t,columnGap:1},B.createElement(Y,{color:Ln.GRAY},"⎿"),B.createElement(Y,{color:Ln.GRAY}," ",n),e.input&&B.createElement(Y,{color:Ln.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),Ok=U(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:B.createElement(Mk,{entry:e})},"LiveAgentStatus"));function getModelOptions(){return Object.values(kt).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}Nt(),Ot(),rr(),__name(getModelOptions,"getModelOptions");var Dk=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),s=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0;return B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,null,B.createElement(Y,{color:Mn,bold:!0},"Select model")),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),B.createElement(Ke,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:e?Ln.GREEN:Ln.GRAY},e?be.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>{const s=r.find(e=>e.label===t),o=s?.value===n,i=e?Ln.GREEN:Ln.GRAY;return B.createElement(K,null,B.createElement(Y,{color:i},` ${(s?.label||t).padEnd(24)}`),B.createElement(Y,{dimColor:!0},s?.description),o&&B.createElement(Y,{color:Ln.GREEN}," ",be.tick))}}),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press "),B.createElement(Y,{dimColor:!0,bold:!0},"Esc"),B.createElement(Y,{dimColor:!0}," to cancel")))},"ModelSelector");Nt(),ir(),rr();var qk=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),s=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0,i=n&&-1===o;return B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},B.createElement(K,null,B.createElement(Y,{bold:!0},"Select AI Provider")),n&&B.createElement(K,{flexDirection:"row"},B.createElement(Y,{dimColor:!0},"Current: "),B.createElement(Y,{color:Ln.GREEN},getProviderDisplayName(n)),i&&B.createElement(Y,{color:Ln.YELLOW}," [OAuth enforced]"))),B.createElement(K,{marginBottom:0},B.createElement(Y,{dimColor:!0},"Available Providers:")),B.createElement(Ke,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:e?Ln.CYAN:Ln.GRAY,bold:e},e?be.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.CYAN:Ln.GRAY,bold:e},` ${t}`)}),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=W(0);if(G(()=>{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 B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Kn,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Nt(),rr(),__name(RetryMessage,"RetryMessage"),Nt(),Oi(),jr(),un(),rr();var Fk=[{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"}],jk=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=H(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[s,o]=W(Math.max(0,r.length-1)),[i,a]=W(Math.max(0,r.length-8)),[l,u]=W("checkpoint"),[d,m]=W(null),[p,g]=W(0),h=H(()=>{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]),f=H(()=>h?Fk:Fk.filter(e=>"conversation"===e.mode),[h]);if(G(()=>{if(r.length>0){const e=r.length-1;o(e),a(Math.max(0,r.length-8))}},[r.length,8]),Z((e,h)=>{h.escape?"mode"===l?(u("checkpoint"),m(null),g(0)):n():"checkpoint"===l?h.upArrow?o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):h.downArrow?o(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):h.return&&r.length>0&&(m(r[s]),u("mode"),g(0)):"mode"===l&&(h.upArrow?g(e=>Math.max(0,e-1)):h.downArrow?g(e=>Math.min(f.length-1,e+1)):h.return&&d&&f[p]&&t({messageId:d.messageId,mode:f[p].mode}))}),0===r.length)return B.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(Y,{color:Mn,bold:!0},"Rewind"),B.createElement(Y,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press "),B.createElement(Y,{dimColor:!0,bold:!0},"Esc"),B.createElement(Y,{dimColor:!0}," to close")));if("mode"===l&&d)return B.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(Y,{color:Mn,bold:!0},"Rewind"),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"Restore to: "),B.createElement(Y,{color:Ln.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),B.createElement(K,{flexDirection:"column"},f.map((e,t)=>{const n=p===t,r=t===f.length-1;return B.createElement(K,{key:e.mode,flexDirection:"column"},B.createElement(K,{flexDirection:"row"},B.createElement(Y,{color:n?Mn:void 0},n?`${sn} `:" "),B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:n?Mn:Ln.WHITE},e.label),B.createElement(Y,{dimColor:!0},e.description))),!r&&B.createElement(Y,null," "))})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press "),B.createElement(Y,{dimColor:!0,bold:!0},"Enter"),B.createElement(Y,{dimColor:!0}," to confirm, "),B.createElement(Y,{dimColor:!0,bold:!0},"Esc"),B.createElement(Y,{dimColor:!0}," to go back")));const y=r.slice(i,i+8);return B.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(Y,{color:Mn,bold:!0},"Rewind"),B.createElement(Y,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),B.createElement(K,{marginTop:1}),B.createElement(K,{flexDirection:"column"},y.map((e,t)=>{const n=i+t,o=s===n,a=e.filesModified.length,l=t===y.length-1,u=n===r.length-1;return B.createElement(K,{key:e.messageId,flexDirection:"column"},B.createElement(K,{flexDirection:"row"},B.createElement(Y,{color:o?Mn:void 0},o?`${sn} `:" "),B.createElement(K,{flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{color:o?Mn:Ln.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),B.createElement(Y,{dimColor:!0}," • "),B.createElement(Y,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),B.createElement(Y,{dimColor:!0},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&B.createElement(Y,null," "))})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press "),B.createElement(Y,{dimColor:!0,bold:!0},"Enter"),B.createElement(Y,{dimColor:!0}," to select, "),B.createElement(Y,{dimColor:!0,bold:!0},"Esc"),B.createElement(Y,{dimColor:!0}," to cancel")))},"RewindSelector");Nt(),$n(),Nt(),Nt(),tC();var zk=__name(e=>{const[t,n]=W(e),[r,s]=W(null);return G(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),s(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}):s(e.message)},"handleNewEvent");return ZE.on("reset",t),ZE.on("new-event",r),()=>{ZE.off("reset",t),ZE.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:s}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new Vb({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let s;if(n===Ct.ANTHROPIC)try{const e=await on.getValidAccessToken();validateOAuthToken({token:e,provider:n}),s=e}catch(e){dlog("Failed to get or validate Anthropic OAuth token:",e instanceof Error?e.message:String(e))}const o={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(o[wt.OAUTH_TOKEN]=`Bearer ${s}`),{request:t,headers:o}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const s of e){const e=estimateTokens(s);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([s])):r+e>2e3?(n.length>0&&t.push(n),n=[s],r=e):(n.push(s),r+=e)}return n.length>0&&t.push(n),t}Nt(),Nt(),gC(),bE(),ts(),$E(),$n(),tC(),Nt(),$n(),tC(),$E(),Nt(),Nt(),Ot(),bE(),ts(),dn(),CE(),$n(),nr(),ar(),__name(createRequestClient,"createRequestClient"),Nt(),$E(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Nt(),Nt(),Ot(),$n(),en(),tC(),Nt();var Bk="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 buildRequestBody2(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:`anthropic:${Bk}`,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}`),ZE.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()}`),ZE.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=je.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 ${St.ALPHA.GENERATE} with model: ${Bk}`);const r=buildRequestBody2(n);let s;try{s=await e.post({endpoint:St.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(s),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,s){let o=0;for(const e of n)o+=estimateTokens(e);dlog(`[Observer] batch ${r}/${s}: ${n.length} prompts`);const i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(ZE.observerHasRun)return;ZE.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 s=Math.min(r.length,6);for(let t=0;t<s;t++){if(ZE.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const s=r[t];try{await processBatch(e,n,s,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),ZE.addEvent({type:"progress",message:"Continuing without live observations..."})}}__name(buildObserverPrompt,"buildObserverPrompt"),__name(buildRequestBody2,"buildRequestBody"),__name(createInsightEmitter,"createInsightEmitter"),__name(processStream,"processStream"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var Uk=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(h.homedir(),".claude","projects");await $.access(r);const s=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${s}`);const o=(await $.readdir(r)).filter(e=>e===s);for(const s of o){const o=e.join(r,s);try{if(!(await $.stat(o)).isDirectory())continue;const r=(await $.readdir(o)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const s of r){const r=e.join(o,s),i=await $.stat(r),a=s.replace(".jsonl","");if(n.push({id:a,filePath:r,createdAt:i.birthtime,lastModified:i.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{ZE.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&ZE.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 $.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=[],s=0;for(const o of e){const e=estimateTokens(o);if(e>t){r.length>0&&(n.push(r),r=[],s=0);const e=this.splitLargePrompt(o,t);for(const t of e)n.push([t])}else s+e<=t?(r.push(o),s+=e):(r.length>0&&n.push(r),r=[o],s=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let s="",o=0;for(const e of r){const r=estimateTokens(e);o+r<=t?(s+=(s?"\n":"")+e,o+=r):(s&&n.push(s),s=e,o=r)}return s&&n.push(s),n}static async importAndLearn(){const e=[],t=[],n=[],r=[];try{ZE.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const s=await loadProjectSettings(),o=s.tasteOnboarding?.learnedSessions||{},i=o["claude-code"]?.length||0,a=o.codex?.length||0;dlog(`[Import] loaded settings: claude-code=${i} learned, codex=${a} learned`);const l=await findNewSessions(o),u=l["claude-code"]||[],d=l.codex||[],m=u.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${u.length} new, codex=${d.length} new`),0===m){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}`);ZE.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:n>0?`From ${r.join(" + ")} sessions`:"No sessions found for this project"});const s=[];return e.length>0&&s.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&s.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:n,learnedSessions:i+a,agentSessions:s,status:"already-learned"}}if(u.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>u.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 p=n.length+r.length;dlog(`[Import] total sessions: ${p} (claude-code: ${n.length}, codex: ${r.length})`),ZE.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){ZE.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 h=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${h.length} batches`);const f=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});ZE.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${h.length} batch${1===h.length?"":"es"}`});try{const s=getApiBaseUrl(),o=new Vb({baseUrl:s});let i=!0;for(let e=0;e<h.length;e++){const t=h[e],n=e+1,r=h.length;r>1&&ZE.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const s=this.formatBatchLearning(t),a=new rC({request:o,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:s}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await a.checkAndProcess({messages:l})).success||(i=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${i}`),ZE.markLearningComplete(),await f,i){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 a=await this.extractLearningSummary(),l=[];if(n.length>0&&l.push(`Claude Code (${n.length})`),r.length>0&&l.push(`Codex (${r.length})`),!i){const s="Learning failed - sessions not marked as learned";return e.push(s),ZE.addEvent({type:"error",message:s}),{success:!1,totalPrompts:t.length,preferencesLearned:a.totalLearnings,errors:e,totalSessions:p,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 ZE.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${l.join(" + ")}`,learningCount:a.totalLearnings,categories:a.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:a.totalLearnings,errors:e,totalSessions:p,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),ZE.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 $.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),s=r?r.length:0;return{totalLearnings:s,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")}};tC();var Wk=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),Qk=__name(e=>{const[t,n]=W({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return G(()=>{ZE.reset(),ZE.markImportStarted(),(async()=>{try{const t=await Promise.race([Uk.importAndLearn(),Wk(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");Nt();var Gk=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{Z((r,s)=>{n&&(s.escape&&e(),(s.return||"\n"===r)&&t())})},"useKeyboardInput");Nt(),$n();var Hk=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=W(null),[s,o]=W(null),i=Q(!1);return G(()=>{if(i.current)return;let n=null;return(async()=>{try{i.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),o(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:s,isLoading:!n&&!s}},"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{ZE.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{ZE.reset(),e()}}Nt(),$n(),Nt(),$n(),tC(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var Vk=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=Q(n),s=V(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),o=V(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=V(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=V(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=V(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:s,handleImportComplete:o,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Nt(),$n();var Kk=__name(({conditions:e,autoLearn:t})=>{const[n,r]=W("checking"),s=Q(!1);return G(()=>{if(e&&!s.current){if(s.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),G(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Nt(),Nt(),rr();var Yk=__name(({error:e})=>B.createElement(K,{padding:1},B.createElement(K,{flexDirection:"column",borderColor:Ln.RED,padding:1},B.createElement(K,{marginBottom:1},B.createElement(Y,null,"Error initializing onboarding: ",e)),B.createElement(K,null,B.createElement(Y,null,"Continuing without onboarding...")))),"OnboardingError");Nt(),Nt(),Ot(),rr();var Jk=__name(()=>`(run /${Tt.LEARN_TASTE} anytime)`,"getSkipHint"),Xk=__name(()=>B.createElement(Y,null,"Skip for now"," ",B.createElement(Y,{dimColor:!0},Jk())),"SkipOptionText"),Zk=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[s,o]=W(1);return Z((e,t)=>{t.escape?r():t.upArrow||t.downArrow?o(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===s?n():r()):r():n()}),B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:On.TEXT,paddingX:1,paddingY:0},B.createElement(Y,{color:On.TEXT,bold:!0},"Build Your Coding Taste"),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),B.createElement(K,{marginTop:1},B.createElement(Y,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{color:1===s?On.TEXT:Ln.GRAY},1===s?be.pointer:" "," 1. Yes, learn from my sessions (recommended)")),B.createElement(K,null,B.createElement(Y,{color:2===s?On.TEXT:Ln.GRAY},2===s?be.pointer:" "," 2."," ",B.createElement(Xk,null)))),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice");Nt(),Nt(),rr();var e_=__name(({error:e})=>B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.RED,paddingX:2,paddingY:1,marginBottom:2},B.createElement(Y,{color:Ln.RED,bold:!0},"Oops, something went wrong:"),B.createElement(K,{marginTop:1},B.createElement(Y,null,e))),"ErrorSection");Nt(),Nt(),rr(),Nt(),Nt(),Nt(),rr();var t_=[be.bullet,be.squareSmallFilled,be.lozenge,be.star,be.triangleRight,be.triangleUp,be.circleFilled,be.pointer],n_=__name(()=>B.createElement(Y,{backgroundColor:On.BADGE_BG,color:On.BADGE_FG},`${cv}TASTE${cv}`),"TasteBadge"),r_=["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"],s_=__name(()=>{const[e,t]=W(()=>Math.floor(Math.random()*r_.length));G(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*r_.length))},2e3);return()=>clearInterval(e)},[]);const n=r_[e];return B.createElement(Y,{color:Ln.YELLOW},n,"...")},"PulsingText"),o_=__name(e=>String(e).padStart(3," "),"padNum"),i_=__name(e=>t_[e%t_.length],"getSymbol"),a_=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${o_(t)} ↓${o_(n)} (↑↓ scroll)`,"buildStatusLine"),l_=__name(({insights:e})=>{const[t,n]=W(0),[r,s]=W(!0),o=e.length,i=o>10,a=Math.max(0,o-10);if(G(()=>{r&&i&&n(a)},[o,r,i,a]),Z((e,t)=>{if(i)return t.upArrow?(s(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&s(!0),t}))}),0===o)return null;const l=e.slice(t,t+10),u=t,d=o-t-10;return B.createElement(K,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&B.createElement(Y,{dimColor:!0},a_(o,u,d,r)),l.map((e,n)=>{const r=t+n;return B.createElement(K,{key:r,marginBottom:0},B.createElement(Y,{dimColor:!0},i_(r)," ",e))}))},"ScrollableInsights"),c_=__name(({label:e,message:t,active:n,complete:r,items:s,insights:o,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return B.createElement(K,{flexDirection:"column",marginBottom:0},B.createElement(n_,null),B.createElement(K,{marginTop:0},B.createElement(Y,{dimColor:!0},"⎿"),B.createElement(K,{marginLeft:2},a?B.createElement(Y,{color:On.TEXT},"learned your coding taste"):B.createElement(s_,null))));const u=__name(()=>{const[e,t]=W(!0);return G(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),B.createElement(Y,{color:Ln.YELLOW},e?be.circleFilled:be.circle)},"PulsingDot"),d=__name(()=>r?B.createElement(Y,{color:On.TEXT},be.nodejs):n?B.createElement(u,null):B.createElement(Y,{dimColor:!0},be.circle),"getStatusIcon"),m=s.length>0||o.length>0||t||l&&l.learningCount>0;return!r||n||m?B.createElement(K,{flexDirection:"column",marginBottom:0},(n||r)&&B.createElement(K,{marginBottom:0},B.createElement(K,{marginRight:1},d()),B.createElement(Y,{color:r?Ln.WHITE:n?Ln.YELLOW:Ln.DIM},e)),r&&t&&(!l||0===l.learningCount)&&B.createElement(K,{marginLeft:3,marginBottom:0},B.createElement(Y,{dimColor:!0},t)),s.length>0&&B.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},s.map((e,t)=>B.createElement(Y,{key:t,dimColor:!0},`${be.bullet} ${e}`))),o.length>0&&B.createElement(l_,{insights:o}),r&&l&&l.learningCount>0&&B.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},B.createElement(K,{marginBottom:1,flexDirection:"row"},B.createElement(Y,null,"⎿"),B.createElement(K,{marginLeft:2},B.createElement(Y,{color:On.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),B.createElement(K,{flexDirection:"column",marginLeft:1},B.createElement(Y,{dimColor:!0},be.pointerSmall," Stored in"," ",l.storage),B.createElement(Y,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),u_=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return B.createElement(K,{flexDirection:"column",marginBottom:1},e.map((e,n)=>B.createElement(K,{key:e.id,marginLeft:0===n?0:3},B.createElement(c_,{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"),d_=__name(({steps:e})=>B.createElement(u_,{steps:e}),"ProgressSection");Nt();var m_=__name(({isImporting:e=!1,waitingForInput:t=!1})=>B.createElement(B.Fragment,null,e&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"ESC to cancel")),t&&B.createElement(K,{marginTop:1},B.createElement(Y,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Nt();var p_=[{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"}}],g_=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:s}=zk(p_),{isImporting:o,waitingForInput:i,error:a}=Qk(t);return Gk({onEscape:e,onEnter:__name(()=>{i&&(a&&n?n():e())},"onEnter"),enabled:o||i}),B.createElement(K,{flexDirection:"column",padding:1},s&&B.createElement(e_,{error:s}),!s&&B.createElement(d_,{steps:r}),B.createElement(m_,{isImporting:o,waitingForInput:i}))},"ImportProgress"),h_=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:s,onErrorDismiss:o,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?B.createElement(Zk,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?B.createElement(g_,{onComplete:r,onError:s,onErrorDismiss:o}):null,"OnboardingStepRenderer"),f_=__name(({onComplete:e,autoLearn:t=!1})=>{G(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:s}=Hk({autoLearn:t,onShouldSkip:e}),{step:o,setStep:i}=Kk({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=Vk({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${o}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),s?null:r?B.createElement(Yk,{error:r}):"done"===o?null:B.createElement(h_,{step:o,conditions:n,onImportStart:a,onImportComplete:l,onImportError:u,onErrorDismiss:d,onSkip:m})},"TasteOnboarding");function getEntryCharCount(e){return("input"in e?e.input??"":"").length+("output"in e?e.output??"":"").length+("command"in e?e.command??"":"").length}function getBudgetedFeed(e,t){if(0===e.length)return[];const n=[...e].reverse();let r=t;const s=[];for(const e of n)if(s.unshift(e),r-=getEntryCharCount(e),r<=0)break;return s}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var y_=U(__name(function MainView2({feed:e,liveAgents:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:s,transcriptMode:o,tasteOnboardingEntryId:i,autoLearnTaste:a,retryAttempt:l,input:u,setInput:d,fileSearchQuery:m,setFileSearchQuery:p,showFileList:g,setShowFileList:h,showProviderSelector:f,showModelSelector:y,showMemorySelector:w,showMcpManager:S,showAgentsConfig:b,showRewindSelector:E,showLoginOverlay:C,showAddDirModal:v,authComponentInfo:T,status:k,currentProvider:_,currentModel:P,showProviderNotification:A,shareInfo:x,showShareNotification:I,unshareNotificationMessage:N,updateStatus:R,updateFailedInfo:$,permissionMode:L,hintMessage:M,pendingExitKey:O,tasteLearningEnabled:D,interactionTokens:q,contextUsage:F,historyManagerRef:j,executionState:z,contextEngineRef:U,onSubmit:W,onCommand:Q,onToggleAutoAccept:G,onResetPendingExitKey:J,onDoubleEscapeEmpty:X,onTasteOnboardingComplete:Z,permissionPanel:ee,questionPanel:te,onRewindSelect:ne,onRewindCancel:re,onLoginComplete:se,onLoginCancel:oe,setShowProviderSelector:ie,setShowModelSelector:ae,setShowMemorySelector:le,setShowMcpManager:ce,setShowAgentsConfig:ue,setShowAddDirModal:de,handleProviderSelect:me,handleProviderCancel:pe,handleModelSelect:ge,handleModelCancel:he,handleAuthSuccess:fe,handleAuthCancel:ye}){const we=H(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Se=useTerminalWidth(),{placeholder:be,isPrediction:Ee,onAccepted:Ce}=usePredictedPlaceholder({contextEngineRef:U,isCmdCodeBusy:r}),ve=H(()=>"off"===o?we:getBudgetedFeed(we,"limited"===o?15e3:5e4),[we,o]),Te=H(()=>"off"===o?0:Math.max(0,we.length-ve.length),[we.length,ve.length,o]),ke=H(()=>0===Te?ve:ve.filter(e=>"user"!==e.role),[ve,Te]),_e=V(()=>ue(!1),[ue]),Pe=V(()=>le(!1),[le]),Ae=V(()=>ce(!1),[ce]),xe=V(()=>de(!1),[de]),Ie=V(()=>ae(!0),[ae]),Ne=!("off"!==o||ee||te||f||y||T||w||S||b||E||C||v||i);return B.createElement(K,{flexDirection:"column",width:"100%"},B.createElement(Lk,{staticKey:s,feed:ke,showHeader:!0,expandedToolOutput:"off"!==o,currentModel:P,hiddenCount:Te}),i&&B.createElement(f_,{onComplete:Z,autoLearn:a}),t.map(e=>B.createElement(Ok,{key:e.id,entry:e})),B.createElement(RetryMessage,{attempt:l}),te,ee,"off"!==o&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(K,null,B.createElement(Y,{dimColor:!0},"─".repeat(Se))),B.createElement(K,{paddingRight:1},B.createElement(Y,{backgroundColor:jn.BG,color:jn.FG,bold:!0},`${cv}DETAILED TRANSCRIPT${cv}`),B.createElement(Y,{dimColor:!0}," · "),B.createElement(Y,{bold:!0},"ctrl+o"),B.createElement(Y,{dimColor:!0}," to toggle"),B.createElement(Y,{dimColor:!0}," · "),B.createElement(Y,{bold:!0},"ctrl+e"),B.createElement(Y,{dimColor:!0}," ","to"," ","limited"===o?"show all":"collapse"))),Ne&&B.createElement(wk,{queuedMessages:n,isProcessing:r,executionState:z,status:k,input:u,setInput:d,onSubmit:W,showFileList:g,setShowFileList:h,fileSearchQuery:m,setFileSearchQuery:p,onCommand:Q,outputTokens:q,contextUsage:F,tasteLearning:D,shareInfo:x,showShareNotification:I,unshareNotificationMessage:N,updateStatus:R,updateFailedInfo:$,currentProvider:_,showProviderInfo:A,permissionMode:L,onToggleAutoAccept:G,hintMessage:M,historyManager:j.current,pendingExitKey:O,onResetPendingExitKey:J,onDoubleEscapeEmpty:X,retryAttempt:l,onAltP:Ie,placeholder:be,isPlaceholderPrediction:Ee,onPlaceholderAccepted:Ce}),f&&B.createElement(K,{marginY:1},B.createElement(qk,{onSelect:me,onCancel:pe,currentProvider:_})),y&&B.createElement(K,{marginY:1},B.createElement(Dk,{onSelect:ge,onCancel:he,currentModel:P})),b&&B.createElement(K,{marginY:1},B.createElement(jT,{onCancel:_e})),w&&B.createElement(K,{marginY:1},B.createElement(Ek,{onClose:Pe})),S&&B.createElement(K,{marginY:1},B.createElement(bk,{onClose:Ae})),E&&U.current&&B.createElement(K,{marginY:1},B.createElement(jk,{checkpoints:U.current.listCheckpoints(),onSelect:ne,onCancel:re})),T&&B.createElement(K,{marginY:1},B.createElement(T.Component,{onSuccess:fe,onCancel:ye})),C&&B.createElement(K,{marginY:1},B.createElement(Sk,{onComplete:se,onCancel:oe})),v&&B.createElement(K,{marginY:1},B.createElement(TT,{onClose:xe})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,onboarding:o,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:p,onSubmit:g,onCommand:h,input:f,setInput:y,fileSearchQuery:w,setFileSearchQuery:S,updateFailedInfo:b,handleTrust:E,handleNoTrust:C,handleToggleAutoAccept:v,handleDoubleEscapeEmpty:T,handleTasteOnboardingComplete:k,loadTasteStatus:_}){if(i.shouldExit)return null;if(o.checkingProject)return null;if(o.showTrustPrompt)return B.createElement(sT,{staticKey:s.staticKey,onTrust:E,onExit:C});if(s.showSessionSelector)return B.createElement(iT,{onSelectSession:p.onSelectSession,onNewSession:p.onNewSession});if(!o.projectTrusted)return null;const P=a.pendingQuestion?B.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:s.setStaticKey}):null,A=a.pendingPermission?B.createElement(fT,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:v}):null;return s.showLearningFeed?B.createElement(LearningView,{setShowLearningFeed:s.setShowLearningFeed,setStaticKey:s.setStaticKey,onExit:()=>i.setShouldExit(!0)}):s.showTasteConfig?B.createElement(TasteConfigView,{staticKey:s.staticKey,setShowTasteConfig:s.setShowTasteConfig,loadTasteStatus:_}):s.showSkillsConfig?B.createElement(SkillsConfigView,{staticKey:s.staticKey,setShowSkillsConfig:s.setShowSkillsConfig}):B.createElement(y_,{feed:e.feed,liveAgents:e.liveAgents,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:s.staticKey,transcriptMode:s.transcriptMode,tasteOnboardingEntryId:o.tasteOnboardingEntryId,autoLearnTaste:o.autoLearnTaste,retryAttempt:n.retryAttempt,input:f,setInput:y,fileSearchQuery:w,setFileSearchQuery:S,showFileList:s.showFileList,setShowFileList:s.setShowFileList,showProviderSelector:s.showProviderSelector,showModelSelector:s.showModelSelector,showMemorySelector:s.showMemorySelector,showMcpManager:s.showMcpManager,showAgentsConfig:s.showAgentsConfig,showRewindSelector:s.showRewindSelector,showLoginOverlay:s.showLoginOverlay,showAddDirModal:s.showAddDirModal,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:b,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:g,onCommand:h,onToggleAutoAccept:v,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:T,onTasteOnboardingComplete:k,permissionPanel:A,questionPanel:P,onRewindSelect:p.onRewindSelect,onRewindCancel:p.onRewindCancel,onLoginComplete:p.onLoginComplete,onLoginCancel:p.onLoginCancel,setShowProviderSelector:s.setShowProviderSelector,setShowModelSelector:s.setShowModelSelector,setShowMemorySelector:s.setShowMemorySelector,setShowMcpManager:s.setShowMcpManager,setShowAgentsConfig:s.setShowAgentsConfig,setShowRewindSelector:s.setShowRewindSelector,setShowLoginOverlay:s.setShowLoginOverlay,setShowAddDirModal:s.setShowAddDirModal,handleProviderSelect:p.handleProviderSelect,handleProviderCancel:p.handleProviderCancel,handleModelSelect:p.handleModelSelect,handleModelCancel:p.handleModelCancel,handleAuthSuccess:p.handleAuthSuccess,handleAuthCancel:p.handleAuthCancel})}__name(renderView,"renderView");var w_=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:s,updateFailedInfo:o,initialPrompt:i,skipOnboarding:a=!1,initialPermissionMode:l})=>{const{exit:u}=te(),{stdout:d}=X(),[m,p]=W(""),[g,h]=W(""),f=Q(!1),y=Q(!1),w=Q(null),S=Q(null),b=useUiOverlays(),E=useFeed(),C=useSession(),v=useStatus(s),T=useAuth(),k=usePendingOps(),_=useOnboarding(),P=useExit(),{executeBash:A,executionState:x}=tv(),I=usePermissionMode({initialPermissionMode:l,dangerouslySkipPermissions:r,setPendingPermission:k.setPendingPermission,setStatus:v.setStatus,contextEngineRef:S}),{createContextEngineCallbacks:N}=useContextEngine({sessionId:C.sessionId,sessionLoaded:C.sessionLoaded,showSessionSelector:b.showSessionSelector,projectTrusted:_.projectTrusted,setFeed:E.setFeed,setLiveAgents:E.setLiveAgents,setQueuedMessages:E.setQueuedMessages,queuedMessagesRef:E.queuedMessagesRef,setStatus:v.setStatus,pinnedStatusRef:v.pinnedStatusRef,setRetryAttempt:v.setRetryAttempt,setInteractionTokens:v.setInteractionTokens,setContextUsage:v.setContextUsage,setCurrentProvider:T.setCurrentProvider,shareInfoRef:v.shareInfoRef,permissionsService:I.permissionsService,permissionModeRef:I.permissionModeRef,setPendingQuestion:k.setPendingQuestion,contextEngineRef:S}),{loadTasteStatus:R,loadCurrentProvider:$,onSubmit:L}=useStartup({resume:e,continueLatest:t,trust:n,initialPrompt:i,stdout:d,feedState:E,sessionState:C,statusState:v,authState:T,onboarding:_,uiOverlays:b,permissionState:I,contextEngineRef:S,isSubmittingRef:f,initialPromptSubmittedRef:y,historyManagerRef:w,executeBash:A,createContextEngineCallbacks:N,setInput:p});useLifecycle({exit:u,feedState:E,exitState:P,statusState:v,authState:T,onboarding:_,uiOverlays:b,skipOnboarding:a});const{handleToggleAutoAccept:M,handleDoubleEscapeEmpty:O,handleTasteOnboardingComplete:D,handleTrust:q,handleNoTrust:F}=useHandlers({resume:e,feedState:E,onboarding:_,uiOverlays:b,exitState:P,pendingOps:k,permissionState:I,statusState:v,authState:T,contextEngineRef:S,loadTasteStatus:R,loadCurrentProvider:$,setInput:__name(e=>p(e),"setInput")}),{onCommand:j}=useCommandCtx({feedState:E,sessionState:C,statusState:v,uiOverlays:b,onboarding:_,exitState:P,permissionState:I,contextEngineRef:S,isSubmittingRef:f,executeBash:A,createContextEngineCallbacks:N,setInput:p});return renderView({feedState:E,sessionState:C,statusState:v,authState:T,uiOverlays:b,onboarding:_,exitState:P,pendingOps:k,permissionState:I,contextEngineRef:S,historyManagerRef:w,executionState:x,actionCallbacks:useMainActionCallbacks({feedState:E,sessionState:C,statusState:v,authState:T,uiOverlays:b,permissionState:I,contextEngineRef:S,createContextEngineCallbacks:N,setInput:p}),onSubmit:L,onCommand:j,input:m,setInput:p,fileSearchQuery:g,setFileSearchQuery:h,updateFailedInfo:o,handleTrust:q,handleNoTrust:F,handleToggleAutoAccept:M,handleDoubleEscapeEmpty:O,handleTasteOnboardingComplete:D,loadTasteStatus:R})},"InteractiveCLI");Nn(),Sn(),CE();var S_=__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"),b_=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),E_=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),C_=__name(({options:e})=>{let t;return e.permissionMode?t=e.permissionMode:e.plan&&(t="plan"),{resume:e.resume,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:t}},"buildInteractiveCLIProps"),v_=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),T_=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),k_=__name(()=>{T_()},"initializeTerminal"),__=__name(async(e={})=>{const t=S_(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),k_(),b_(e)){const e=await Yb.isProjectInitialized(),t=e?await Yb.listSessions():[],n=E_({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=C_({options:e}),r=v_();ee(B.createElement(w_,{...n}),r)},"interactiveMode");Nt(),Es(),bE(),ts(),Ot(),Gs(),dn(),nr(),ar(),en(),qE(),SC(),gi(),JE(),CE(),hi();var P_=null,A_=!1,x_=new Set([Is.EDIT_FILE,Is.WRITE_FILE,Is.SHELL_COMMAND]);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(A_)return;A_=!0;const e=__name(e=>{P_?.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(),P_=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));try{const n=await processQuery({query:t,signal:P_.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 ii&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof ai&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof di&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof si&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof mi&&(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 I_=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===Ct.ANTHROPIC&&(r=await on.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const s=getEnvironmentContext(),o=await getMemoryContent([]),i=await getTasteContent(),a=generateSkillsXML(await loadAllSkillSummaries())||null,l=crypto.randomUUID(),u=await isTasteLearningEnabled(),d={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.TASTE_LEARNING]:u.toString(),[wt.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(d[wt.OAUTH_TOKEN]=`Bearer ${r}`),{tools:e,config:s,memory:o,taste:i,skills:a,headers:d,sessionId:l}}async function callApi(e,t,n,r){const s={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:`anthropic:${getConfiguredModel()}`},o={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:s,threadId:t.sessionId},i=await e.post({body:o,stream:!0,endpoint:St.ALPHA.GENERATE,headers:t.headers,signal:r});return je.fromReadableStream(i).finalMessage()}async function executeToolCall(e,t,n){if(x_.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 ii||t instanceof ai||t instanceof di||t instanceof si||t instanceof mi)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,s=getApiBaseUrl(),o=new Vb({baseUrl:s}),i=[{role:"user",content:t}],a=await setupConversationContext();let l=0,u="";for(;l<I_;){if(l++,n.aborted)throw new Error("Cancelled");const e=await callApi(o,a,i,n),t=e.content.filter(e=>"text"===e.type),s=e.content.filter(e=>"tool_use"===e.type),d=t.map(e=>e.text).join("");if(d&&(u+=d),0===s.length)break;const m=[];for(const e of s){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);m.push(t)}i.push({role:"assistant",content:e.content}),i.push({role:"user",content:m})}return l>=I_&&process.stderr.write(`Warning: Reached maximum conversation turns (${I_}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),u}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery"),zt();var N_=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),R_=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),$_=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),e.plan&&(t.plan=!0),e.permissionMode&&(t.permissionMode=e.permissionMode),t},"buildRuntimeOptions"),L_=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),M_=__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=M_(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=N_(e);await R_();const r=$_(t),s=L_({options:t,runtimeOptions:r,initialPrompt:n});__(s)}__name(interactiveModeAction,"interactiveModeAction"),Nt(),$n(),Vr(),globalThis.COMMAND_CODE_CWD=process.cwd();var O_=__name(()=>process.cwd(),"getCwd"),D_=__name(()=>process.argv.slice(2),"getArgs"),q_=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),F_=__name(()=>{const e=O_(),t=D_(),n=q_(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){F_(),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"),Nt(),Ot(),$n(),yr(),ir();var j_=getPackageJson(),z_=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=j_.version,t=getInvokedCommandName(),n=Ak.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(Be.bold("Command Code")+Be.gray(` v${e}`)),console.log(Be.gray(Tk)),console.log(),console.log(Be.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(Be.bold("Options"));for(const e of Pk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(kk)+Be.gray(e.description))}console.log(),console.log(Be.bold("Commands"));for(const e of xk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(kk)+Be.gray(e.description))}console.log(),console.log(Be.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(kk)+Be.gray(e.description));console.log(),console.log(Be.bold("Keyboard Shortcuts"));for(const e of _k)console.log(" "+e.key.padEnd(kk)+Be.gray(e.description));console.log(),console.log(Be.bold("Examples"));for(const e of Nk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(kk)+Be.gray(e.description))}console.log(),console.log(Be.cyan("❯")+" "+Be.gray(Rk.replace(/cmd/,t))),console.log(),console.log(Be.bold("Links"));for(const e of Ik)console.log(" "+e.key.padEnd(kk)+Be.cyan(e.description));console.log()}function createProgram(){const e=new Ae;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(j_.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("--plan","Start in plan mode (read-only exploration and planning)").addOption(new xe("--permission-mode <mode>","Set permission mode").choices(["standard","plan","auto-accept"])).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",z_,[]).addOption(new xe(ft).hideHelp()).addOption(new xe(yt).hideHelp()).addOption(new xe("-d, --debug","Enable debug mode").hideHelp()).addOption(new xe("--local","Use local server").hideHelp()).addOption(new xe("--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 s=t.opts(),o=Object.entries(s).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");o&&dlog(`[cmd] options: ${o}`);const i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Nt(),Vr(),Jr(),AC();var B_=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=h.platform(),n=h.arch();let r,s,o,i;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,s=e.user?.id,o=e.org?.login,i=e.org?.id)}catch{}if(!s)try{const e=await loadCredentials();s=e?.userId}catch{}systemInfo({userName:r,userId:s,orgLogin:o,orgId:i,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(){B_||(B_=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Ie("Opening GitHub issues...").start();try{await ie(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"),Qs(),Nt(),__name(openGitHubIssue,"openGitHubIssue");var U_=new Ae("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Nt();var W_=new Ae("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const{waitUntilExit:t}=ee(B.createElement(Qv,{verbose:e.verbose,text:e.text}));await t()}Nt(),Nt(),__name(runInfo,"runInfo");var Q_=new Ae("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=>{await runInfo(e)});function runLearnTaste(){const{unmount:e}=ee(B.createElement(g_,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}Nt(),Ot(),Nt(),__name(runLearnTaste,"runLearnTaste"),$n(),Vr();var G_=new Ae(Tt.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:Br.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 addMcpCommand(){const e=new Ae("add");return e.description("Add an MCP server").argument("<name>","Server name (unique identifier)").argument("[url]","Server URL (required for http transport)").option("-t, --transport <type>","Transport type (stdio or http)","stdio").addOption(new xe("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("-e, --env <KEY=value>","Environment variable (repeatable)",collectKeyValue,{}).option("-H, --header <header>","HTTP header (repeatable, http only)",collectHeaders,{}).allowUnknownOption().allowExcessArguments().action(async(e,t,n,r)=>{const s=getInvokedCommandName();try{let o;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(Be.red(`Error: Invalid server name '${e}'`)),console.error(Be.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1)),"stdio"!==n.transport&&"http"!==n.transport&&(console.error(Be.red(`Error: Invalid transport type '${n.transport}'`)),console.error(Be.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(Be.red("Error: URL is required for http transport")),console.error(Be.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(Be.red(`Error: Invalid URL '${t}'`)),process.exit(1)}o={transport:"http",enabled:!0,url:t,...Object.keys(n.header).length>0&&{headers:n.header},...Object.keys(n.env).length>0&&{env:n.env}},console.log(Be.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(Be.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(Be.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(Be.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${no}/callback`]});e&&(n=e.clientId,t=e.clientSecret)}o.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},console.log(Be.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(Be.gray(` ${e}`))},"onStatus")});s.success?console.log(Be.green("✓ Successfully authenticated")):(i=!0,console.log(Be.yellow(`Warning: Authentication failed: ${s.error}`)),console.log(Be.gray("You can retry with: cmd mcp auth "+e)),console.log(Be.gray("Or authenticate via the /mcp menu in a session")))}}else{const s=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(Be.red("Error: Command is required for stdio transport")),console.error(Be.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),a=e[0],l=e.slice(1)}else if(t){a=t;const n=s.indexOf(e);-1!==n&&s.length>n+2&&(l=s.slice(n+2))}else console.error(Be.red("Error: Command is required for stdio transport")),console.error(Be.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(Be.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);o={transport:"stdio",enabled:!0,command:a,...l.length>0&&{args:l},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:o,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(Be.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(Be.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===o.transport)console.log(Be.gray(` URL: ${o.url}`));else{const e=[o.command,...o.args||[]].join(" ");console.log(Be.gray(` Command: ${e}`))}console.log(""),console.log(Be.cyan("Next steps:")),console.log(Be.gray(`Start ${s} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function collectKeyValue(e,t){const[n,...r]=e.split("=");return n&&0!==r.length||(console.error(Be.red(`Error: Invalid format '${e}', expected KEY=value`)),process.exit(1)),t[n]=r.join("="),t}function collectHeaders(e,t){const n=e.indexOf(":");-1===n&&(console.error(Be.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),s=e.substring(n+1).trim();return r||(console.error(Be.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=s,t}function listMcpCommand(){const e=new Ae("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(Be.yellow("\nNo MCP servers configured\n")),console.log(Be.gray("Add a server with:")),console.log(Be.gray(" cmd mcp add --transport http <name> <url>")),console.log(Be.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(Be.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(Be.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(Be.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const s of e){const e=s.config.enabled?Be.green("enabled"):Be.gray("disabled");let o;o=s.config.oauth?await hasTokens(s.name)?Be.green(be.tick):Be.red(be.cross):s.config.headers||s.config.env?Be.green(be.tick):Be.gray("-"),console.log(` ${Be.white(s.name.padEnd(t))} ${Be.cyan(s.config.transport.padEnd(n))} ${Be.gray(s.scope.padEnd(r))} ${o} ${e}`)}console.log(Be.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new Ae("get");return e.description("Show details for an MCP server").argument("<name>","Server name").action(async e=>{try{const t=await getMcpServer({name:e});t||(console.error(Be.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(Be.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${Be.dim("Scope:")} ${r}`),console.log(` ${Be.dim("Transport:")} ${n.transport}`),console.log(` ${Be.dim("Status:")} ${n.enabled?Be.green("enabled"):Be.gray("disabled")}`),"http"===n.transport){if(console.log(` ${Be.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${Be.dim("Headers:")}`);for(const[e,t]of Object.entries(n.headers)){const n=e.toLowerCase().includes("auth")||e.toLowerCase().includes("token")||e.toLowerCase().includes("key")?"***":t;console.log(` ${e}: ${n}`)}}}else console.log(` ${Be.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${Be.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${Be.dim("Environment:")}`);for(const[e,t]of Object.entries(n.env)){const n=e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token")||e.toLowerCase().includes("password")?"***":t;console.log(` ${e}=${n}`)}}console.log("")}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Ae("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new xe("-s, --scope <scope>","Scope to remove from (auto-detects if not specified)").choices(["local","project","user"])).action(async(e,t)=>{try{const n=await getMcpServer({name:e});n||(console.error(Be.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(Be.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(Be.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const s="user"===r?"global":"project"===r?"project":"local";console.log(Be.green(`✓ Removed MCP server '${e}' from ${s} config`))}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new Ae("add-json");return e.description("Add an MCP server from JSON configuration").argument("<name>","Server name (unique identifier)").argument("<json>","Server configuration as JSON string").addOption(new xe("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("--client-secret <secret>","OAuth client secret (injected into oauth config)").action(async(e,t,n)=>{const r=getInvokedCommandName();try{let s,o;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(Be.red(`Error: Invalid server name '${e}'`)),console.error(Be.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{s=JSON.parse(t)}catch{console.error(Be.red("Error: Invalid JSON")),console.error(Be.gray("Make sure to quote the JSON string properly")),console.error(Be.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}s&&"object"==typeof s&&"type"in s&&!("transport"in s)&&(s.transport=s.type,delete s.type),s?.oauth?.callbackPort&&(o=s.oauth.callbackPort,delete s.oauth.callbackPort),n.clientSecret&&s?.oauth&&(s.oauth.clientSecret=n.clientSecret);const i=js.safeParse(s);if(!i.success){console.error(Be.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(Be.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(Be.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(Be.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(Be.cyan("Starting OAuth authentication...")),console.log(Be.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:a.oauth.authorizationUrl,tokenUrl:a.oauth.tokenUrl,clientId:a.oauth.clientId,clientSecret:a.oauth.clientSecret,scopes:a.oauth.scopes},n=await performOAuthFlow(e,t,{...o&&{port:o},onStatus:__name(e=>{console.log(Be.gray(` ${e}`))},"onStatus")});n.success?console.log(Be.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(Be.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(Be.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(Be.gray("Or authenticate via the /mcp menu in a session")))}const u="user"===n.scope?"global":"project"===n.scope?"project":"local";if(l?console.log(Be.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(Be.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(Be.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(Be.gray(` Command: ${e}`))}console.log(""),console.log(Be.cyan("Next steps:")),console.log(Be.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new Ae("auth");return e.description("Manage OAuth authentication for MCP servers").argument("[server]","Server name to authenticate").option("--status","Check authentication status").option("--clear","Clear stored authentication").option("--list","List servers with stored authentication").action(async(e,t)=>{const n=getInvokedCommandName();try{if(t.list){const e=await listServersWithTokens();if(0===e.length)return void console.log(Be.yellow("No servers with stored authentication."));console.log(Be.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?Be.yellow("expired"):Be.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(Be.red("Error: Server name is required")),console.error(Be.gray(`Usage: ${n} mcp auth <server>`)),console.error(Be.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(Be.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(Be.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(Be.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(Be.gray(" A refresh token is available for re-authentication"));else{if(console.log(Be.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(Be.gray(` Expires in ${e} minutes`))}t.scope&&console.log(Be.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(Be.green(`✓ Cleared authentication for '${e}'`)):console.log(Be.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(Be.red(`Error: MCP server '${e}' not found`)),console.error(Be.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(Be.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(Be.gray(`Add OAuth config using "${n} mcp add-json" with oauth field`)),process.exit(1));const s={authorizationUrl:r.config.oauth.authorizationUrl,tokenUrl:r.config.oauth.tokenUrl,clientId:r.config.oauth.clientId,clientSecret:r.config.oauth.clientSecret,scopes:r.config.oauth.scopes};console.log(Be.cyan(`Authenticating with '${e}'...`)),console.log(Be.gray("A browser window will open for authentication.\n"));const o=await performOAuthFlow(e,s,{onStatus:__name(e=>{console.log(Be.gray(` ${e}`))},"onStatus")});if(o.success)return console.log(Be.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(Be.gray("Restart the session to connect with the authenticated server."));console.error(Be.red(`\nError: Authentication failed: ${o.error}`)),console.log(Be.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Ae("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(h.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${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")}Nt(),Nt(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Nt(),__name(listMcpCommand,"listMcpCommand"),Nt(),__name(getMcpCommand,"getMcpCommand"),Nt(),__name(removeMcpCommand,"removeMcpCommand"),Nt(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Nt(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Nt(),Ot(),Nt(),Nt(),fC(),Nt(),Ot(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Nt(),Nt();var H_=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||H_.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const s=n[r].trim();return{endIdx:t+r,inclusive:H_.test(s)&&!s.startsWith("#")&&!s.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:s}=findLookaheadEnd(e,t),o=s?r+1:r;return{combined:[n,...e.slice(t,o).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:o}}function processRawLine(e,t){const n=e[t],r=t+1,s=n.trim();if(!s.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(H_.test(s))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:o,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:o,originalLineNum:r},nextIdx:i}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:s}=processRawLine(e,n);t.push(r),n=s}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],s=t.substring(1).trim();if(!H_.test(s))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 o=Array.from(s.matchAll(/confidence:\s*(\S+)/gi)),i=o.length>0?o[o.length-1]:null;if(!i)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 a=i[1],l=parseFloat(a);if(isNaN(l))return r.push({line:n,severity:"error",message:`Confidence value "${a}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==i.index?s.substring(0,i.index).trim():s.trim();return u&&0!==u.length?(u.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(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 hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=t.slice(n+1,n+4),s=r.findIndex(e=>e.trim().startsWith("# "));return(-1===s?r:r.slice(0,s)).some(e=>e.includes("See [")&&e.includes("taste.md"))}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),s=t.filter(e=>"warning"===e.severity),o=0===r.length;if(0===t.length)return{valid:o,issues:[...t],summary:`${be.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),s.length>0&&i.push(`${s.length} warning${s.length>1?"s":""}`);const a=r.length>0?be.cross:be.warning;return{valid:o,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?Be.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(Be.dim(` → ${e.suggestion}`)),n}function formatIssueGroup(e,t,n){return 0===e.length?[]:[n,...e.flatMap(e=>formatSingleIssue(e,t)),""]}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`${Be.green(e)} ${Be.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),s=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?Be.red(t.summary):Be.yellow(t.summary),"",...formatIssueGroup(r,Be.red,Be.bold(Be.red("Errors:"))),...formatIssueGroup(s,Be.yellow,Be.bold(Be.yellow("Warnings:")))].join("\n").trim()}__name(findLookaheadEnd,"findLookaheadEnd"),__name(joinMultiLineLearning,"joinMultiLineLearning"),__name(processRawLine,"processRawLine"),__name(preprocessLines,"preprocessLines"),__name(validateLearningLine,"validateLearningLine"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(buildResult,"buildResult"),Nt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var V_=new Set(["# Taste (Continuously Learned by [CommandCode][cmd])","# Taste (Continuously Learned by CommandCode.ai)","# Taste (Continuously Learned by CommandCode)"]);function warnIfEmptyCategory(e,t){!e.currentCategory||e.learningsInCurrentCategory>0||hasReferenceAfterCategory({lines:t,categoryLineIndex:e.categoryLineNumber-1})||e.issues.push({line:e.categoryLineNumber,severity:"warning",message:`Category '${e.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function processHeading(e){const{line:t,lineNum:n,state:r,rawLines:s}=e;V_.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,s),r.currentCategory=t.trim().substring(2).trim(),r.categoryLineNumber=n,r.learningsInCurrentCategory=0)}function processLearning(e){const{line:t,lineNum:n,state:r}=e;r.currentCategory?(r.learningsInCurrentCategory++,r.issues.push(...validateLearningLine({line:t.trim(),lineNum:n}))):r.issues.push({line:n,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'})}__name(warnIfEmptyCategory,"warnIfEmptyCategory"),__name(processHeading,"processHeading"),__name(processLearning,"processLearning");var K_=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,Y_=/^\[cmd\]: https:\/\/commandcode\.ai\/$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:s}=e,o=t.trim();o&&(o.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:s}):o.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):K_.test(o)||Y_.test(o)||r.issues.push({line:n,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"}))}function checkFinalCategory(e){const{state:t,rawLines:n}=e;!t.currentCategory||t.learningsInCurrentCategory>0||!t.categoryLineNumber||hasReferenceAfterCategory({lines:n,categoryLineIndex:t.categoryLineNumber-1})||t.issues.push({line:t.categoryLineNumber,severity:"warning",message:`Category '${t.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}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 s=t.split("\n"),o=preprocessLines(s),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of o)processLine({line:e,lineNum:t,state:i,rawLines:s});return checkFinalCategory({state:i,rawLines:s}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var J_=__name(e=>"local-global"===e?"global":"project","locationLabel"),X_=__name(({file:e,error:t})=>({success:!1,filesLinted:[],errors:[{file:e,error:t}],totalErrors:0,totalWarnings:0}),"failResult");function resolvePackageFile(e,t){const n=getCategoryTasteFile({target:t,category:e});return E(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${J_(t)}`}}}function collectSpecificFiles(e){const{packages:t,target:n}=e,r=t.map(e=>resolvePackageFile(e,n));return{files:r.filter(e=>"result"in e).map(e=>e.result),errors:r.filter(e=>"error"in e).map(e=>e.error)}}async function collectAllFiles(e){const{tastePath:t,target:n}=e,r=[],s=getRootTasteFile({target:n});E(s)&&r.push({path:s,displayName:"taste.md"});const o=(await $.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>E(e)).map(({entry:e,categoryFile:t})=>({path:t,displayName:`${e.name}/taste.md`}));return r.push(...o),r}async function lintFile(e){let t=await $.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await $.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),s=r.issues.filter(e=>"error"===e.severity).length,o=r.issues.filter(e=>"warning"===e.severity).length,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:s,warnings:o,formatted:i}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:s}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&s.length>0)return{success:!1,filesLinted:[],errors:s,totalErrors:0,totalWarnings:0};if(0===r.length)return X_({file:"all",error:`No taste files found in ${J_(n)}`});const o=await Promise.all(r.map(lintFile)),i=o.reduce((e,t)=>e+t.errors,0),a=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid)&&0===s.length,filesLinted:o,errors:s,totalErrors:i,totalWarnings:a}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return X_({file:"all",error:`No taste files found in ${J_(n)}`});const s=await Promise.all(r.map(lintFile)),o=s.reduce((e,t)=>e+t.errors,0),i=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid),filesLinted:s,errors:[],totalErrors:o,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return E(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):X_({file:"all",error:`No taste directory found in ${J_(n)}`})}function resolveConflictStrategy(e){const t=[e.skip&&"skip",e.merge&&"merge",e.overwrite&&"overwrite"].filter(Boolean);return t.length>1&&exitWithError(`Cannot combine --${t[0]} and --${t[1]}. Choose one conflict strategy.`),t[0]}__name(resolvePackageFile,"resolvePackageFile"),__name(collectSpecificFiles,"collectSpecificFiles"),__name(collectAllFiles,"collectAllFiles"),__name(lintFile,"lintFile"),__name(lintSpecificPackages,"lintSpecificPackages"),__name(lintAllFiles,"lintAllFiles"),__name(lint,"lint"),Nt(),Vr(),__name(resolveConflictStrategy,"resolveConflictStrategy");var Z_=Be.bgGreen.black.bold(" TASTE ");function shortenPath(e){const t=process.env.HOME??process.env.USERPROFILE??"";return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function exitWithError(e){console.error(`${Be.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`),process.exit(1)}function formatUsageLine(e){const t=e.match(/^(\s*(?:Usage:|or:)?\s*)(cmd)(\s+.+?)(\s+\(.*\))?$/);return t?`${Be.dim(t[1])}${Be.green(t[2])}${Be.white(t[3]??"")}${t[4]?Be.dim(t[4]):""}`:Be.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${Be.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`);for(const e of t)console.error(formatUsageLine(e));process.exit(1)}function resolveRemoteDefault(e){return e.global||e.remote?e:{...e,remote:!0}}__name(shortenPath,"shortenPath"),__name(exitWithError,"exitWithError"),__name(formatUsageLine,"formatUsageLine"),__name(exitWithUsage,"exitWithUsage"),__name(resolveRemoteDefault,"resolveRemoteDefault");var eP=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return ot(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:eP})}function getProfileLink(e){return ot(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:eP})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return st(e,n,{trim:!1})}function formatMergeParts(e){const t=[];return e.added>0&&t.push(`${e.added} ${1===e.added?"learning":"learnings"} added`),e.updated>0&&t.push(`${e.updated} ${1===e.updated?"learning":"learnings"} updated`),e.unchanged>0&&t.push(`${e.unchanged} ${1===e.unchanged?"learning":"learnings"} unchanged`),t}function hasMergeConflictRisk(e){return(e.added>0||e.updated>0)&&e.unchanged>0}function hasMergeConflictRiskInRecord(e){return Object.values(e).some(hasMergeConflictRisk)}function logMergeReviewTip(){console.log(Be.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function parseOwnerPackage(e){if(!e.includes("/"))return;const[t,n]=e.split("/");return t&&n?{owner:t,packageName:n}:void 0}function handleResultErrors(e){for(const t of e){const e=t.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${t.pkg}' `);console.error(`${Be.red("Error:")} ${e}`)}process.exit(1)}function getTimeAgo(e){const t=Date.now()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),s=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`:`${s} day${s>1?"s":""} ago`}async function flushAndExit(e){await Promise.race([shutdownTelemetry(),new Promise(e=>setTimeout(e,500))]).catch(()=>{}),process.exit(e)}function withErrorHandler(e){return async(...t)=>{try{await e(...t),await flushAndExit(0)}catch(e){const t=e instanceof Error?e.message:String(e);console.error(Be.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new Ae("lint").argument("[package]","Taste package name").option("-g, --global","Validate taste packages from global storage (~/.commandcode)").option("--all","Validate all taste packages").description(`Validate taste package format ${Be.dim("(structure, style, etc.)")}`).action(withErrorHandler(async(e,t)=>runLint({packageName:e,options:t})))}function validateLintOptions({packageName:e,options:t}){e||t.all||exitWithUsage({message:"Specify a taste package name or use --all to validate everything",usage:["cmd taste lint <package> validate a taste package","cmd taste lint --all validate all taste packages"]}),e&&t.all&&exitWithError("Use either a package name or --all, not both")}function logLintResults(e){for(const t of e.filesLinted)console.log(t.formatted);e.filesLinted.length>1&&logLintSummary(e),e.success||process.exit(1)}function logLintSummary({filesLinted:e,totalErrors:t,totalWarnings:n}){if(console.log(""),0===t&&0===n)return void console.log(`${Be.green(be.tick)} All ${Be.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(Be.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(Be.yellow(`${n} warning${n>1?"s":""}`)),console.log(`Summary: ${r.join(", ")} across ${e.length} files`)}async function runLint({packageName:e,options:t}){console.log(""),validateLintOptions({packageName:e,options:t});const n=await lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(Be.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),s=r[0].trim(),o=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===o.length?null:{category:normalizeCategory({category:s}),learnings:o,sourcePath:n}}function parsePackages(e){const{content:t,sourcePath:n}=e;return t.split(/^# /gm).filter(e=>e.trim()).filter(e=>!e.includes("See [")).map(e=>parseSection({section:e,sourcePath:n})).filter(e=>null!==e)}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 formatPackage(e){const{pkg: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}async function readAndMigrateFile(e){const{filePath:t}=e,n=await $.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await $.writeFile(t,r,"utf-8"),r)}function trimTrailingBlanks(e){const{lines:t,until:n}=e;let r=e.from;for(;r>n&&""===t[r].trim();)r--;return r}function findCategoryRange(e){const{lines:t,pattern:n}=e,r=t.findIndex(e=>n.test(e));if(-1===r)return null;const s=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===s)return{start:r,end:t.length-1};const o=trimTrailingBlanks({lines:t,from:s-1,until:r});return{start:r,end:o}}function ensureHeader(e){if(!e)return lC+"\n\n";const t=e.trim();return t.startsWith(iC)||t.startsWith(cC)||t.startsWith(uC)?e:lC+"\n\n"+e}function ensureTrailingNewlines(e){return e?e.endsWith("\n\n")?e:e.endsWith("\n")?e+"\n":e+"\n\n":e}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(formatMergeParts,"formatMergeParts"),__name(hasMergeConflictRisk,"hasMergeConflictRisk"),__name(hasMergeConflictRiskInRecord,"hasMergeConflictRiskInRecord"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(parseOwnerPackage,"parseOwnerPackage"),__name(handleResultErrors,"handleResultErrors"),__name(getTimeAgo,"getTimeAgo"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Nt(),Es(),Nt(),Nt(),Nt(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Nt(),__name(formatPackage,"formatPackage"),Nt(),fC(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var tP="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:tP,category:e.name});return E(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await $.stat(e.sourcePath);return{category:e.category,learningCount:e.learnings.length,lastUpdated:t.mtime,filePath:e.sourcePath}}catch{return{category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}}}async function getAllPackages(){const e=getTastePath({target:tP});if(!E(e))return[];const t=await $.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:tP,category:t});return E(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:tP});await $.mkdir(r,{recursive:!0});const s=getCategoryTasteFile({target:tP,category:n.category}),o=e.dirname(s);await $.mkdir(o,{recursive:!0});const i=formatPackage({pkg:n});await $.writeFile(s,i,"utf-8")}async function listPackages(){const e=await getAllPackages();return await Promise.all(e.map(getPackageInfo))}__name(loadCategoryPackages,"loadCategoryPackages"),__name(getPackageInfo,"getPackageInfo"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(writePackage,"writePackage"),__name(listPackages,"listPackages"),Nt(),Nt(),fC();var nP="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!E(n))return null;const r=migrateHeader({content:await $.readFile(n,"utf-8")}).split("\n"),s=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!s)return null;const o=r.slice(0,s.start),i=s.end<r.length-1?r.slice(s.end+1):[],a={before:o.join("\n").trim(),after:i.join("\n").trim()},l=[...o,...i].join("\n").trim();return""===l&&await $.rm(n,{force:!0}),""!==l&&await $.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:nP}),s=await removeCategoryFromRoot({category:n,rootFile:r}),o=getCategoryTasteFile({target:nP,category:n}),i=e.dirname(o);return E(i)&&await $.rm(i,{recursive:!0,force:!0}),s}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,s=formatPackage({pkg:t});if(r){let e=ensureHeader(migrateHeader({content:r.before}));e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=s.trim()+t,void await $.writeFile(n,e.trim()+"\n","utf-8")}let o="";E(n)&&(o=await $.readFile(n,"utf-8"),o=migrateHeader({content:o})),o=ensureHeader(o),o=ensureTrailingNewlines(o),o+=s,await $.writeFile(n,o.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:s}=t,o=getCategoryTasteFile({target:nP,category:n.category}),i=e.dirname(o);await $.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await $.writeFile(o,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(s){let e=ensureHeader(migrateHeader({content:s.before}));e=ensureTrailingNewlines(e);const t=s.after?"\n\n"+s.after:"";return e+=l.trim()+t,void await $.writeFile(r,e.trim()+"\n","utf-8")}let u="";E(r)&&(u=await $.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await $.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var rP="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:rP,category:e.name});return E(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:rP});if(!E(e))return[];const t=[],n=getRootTasteFile({target:rP});if(E(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await $.readdir(e,{withFileTypes:!0}),s=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...s),t}async function getPackage2(e){const{category:t}=e;return(await getAllPackages2()).find(e=>e.category===t)||null}async function writePackage2(e){const{pkg:t}=e,n=getTastePath({target:rP});await $.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:rP}),s=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:s}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:s})}function exists2(){const e=getTastePath({target:rP});return E(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!E(n))return;const r=await $.readFile(n,"utf-8"),s=new Blob([r],{type:"text/markdown"}),o=new File([s],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,o)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:s,type:o="category",isPublic:i=!1}=t,a=new FormData;a.append("name",n),s&&a.append("description",s),a.append("type",o),a.append("isPublic",String(i));const l=formatPackage({pkg:r}),u=new Blob([l],{type:"text/markdown"}),d=new File([u],"taste.md",{type:"text/markdown"});if(a.append("files[taste.md]",d),"category"===o)return a;const m=getTastePath({target:"local-project"}),p=e.join(m,r.category);if(!E(p))return a;const g=getCategoryTasteFile({target:"local-project",category:r.category});if(!E(g))return a;const h=await $.readFile(g,"utf-8"),f=new Blob([h],{type:"text/markdown"}),y=new File([f],"taste.md",{type:"text/markdown"});return a.append(`files[${r.category}/taste.md]`,y),a}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:s=!1}=e,o=new FormData;o.append("name",n),r&&o.append("description",r),o.append("type","project"),o.append("isPublic",String(s));const i=getRootTasteFile({target:"local-project"});if(E(i)){const e=await $.readFile(i,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});o.append("files[taste.md]",n)}const a=t.map(e=>appendCategoryFile(o,e));return await Promise.all(a),o}function parseLearningLine(e){const t=e.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(!t)return null;const n=t[1].trim(),r=parseFloat(t[2]);return!n||isNaN(r)?null:{text:n,confidence:r}}function parseTasteContent(e){return e.split("\n").filter(e=>{const t=e.trim();return t&&!t.startsWith("#")&&t.startsWith("-")}).map(e=>parseLearningLine(e.trim())).filter(e=>null!==e)}async function parseApiError(e){const{response:t,fallback:n}=e;try{const e=await t.json();return e.error?.message||e.message||n}catch{return n}}function throwTrackedError(e){const{message:t,label:n,heading:r,status:s,extra:o}=e,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:Br.TASTE_REMOTE_STORAGE,heading:r,"http.status":s,...o}}),i}async function requireAuthKey(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");return e}async function downloadPackage(e){const{owner:t,packageName:n}=e,r=getApiBaseUrl(),s=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(s)return s;const o=await getAuthKey();if(!o)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");return tryAuthenticatedDownload({baseUrl:r,owner:t,packageName:n,apiKey:o})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,s=`${t}${St.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let o;try{o=await fetch(s,{method:"GET"})}catch{return null}if(o.ok){const{data:e}=await o.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===o.status)return null;throwTrackedError({message:await parseApiError({response:o,fallback:`Failed to download taste package (${o.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:o.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:s}=e,o=`${t}${St.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${s}`}});if(i.ok){const{data:e}=await i.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===i.status)return null;throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:i.status})}async function fetchSinglePackage(e){try{return await getPackage3({category:e.name})}catch(t){const n=t instanceof Error?t:new Error(String(t));return trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_package_error"}),context:{component:Br.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${n.message}`),null}}async function getAllPackages3(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${St.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list taste packages",status:n.status});const{data:r}=await n.json(),s=r.packages||[];if(0===s.length)return[];const o=[];for(let e=0;e<s.length;e+=5){const t=s.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));o.push(...n.filter(e=>null!==e))}return o}async function getPackage3(e){const{category:t}=e;let n;await requireAuthKey();try{n=await getAuthenticatedEntity()}catch(e){const n=e instanceof Error?e:new Error(String(e));throw dlog(`[Auth] getPackage: entity endpoint unavailable — ${n.message}`),trackError({error:sanitizeErrorForTelemetry({error:n,label:"get_entity_error"}),context:{component:Br.TASTE_REMOTE_STORAGE,heading:"getAuthenticatedEntity failed in getPackage"}}),new Error(`Could not resolve your account to fetch '${t}'. Check your connection and try again.`)}if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");return downloadRemotePackage({owner:n.user.userName,packageName:t})}async function downloadRemotePackage(e){const{owner:t,packageName:n}=e,r=await downloadPackage({owner:t,packageName:n});if(!r)return null;const s=r.files||[];if(0===s.length)return null;const o=s.find(e=>"taste.md"===e.file);if(!o)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(o.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1}=e,s=await requireAuthKey(),o=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r}),i=`${getApiBaseUrl()}${St.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,a=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:o});a.ok||throwTrackedError({message:await parseApiError({response:a,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:a.status}),await a.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:s=!1}=e,o=await requireAuthKey(),i=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:s}),a=`${getApiBaseUrl()}${St.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:i});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:l.status,extra:{"package.count":t.length}}),await l.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${St.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list packages",status:n.status});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 function list(e){const{location:t}=e;if("local-global"===t)return listPackages();if("remote-project"===t||"remote-user"===t)return listPackages2();if("local-project"===t){const e=getRootTasteFile({target:"local-project"}),t=await getAllPackages2();return Promise.all(t.map(async t=>{let n;if(t.sourcePath!==e)try{n=(await $.stat(t.sourcePath)).mtime}catch{}return{category:t.category,learningCount:t.learnings.length,lastUpdated:n,filePath:t.sourcePath}}))}throw new Error(`Invalid location: ${t}`)}function createListCommand(){return new Ae("list").alias("ls").option("-g, --global","List global packages").addOption(new xe("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new xe("--staging","Use staging environment").hideHelp()).description(`List available packages ${Be.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}__name(loadCategoryPackages2,"loadCategoryPackages"),__name(getAllPackages2,"getAllPackages"),__name(getPackage2,"getPackage"),__name(writePackage2,"writePackage"),__name(exists2,"exists"),Nt(),ts(),Nt(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),Ot(),Nt(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),AC(),Vr(),Nt(),Qs(),Vr(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Nt(),ts(),Qs(),Ot(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),$n(),__name(fetchSinglePackage,"fetchSinglePackage"),__name(getAllPackages3,"getAllPackages"),__name(getPackage3,"getPackage"),__name(downloadRemotePackage,"downloadRemotePackage"),__name(writePackage3,"writePackage"),__name(writePackages,"writePackages"),__name(listPackages2,"listPackages"),__name(list,"list"),__name(createListCommand,"createListCommand");var sP={remote:{location:"remote-project",name:"remote",subtitle:"commandcode.ai account"},global:{location:"local-global",name:"global",subtitle:"~/.commandcode/taste"},project:{location:"local-project",name:"project",subtitle:".commandcode/taste"}};function resolveStorage(e){return e.remote?sP.remote:e.global?sP.global:sP.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${be.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${be.arrowDown}${e.downloadCount}`.length),t}function formatPackageLine({pkg:e,maxLen:t}){const n=" ".repeat(t-getPackageDisplayLength(e)+2),r=e.lastUpdated?getTimeAgo(e.lastUpdated):null,s=r?`, updated ${r}`:"";return` ${Be.white(e.category)}${e.isPublic?Be.green(" [public]"):""}${e.isPublic&&e.starCount?Be.yellow(` ${be.star}${e.starCount}`):""}${e.downloadCount?Be.gray(` ${be.arrowDown}${e.downloadCount}`):""}${n}${Be.dim.gray(`(${e.learningCount} learnings${s})`)}`}function validateListOptions(e){e.global&&e.remote&&exitWithError("Error: Cannot specify both --global and --remote flags")}async function fetchPackages({options:e}){const t=resolveStorage(e),n=e.remote?Ie(`Fetching ${t.name} packages`).start():null,r=await list({location:t.location});return n?.stop(),{packages:r,storage:t}}async function getStorageLabel({options:e,fallback:t}){if(!e.remote)return t;const n=await getUserName();return n?getProfileLink(n):t}function printPackageTable({packages:e,subtitle:t}){console.log(`\n${Z_} Packages`),console.log(`${Be.gray("⎿")} ${Be.dim(t)}\n`);const n=Math.max(...e.map(getPackageDisplayLength));let r=0;for(const t of e)r+=t.learningCount,console.log(formatPackageLine({pkg:t,maxLen:n}));console.log(Be.dim(`\nTotal: ${e.length} packages, ${r} learnings\n`))}async function runList({options:e}){console.log(""),validateListOptions(e);const{packages:t,storage:n}=await fetchPackages({options:e});0!==t.length?printPackageTable({packages:t,subtitle:await getStorageLabel({options:e,fallback:n.subtitle})}):console.log(Be.yellow(`No taste packages found in ${n.name}`))}async function fetchAllPackages(e){const{target:t}=e;return"local-project"===t?getAllPackages2():"local-global"===t?getAllPackages():getAllPackages3()}function handleOpenError(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 readCategoryLineNumber(t){const{filePath:n,category:r}=t,s=await $.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const o=s.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return o>=0?o+1:1}async function findCategoryLineNumber(e){try{return await readCategoryLineNumber(e)}catch{return 1}}async function openPackage(e){const{packageName:t,target:n}=e,r=(await fetchAllPackages({target:n})).find(e=>e.category===t);if(!r){let e="project";return"local-global"===n&&(e="global"),"remote-project"!==n&&"remote-user"!==n||(e="remote"),{success:!1,error:`Taste package '${t}' not found in ${e}`}}const s=r.sourcePath,o=await findCategoryLineNumber({filePath:s,category:t});return await et([{file:s,line:o}]),{success:!0,filePath:s,lineNumber:o}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Nt(),Nt(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var oP=new Set(["local-project","local-global","remote-project","remote-user"]);async function open7(e){const{package:t,target:n}=e;if(!oP.has(n))return{success:!1,error:`Invalid target: ${n}`};try{return await openPackage({packageName:t,target:n})}catch(e){return handleOpenError(e)}}function getEditorSetupInstructions(){const e=it.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}`}function createOpenCommand(){return new Ae("open").argument("[package]","Taste package name, or owner/package to open in browser").option("-g, --global","Open taste package from global storage (~/.commandcode)").description(`Open a taste package in your editor ${Be.dim("(use owner/package to open in browser)")}`).action(withErrorHandler(async(e,t)=>runOpen({packageName:e,options:t})))}function validateOpenOptions(e){e||exitWithUsage({message:"Specify a taste package name to open",usage:["cmd taste open <package> open taste package in editor","cmd taste open <package> -g open global taste package in editor","cmd taste open owner/package open package page in browser"]})}async function runOpen({packageName:e,options:t}){console.log(""),validateOpenOptions(e);const n=parseOwnerPackage(e);n?await openInBrowser(n):await openInEditor3({packageName:e,options:t})}async function openInBrowser(e){const t=`https://commandcode.ai/${e.owner}/${e.packageName}`;await ie(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${Be.green(be.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open7({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${Be.green(be.tick)} Opened ${Be.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open7,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Nt(),Nt(),Nt(),Nt();var iP=null,aP=!1;function setActiveSpinner(e){iP=e}function stopActiveSpinner(e){iP&&(iP.stop(e),iP=null)}function setPrompted(e){aP=e}function wasPrompted(){return aP}function beginPrompt(e,t){stopActiveSpinner(),Ee.intro(Be.dim(e)),t&&Ee.log.message(Be.dim(t)),setPrompted(!0)}function handleCancel(e){Ee.isCancel(e)&&(Ee.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Ee.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Ee.spinner();r.start(t),setActiveSpinner({stop:__name(e=>r.stop(e??n),"stop"),cancel:__name(e=>r.cancel(e),"cancel"),error:__name(e=>r.error(e),"error")})}async function promptMergeStrategy(e){const{packageName:t,owner:n,localPkg:r,remoteLearningsCount:s}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${Be.green(`'${t}'`)} from ${n}`,o),Ee.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${s} learnings ${Be.dim(`(from ${n})`)}`);const i=await Ee.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} → ${s} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});handleCancel(i);const a=i;return startStrategySpinner(a),a}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e,s="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${Be.green(`'${t}'`)} to global`,s),Ee.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const o=await Ee.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"});handleCancel(o);const i=o;return startStrategySpinner(i),i}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${Be.green(`'${t}'`)} from global`,s),Ee.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const o=await Ee.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"});handleCancel(o);const i=o;return startStrategySpinner(i),i}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:s}=e,o=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ot(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${Be.green(`'${t}'`)} to ${n}`,o),Ee.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${s} learnings) in ${n}`),Ee.log.info(`Current package: ${Be.cyan(i)} ${Be.dim("(review)")}`);const a=await Ee.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"});handleCancel(a);const l=a;return startStrategySpinner(l),l}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:s}=e,o=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ot(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${Be.green(`'${t}'`)} to ${n}`,o),Ee.log.message(`Local: ${r} learnings\nRemote: ${s} learnings`),Ee.log.info(`Current package: ${Be.cyan(i)} ${Be.dim("(review)")}`);const a=await Ee.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 (${s} → ${r} learnings)`}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}function mergeSingleLearning(e,t,n,r){const s=t.get(e.text);return s?e.confidence>s.confidence?(n.set(e.text,e),void r.updated++):void r.unchanged++:(n.set(e.text,e),void r.added++)}function mergePackages(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},s=new Map(n.map(e=>[e.text,e])),o=new Map(s);for(const e of t)mergeSingleLearning(e,s,o,r);const i=new Set(t.map(e=>e.text)),a=n.filter(e=>!i.has(e.text)).length;return r.unchanged+=a,{merged:Array.from(o.values()),details:r}}function validateSinglePackage(e,t){const n=validateTasteFile({content:formatPackage({pkg:e}),filePath:`${e.category}/taste.md`});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:e.category,error:`Validation failed for taste package in ${t}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${e.category}' in ${t} has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validateSingleRemoteFile(e,t){const n=validateTasteFile({content:e.content,filePath:e.file});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:t,error:`Validation failed for ${e.file}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validatePackages(e){const{packages:t,label:n}=e;return t.map(e=>validateSinglePackage(e,n)).filter(e=>null!==e)}function validateRemoteFiles(e){const{files:t,packageName:n}=e;return t.map(e=>validateSingleRemoteFile(e,n)).filter(e=>null!==e)}function mergeOrKeep(e){const{source:t,existing:n}=e;if(!n)return{pkg:t,details:{added:t.learnings.length,updated:0,unchanged:0}};const r=mergePackages({source:t.learnings,target:n.learnings});return{pkg:{...t,learnings:r.merged},details:r.details}}async function resolveRemotePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,tastePkg:s,owner:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:s.category,owner:o,localPkg:r,remoteLearningsCount:s.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:s,result:o}=e,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:s,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void o.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),o.packagesPulled.push(t.category),o.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),o.packagesPulled.push(t.category),o.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});o.filePaths[t.category]=l}async function processPackage(e){const{tastePkg:t,result:n}=e;try{await executePackageStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullProjectPackage(e){const{files:t,packageName:n,owner:r,overwrite:s,flagStrategy:o,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(a){const e=parsePackages({content:a.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:s,flagStrategy:o,result:i})}const l=t.filter(e=>"taste.md"!==e.file);for(const e of l){const t=e.file.replace("/taste.md",""),a={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:a,owner:r,overwrite:s,flagStrategy:o,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:s,flagStrategy:o,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(!a)return i.success=!1,void i.errors.push({pkg:n,error:"No taste.md file found in category package"});const l={category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,owner:r,overwrite:s,flagStrategy:o,result:i})}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),Nt(),Nt(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Nt(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var lP=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),cP=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),uP=__name(e=>"local-global"===e?"global":"remote-project"===e?"remote project":"remote-user"===e?"remote":"source","sourceName");async function resolvePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,source:s,tastePkg:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===s?promptGlobalPullStrategy({packageName:o.category,localPkg:r,globalLearningsCount:o.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:s,result:o}=e,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:s,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void o.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),o.packagesPulled.push(t.category),o.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),o.packagesPulled.push(t.category),o.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});o.filePaths[t.category]=l}async function pullSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePullStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pull(e){const{packages:t,source:n,overwrite:r=!1,strategy:s}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return lP({pkg:"all",error:`Invalid source: ${n}`});const o=uP(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return lP({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return lP({pkg:"all",error:`No taste packages found in ${o}`});const a=validatePackages({packages:i,label:o});if(a.length>0)return{success:!1,packagesPulled:[],errors:[...a],mergeDetails:{},overwritten:[],filePaths:{}};const l=t.length>0?i.filter(e=>t.includes(e.category)):i;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${o}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=cP();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:s,overwrite:r,result:u});return u}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o}=e,i=await downloadPackage({owner:t,packageName:n});if(!i)return lP({pkg:n,error:"Taste package not found in remote"});const{type:a,files:l}=i,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy:s,result:o};return"project"===a?(await pullProjectPackage(d),o):(await pullCategoryPackage(d),o)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:s}=e,o=cP();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o})}catch(e){return lP({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Ee.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:s,mergeDetails:o}=e,i=wasPrompted()?"":`${be.tick} `,a=r?Be.dim(`\n ${shortenPath(r)}`):"";if(s.overwrite)return`${Be.green(i)}Replaced ${Be.green(`'${t}'`)} taste package in project`+a;if(o){const e=formatMergeParts(o);return`${Be.green(i)}Pulled ${Be.green(`'${t}'`)} taste package from ${n} ${Be.gray(`(${e.join(", ")})`)}`+a}return`${Be.green(i)}Pulled ${Be.green(`'${t}'`)} taste package from ${n}`+a}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const s=t.packagesPulled[0],o=t.filePaths?.[s],i=t.mergeDetails?.[s];return logResult(buildPullMessage({pkgName:s,sourceName:n,filePath:o,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],s=t.skipped??[],o=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+s.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return o.length>0&&l.push(wrapLine(`${Be.green("Pulled")} (${o.length}) ${o.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${Be.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),s.length>0&&l.push(wrapLine(`${Be.dim("Skipped")} (${s.length}) ${Be.dim(s.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Ee.log.message(l.join("\n")),Ee.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${Be.green(be.tick)} ${a} from ${n}`),l.length>0&&console.log(l.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,s=t.skipped??[];t.packagesPulled.length+s.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():s.length>0?logResult(Be.yellow(`Skipped '${s[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new Ae("pull").argument("[package]","Taste package name, or owner/package to pull from remote").option("-g, --global","Pull taste package from global storage (~/.commandcode)").addOption(new xe("--local","Use local server").hideHelp()).option("--remote","Pull taste package from commandcode.ai remote").option("--all","Pull all taste packages from global").option("--overwrite","Replace local package without prompting").option("--skip","Keep local package, skip conflicting pull").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new xe("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${Be.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:s}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?s??"remote":"global",options:n})}))}function validatePullOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one source"),n.remote&&n.all&&exitWithUsage({message:"--all is not supported for remote pull — specify a package instead",usage:["cmd taste pull <owner>/<package> pull a taste package from remote"]}),n.remote&&!t&&exitWithUsage({message:"Specify a taste package to pull from remote",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),n.remote&&t&&!t.includes("/")&&exitWithUsage({message:`Remote pull requires owner/package format — got '${t}'`,usage:["cmd taste pull <owner>/<package> e.g. cmd taste pull ahmadawais/code-style"]}),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to pull everything",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}async function runPull(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePullOptions({packageName:t,options:r});const s=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:s}):pullGlobal({packageName:t,options:r,strategy:s})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,s=parseOwnerPackage(t);s||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner(Ie("Pulling taste package").start());const o=await pullRemote({owner:s.owner,packageName:s.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:o,owner:s.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner(Ie("Pulling taste package").start());const s=n.all||!t?[]:[t],o=await pull({packages:s,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:o}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new Vb({baseUrl:e}),n=await t.get({endpoint:St.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 logResult2(e){if(wasPrompted())return Ee.outro(e),void setPrompted(!1);console.log(e)}function logPushAllSuccess(t){const{result:n,options:r}=t;if(!r.all)return!1;if(0===n.packagesPushed.length){const e=n.skipped?.length??0;if(e>0){const t=wasPrompted()?"":`${be.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${Be.green(t)}Skipped ${n}`)}return!1}const s=n.packagesPushed.length,o=`${s} ${1===s?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${be.tick} `;if(!a)return logResult2(`${Be.green(l)}Pushed ${o} to remote`),!1;if(r.overwrite||Boolean(n.overwritten?.length)){let e=0;if(n.mergeDetails)for(const t of Object.values(n.mergeDetails))e+=t.updated??0;const t=e>0?` ${Be.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${Be.green(l)}Replaced ${o} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${Be.green(l)}Pushed ${o} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const p=formatMergeParts({added:u,updated:d,unchanged:m}),g=p.length>0?` ${Be.gray(`(${p.join(", ")})`)}`:"";return logResult2(`${Be.green(l)}Pushed ${o} to ${a}${g}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],s=t.filePaths?.[r],o=n.remote&&s,i=o?s:"global",a=wasPrompted()?"":`${be.tick} `,l=!o&&s?Be.dim(`\n ${shortenPath(s)}`):"";if(n.overwrite)return logResult2(`${Be.green(a)}Replaced ${Be.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${Be.green(a)}Pushed ${Be.green(`'${r}'`)} taste package to ${i} ${Be.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${Be.green(a)}Pushed ${Be.green(`'${r}'`)} taste package to ${i}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",s=wasPrompted()?"":`${be.tick} `;return logResult2(wrapLine(`${Be.green(s)}Pushed ${Be.green(t.packagesPushed.length)} taste packages ${Be.green(`(${t.packagesPushed.join(", ")})`)} to ${r}`)),!(n.overwrite||!t.mergeDetails)&&hasMergeConflictRiskInRecord(t.mergeDetails)}function logPushUrls(e){const{result:t,options:n}=e;if(!n.remote||!t.filePaths)return;const r=new Set;for(const e of t.packagesPushed){const n=t.filePaths[e];if(!n||!n.includes("/"))continue;const[s,o]=n.split("/");if(!s||!o)continue;const i=getPackageLink({owner:s,packageName:o});r.has(i)||(r.add(i),console.log(Be.gray(` ${i}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],s=t.packagesPushed.filter(e=>!n.includes(e)),o=t.packagesPushed.length+r.length,i=[];s.length>0&&i.push(wrapLine(`${Be.green("Merged")} (${s.length}) ${s.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${Be.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${Be.dim("Skipped")} (${r.length}) ${Be.dim(r.join(", "))}`,4)),i.length>0&&Ee.log.message(i.join("\n"));const a=`${o} ${1===o?"package":"packages"}`;Ee.outro(a)}function logPushBreakdown(e){const t=e.overwritten??[],n=e.skipped??[];if(0===n.length&&0===t.length)return;const r=e.packagesPushed.filter(e=>!t.includes(e)),s=[];r.length>0&&s.push(wrapLine(`${Be.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&s.push(wrapLine(`${Be.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&s.push(wrapLine(`${Be.dim("Skipped")} (${n.length}) ${Be.dim(n.join(", "))}`)),s.length>0&&console.log(s.join("\n"))}function logPushSuccess(e){const{result:t,options:n}=e;if(wasPrompted())return setPrompted(!1),logConflictSummary({result:t}),void logPushUrls({result:t,options:n});const r=logPushAllSuccess({result:t,options:n})||logPushSingleSuccess({result:t,options:n})||logPushMultiSuccess({result:t,options:n});n.all&&logPushBreakdown(t),logPushUrls({result:t,options:n}),r&&logMergeReviewTip()}__name(resolvePullStrategy,"resolvePullStrategy"),__name(executePullStrategy,"executePullStrategy"),__name(pullSinglePackage,"pullSinglePackage"),__name(pull,"pull"),__name(executePullRemote,"executePullRemote"),__name(pullRemote,"pullRemote"),Nt(),__name(logResult,"logResult"),__name(buildPullMessage,"buildPullMessage"),__name(logPullSingleSuccess,"logPullSingleSuccess"),__name(logPullSummary,"logPullSummary"),__name(logPullSuccess,"logPullSuccess"),__name(createPullCommand,"createPullCommand"),__name(validatePullOptions,"validatePullOptions"),__name(runPull,"runPull"),__name(pullRemoteSingle,"pullRemoteSingle"),__name(pullGlobal,"pullGlobal"),Nt(),$n(),Nt(),ts(),bE(),Ot(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Nt(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Nt(),AC(),Nt();var dP=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),mP=__name(e=>e.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0),"countRemoteLearnings");async function resolvePushAllStrategy(e){const{flagStrategy:t,overwrite:n,existingProject:r,packagesToPush:s,projectName:o,owner:i}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const a=r.type??"category",l=s.reduce((e,t)=>e+t.learnings.length,0),u=mP(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:o,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:o,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:s,isPublic:o,isPublicExplicitlySet:i,flagStrategy:a}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l});if("skip"===await resolvePushAllStrategy({flagStrategy:a,overwrite:s,existingProject:d,packagesToPush:n,projectName:l,owner:r}))return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:i?o:d?.isPublic??!1});for(const e of n)u.packagesPushed.push(e.category),u.filePaths[e.category]=`${r}/${l}`,u.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&u.overwritten.push(...n.map(e=>e.category)),u}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return dP({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var pP=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),gP=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:s}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:s})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var hP=__name(e=>{const{target:t,category:n,owner:r}=e;return"local-global"===t?getCategoryTasteFile({target:"local-global",category:n}):"remote-project"!==t&&"remote-user"!==t||!r?void 0:`${r}/${n}`},"getDestPath");async function getUserOwner(){try{const e=await getAuthenticatedEntity();if(e.success&&e.user?.userName)return e.user.userName}catch{}}async function resolveSinglePushStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,target:s,tastePkg:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===s?promptGlobalPushStrategy({packageName:o.category,localLearningsCount:o.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:s,userOwner:o,isPublic:i,result:a}=e,l="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),u=await resolveSinglePushStrategy({flagStrategy:r,overwrite:s,existingPkg:l,target:n,tastePkg:t});if("skip"===u)return void a.skipped.push(t.category);if("overwrite"===u&&(await writePkg({pkg:t,target:n,owner:o,isPublic:i}),a.packagesPushed.push(t.category),a.overwritten.push(t.category),a.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:o,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=hP({target:n,category:t.category,owner:o});d&&(a.filePaths[t.category]=d)}async function pushSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePushStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function push(e){const t=void 0!==e.isPublic,{packages:n,target:r,overwrite:s=!1,isPublic:o=!1,strategy:i}=e;if(!exists2())return pP({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return pP({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:a,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?a.filter(e=>n.includes(e.category)):a;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:s,isPublic:o,isPublicExplicitlySet:t,flagStrategy:i}):pP({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return pP({pkg:"all",error:`Invalid target: ${r}`});const m=gP();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,overwrite:s,userOwner:d,isPublic:o,result:m});return m}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:s=!1,isPublic:o=!1,strategy:i}=e,a=await getPackage2({category:r});if(!a)return pP({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:a}),filePath:`${a.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return pP({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:i,overwrite:s,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?o:u?.isPublic??!1,p=gP();if("skip"===d)return p.skipped.push(r),p;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m}),p.packagesPushed.push(r),p.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),p.packagesPushed.push(r),p.mergeDetails[r]=t}return p.filePaths[r]=`${n}/${r}`,p}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return pP({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return pP({pkg:t,error:e instanceof Error?e.message:String(e)})}}async function promptOwnerSelection(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"}))],s=await Ee.select({message:"Owner",options:r,initialValue:t});return Ee.isCancel(s)&&(Ee.cancel("Operation cancelled"),process.exit(0)),s}function createPushCommand(){return new Ae("push").description(`Push taste packages to remote ${Be.dim("(commandcode.ai)")} or global ${Be.dim("(~/.commandcode)")}`).argument("[package]","Taste package name to push (omit with --all)").option("--all","Push all taste packages to remote").option("--remote","Push to commandcode.ai remote (default)").option("-g, --global","Push to local global storage (~/.commandcode)").addOption(new xe("--local","Use local server").hideHelp()).option("--public","Make package publicly discoverable on commandcode.ai").option("--private","Make package private (not publicly discoverable)").option("--owner <owner>","Push under a specific owner or organization").option("--overwrite","Replace existing package without prompting").option("--skip","Keep existing package, skip conflicting push").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new xe("--staging","Push to staging environment").hideHelp()).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),r=await runPush({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPushSuccess({result:r,options:n})}))}function validatePushOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one destination"),n.public&&n.private&&exitWithError("--public and --private are mutually exclusive — pick one visibility"),n.owner&&n.global&&exitWithError("--owner only applies to remote pushes, not --global"),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to push everything",usage:["cmd taste push <package> push a taste package to remote (default)","cmd taste push --all push all taste packages to remote","cmd taste push <package> -g push a taste package to global (~/.commandcode)"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}__name(getUserOwner,"getUserOwner"),__name(resolveSinglePushStrategy,"resolveSinglePushStrategy"),__name(executePushStrategy,"executePushStrategy"),__name(pushSinglePackage,"pushSinglePackage"),__name(push,"push"),__name(executeRemotePush,"executeRemotePush"),__name(pushRemote,"pushRemote"),Nt(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var fP=__name(e=>!!e.public||!e.private&&void 0,"resolveVisibility");async function validateOwnerAccess(e){let t;try{t=await fetchUserNamespaces()}catch(e){return void dlog(`[Auth] validateOwnerAccess: namespace service unavailable, skipping — ${e instanceof Error?e.message:String(e)}`)}const n=[t.userName,...t.orgs.map(e=>e.login)];n.includes(e)||exitWithError(`No push access to '${e}'. Available: ${n.join(", ")}`)}async function resolveOwnerForPush(e){const{packageName:t,owner:n}=e,r=parseOwnerPackage(t);if(r)return await validateOwnerAccess(r.owner),r;if(n)return await validateOwnerAccess(n),{owner:n,packageName:t};Ee.intro(Be.dim(`pushing ${t}`)),setPrompted(!0);const s=Ee.spinner();s.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(s.error("Failed"),Ee.outro(Be.red(`Taste package '${t}' not found in project`)),process.exit(1));const o=await fetchUserNamespaces();return s.stop(o.orgs.length>0?"Select owner to push to":""),{owner:o.orgs.length>0?await promptOwnerSelection(o):o.userName,packageName:t}}async function runPush(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePushOptions({packageName:t,options:r});const s=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:s}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:s}):pushGlobal({packageName:t,options:r,strategy:s})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const s=(await getAllPackages2()).length,o=`${s} ${1===s?"package":"packages"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(Be.dim(` Pushing ${o} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(Ie("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:fP(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:s,packageName:o}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:s,pkgName:o});const i=await pushRemote({owner:s,packageName:o,overwrite:n.overwrite,isPublic:fP(n),strategy:r});return stopActiveSpinner(`Pushed to ${s}/${o}`),i}function resolveStrategyLabel(e){const{strategy:t,isRemote:n=!1}=e;return"overwrite"===t?" · overwrite":"skip"===t?" · skip conflicts":"merge"===t?" · auto-merge":n?"":" · will prompt on conflicts"}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=Ee.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Ie("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,s=n.all||!t?[]:[t],o=await getAllPackages2(),i=s.length>0?s.length:o.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(Be.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(Ie("Pushing taste packages").start());const d=await push({packages:s,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new Ae(Tt.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),e}function formatVersion(e,t,n=!1){const r=n?re.bold(re.green(t)):re.white(t);return`${re.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${re.bold(re.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(re.dim(`Run ${re.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(re.dim("Try updating manually:")),console.log(re.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(re.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Ie("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(`${re.green(be.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${re.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Ie("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} ${be.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:Br.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 ${re.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(resolveStrategyLabel,"resolveStrategyLabel"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),__name(createTasteCommand,"createTasteCommand"),Nt(),Ot(),Vr(),__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 yP=new Ae("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Nt(),Qs(),AC();var wP=__name((e,t)=>`${be.info} ${e}: ${re.cyan(t)}`,"formatInfoLine"),SP=__name(e=>re.bold(`${e}:`),"formatSectionHeader"),bP=__name(e=>re.red(e),"formatError"),EP=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),CP=__name(e=>["",SP("User Information"),wP("Name",e.name),wP("Email",e.email),wP("Username",e.userName)],"buildUserOutput"),vP=__name(e=>["",SP("Organization"),wP("Name",e.name),wP("Login",e.login)],"buildOrgOutput"),TP=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),kP=__name((e,t)=>{TP(CP(e)),t&&TP(vP(t)),console.log("")},"displayUserInfo"),_P=__name(e=>null!==e&&e.length>0,"validateApiKey"),PP=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Ie("Fetching user information...").start();try{const t=await getAuthKey();_P(t)||(e.fail(bP('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();PP(n)||(e.fail(bP("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),kP(n.user,n.org)}catch(t){e.fail(bP(`Error: ${EP(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var AP=new Ae("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var xP=createProgram();xP.action(interactiveModeAction),xP.addCommand(W_),xP.addCommand(Q_),xP.addCommand(AP),xP.addCommand(yP),xP.addCommand(U_),xP.addCommand(createTasteCommand()),xP.addCommand(createMcpCommand()),xP.addCommand(G_),xP.addCommand(ps),xP.addCommand(bs),xP.addCommand(As),setupCommanderHooks(xP),xP.parse();
253
+ 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)})})}Vr(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Nt(),Nt(),Ot(),Qs(),Nt(),Ot();var OC="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",DC="\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 qC=getMaxLineWidth(OC),FC=getMaxLineWidth(DC),jC=qC+1,zC=FC+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var BC=__name(e=>{const t=e??getTerminalWidth();return t>=jC?OC:t>=zC?DC:UC},"getResponsiveCommandLogo"),UC="⌘ CMD\n";rr();var WC=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),QC=__name(e=>{const t=__name(e=>({r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}),"hexToRgb"),n=t(Zn.START),r=t(Zn.END);return e.split("\n").map(e=>0===e.length?e:e.split("").map((t,s)=>{const o=e.length>1?s/(e.length-1):0,i=Math.round(n.r+(r.r-n.r)*o),a=Math.round(n.g+(r.g-n.g)*o),l=Math.round(n.b+(r.b-n.b)*o);return Be.rgb(i,a,l)(t)}).join("")).join("\n")},"applyViceGradient"),GC=__name(e=>{console.log(QC(BC())),console.log(""),console.log(`${be.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),HC=__name(async e=>{const t=We.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"),VC=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.log(""),console.log(`${be.cross} Authentication failed. Please try again with: cmd login`),!1)}catch{return!1}},"attemptLogin"),KC=__name(()=>{console.log(""),console.log(`${be.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),YC=__name(()=>{console.log(""),console.log(`${be.info} Authentication cancelled. You can authenticate later with: cmd login`)},"showCancelledMessage");async function checkAuthAndPromptLogin(){try{if(await getAuthKey())return!0;GC(Mt());const{answer:e,cancelled:t}=await HC(`Would you like to sign in now? ${Be.dim("(y/n)")}: `);return t?(YC(),!1):WC(e)?(console.log(""),VC()):(KC(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}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}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin"),Nt(),Nt(),Nt(),Nt(),jr(),Nt(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var JC=["no job control","cannot set terminal process group"],XC=null;function getShellInfo(){return XC||(XC=detectUserShell()),XC}__name(getShellInfo,"getShellInfo");var ZC=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:s=process.env}=t;return new Promise(t=>{let o=!1;const i=__name(e=>{o||(o=!0,t(e))},"doResolve"),a=getShellInfo(),l="bash"===a.type||"zsh"===a.type,u=l?a.path:"/bin/bash",d=N(u,l?["-i","-c",e]:["-c",e],{cwd:r,env:{...s},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let m="",p="",g=null;n>0&&(g=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),i({stdout:m,stderr:p+(p?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(m.length+n.length>Mr){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void i({stdout:m,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}m+=n}catch(e){p+=`\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(p.length+t.length>Or)return void(p+="\n[Error output truncated: too large]");p+=t}catch(e){p+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{g&&clearTimeout(g);const n=l?p.split("\n").filter(e=>!JC.some(t=>e.includes(t))).join("\n"):p;i({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{g&&clearTimeout(g),i({stdout:m,stderr:p+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),ev=__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");Jo();var tv=__name(()=>{const[e,t]=W({isExecuting:!1,currentCommand:null});return{executeBash:V(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await ZC(e,{timeout:3e4,cwd:process.cwd()}),s=ev(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]=Fo(r,s);break}}return n}),r()}catch(t){const s=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]=Fo(r,`Error: ${s}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function useUiOverlays(){const[e,t]=W(!1),[n,r]=W(!1),[s,o]=W(!1),[i,a]=W(!1),[l,u]=W(!1),[d,m]=W(!1),[p,g]=W(!1),[h,f]=W(!1),[y,w]=W(!1),[S,b]=W(!1),[E,C]=W(!1),[v,T]=W(!1),[k,_]=W(!1),[P,A]=W(0),[x,I]=W("off");return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:s,setShowTasteConfig:o,showSkillsConfig:i,setShowSkillsConfig:a,showProviderSelector:l,setShowProviderSelector:u,showModelSelector:d,setShowModelSelector:m,showMemorySelector:p,setShowMemorySelector:g,showMcpManager:h,setShowMcpManager:f,showLearningFeed:y,setShowLearningFeed:w,showSessionSelector:S,setShowSessionSelector:b,showAddDirModal:E,setShowAddDirModal:C,showRewindSelector:v,setShowRewindSelector:T,showLoginOverlay:k,setShowLoginOverlay:_,staticKey:P,setStaticKey:A,transcriptMode:x,setTranscriptMode:I,expandedToolOutput:"off"!==x}}function useFeed(){const[e,t]=W([]),[n,r]=W([]),[s,o]=W([]),[i,a]=W(!1),l=Q([]);return G(()=>{l.current=s},[s]),{feed:e,setFeed:t,liveAgents:n,setLiveAgents:r,queuedMessages:s,setQueuedMessages:o,isCmdCodeBusy:i,setIsCmdCodeBusy:a,queuedMessagesRef:l}}function useSession(){const[e,t]=W(crypto.randomUUID()),[n,r]=W(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:Q(null)}}function useStatus(e){const[t,n]=W("Ready..."),r=Q(!1),[s,o]=W(""),i=Q(null),[a,l]=W(null),u=Q(a),[d,m]=W(null),[p,g]=W(!1),[h,f]=W(""),[y,w]=W(null),[S,b]=W(0),[E,C]=W(null),[v,T]=W(!1),[k,_]=W(e??null);G(()=>{u.current=a},[a]),G(()=>{if(k){const e=setTimeout(()=>{_(null)},3e4);return()=>clearTimeout(e)}},[k]);const P=__name(e=>{i.current&&clearTimeout(i.current),o(e),i.current=setTimeout(()=>{o(""),i.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:s,setHintMessage:o,hintTimerRef:i,shareInfo:a,setShareInfo:l,shareInfoRef:u,billingLink:d,setBillingLink:m,showShareNotification:p,setShowShareNotification:g,unshareNotificationMessage:h,setUnshareNotificationMessage:f,retryAttempt:y,setRetryAttempt:w,interactionTokens:S,setInteractionTokens:b,contextUsage:E,setContextUsage:C,tasteLearningEnabled:v,setTasteLearningEnabled:T,updateStatus:k,setUpdateStatus:_,showHintMessage:P}}function useAuth(){const[e,t]=W(null),[n,r]=W(getConfiguredModel()),[s,o]=W(!1),[i,a]=W(null),[l,u]=W(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,isOAuthMode:s,setIsOAuthMode:o,authComponentInfo:i,setAuthComponentInfo:a,showProviderNotification:l,setShowProviderNotification:u,providerNotificationTimer:Q(null),modelNotificationTimer:Q(null)}}Nt(),__name(useUiOverlays,"useUiOverlays"),Nt(),__name(useFeed,"useFeed"),Nt(),__name(useSession,"useSession"),Nt(),__name(useStatus,"useStatus"),Nt(),nr(),__name(useAuth,"useAuth"),Nt(),Nt(),Nt(),Ot();var nv=class extends Re{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 L.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 L.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await L.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 L.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"),s=`Bash(${e.split(" ")[0]}:*)`;try{let e;await L.mkdir(n,{recursive:!0});try{const t=await L.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(s)||e.permissions.allow.push(s),await L.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},rv=__name((e={})=>{const[t,n]=W(null),[r,s]=W(null),[o,i]=W(!1);return G(()=>{const t=e.projectRoot||process.cwd(),r=new nv(t);return r.on("permission-request",(t,n)=>{s(t),i(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{s(t),i(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:V(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:V(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:V(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),s(null),i(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),s(null),i(!1)}},[t]),clearSessionPermissions:V(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:V(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:V((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:V(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:o,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r="auto-accept"===("boolean"==typeof t?t?"auto-accept":"standard":t),s=["create","edit","delete","execute","shellCommands"];for(const e of s)n.setAutoApprove(e,r)}function usePermissionMode({initialPermissionMode:e,dangerouslySkipPermissions:t=!1,setPendingPermission:n,setStatus:r,contextEngineRef:s}){const[o,i]=W(()=>e||(t?"auto-accept":"standard")),a=Q(o);G(()=>{a.current=o},[o]);const{requestShellPermission:l,service:u,respondToPrompt:d,clearSessionPermissions:m,setEnabled:p}=rv({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{n({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),s.current&&r("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{n({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),s.current&&r("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?r("Permission granted"):r("Permission denied")},"onPermissionResponse")});return G(()=>{u&&applyAutoAcceptMode({enabled:o,service:u})},[o,u]),{permissionMode:o,setPermissionMode:i,permissionModeRef:a,permissionsService:u,respondToPrompt:d,clearSessionPermissions:m}}function usePendingOps(){const[e,t]=W(null),[n,r]=W(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function useOnboarding(){const[e,t]=W(!1),[n,r]=W(!1),[s,o]=W(!0),[i,a]=W(!1),[l,u]=W(!1),[d,m]=W(null),[p,g]=W(!1);return{showTrustPrompt:e,setShowTrustPrompt:t,projectTrusted:n,setProjectTrusted:r,checkingProject:s,setCheckingProject:o,showTasteOnboarding:i,setShowTasteOnboarding:a,onboardingComplete:l,setOnboardingComplete:u,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:m,autoLearnTaste:p,setAutoLearnTaste:g,tasteOnboardingCheckedRef:Q(!1)}}function useExit(){const[e,t]=W(!1),[n,r]=W(null),s=Q(null),o=Q(0),i=Q(null),a=V(()=>{s.current=null,r(null),i.current&&(clearTimeout(i.current),i.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:s,lastExitKeyTimeRef:o,exitConfirmationTimeoutRef:i,resetPendingExitKey:a}}function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:t,description:`Terminate process on ${t}`}}function buildShellPermissionRequest(e,t){const n=e.args,r=Array.isArray(n)?n.join(" "):"string"==typeof n?n:"";return{command:"string"==typeof e.command?e.command:"",args:"string"==typeof n?n:Array.isArray(n)?n.join(" "):void 0,workingDirectory:"string"==typeof e.directory?e.directory:void 0,description:t??`Execute shell command: ${String(e.command??"")} ${r}`}}function getFileAction(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function buildFilePermissionRequest(e,t){const n="edit_file"===e?t.oldValue:void 0,r="edit_file"===e?t.newValue:void 0;return{action:getFileAction(e),filePath:String(t.filePath??t.file_path??t.path??t.absolutePath??"unknown"),description:"string"==typeof t.description?t.description:`${e} operation`,oldContent:"string"==typeof n?n:void 0,newContent:"string"==typeof r?r:void 0}}function useContextEngine({sessionId:e,sessionLoaded:t,showSessionSelector:n,projectTrusted:r,setFeed:s,setLiveAgents:o,setQueuedMessages:i,queuedMessagesRef:a,setStatus:l,pinnedStatusRef:u,setRetryAttempt:d,setInteractionTokens:m,setContextUsage:p,setCurrentProvider:g,shareInfoRef:h,permissionsService:f,permissionModeRef:y,setPendingQuestion:w,contextEngineRef:S}){const b=V(t=>({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;if(!t||"running"!==n)return t&&n&&"running"!==n?(o(t=>t.filter(t=>t.id!==e.id)),void s(t=>[...t,e])):void s(t=>[...t,e]);o(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]})},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...a.current];return a.current=[],i([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{m(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{p(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{d(e)},"onRetryUpdate"),onProviderChange:__name(e=>{g(e)},"onProviderChange"),onStatusUpdate:__name(e=>{u.current=!0,l(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{const r=t??{};if(!f)return!0;if("shell_command"===e){const e=buildShellPermissionRequest(r,n);return(await f.requestShellPermission(e)).allowed}if("kill_shell"===e){const e=createKillShellPermissionRequest(r);return(await f.requestShellPermission(e)).allowed}const s=buildFilePermissionRequest(e,r);return(await f.requestPermission(s)).allowed},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{w({params:e,resolve:t,reject:n}),l("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const n=h.current;return n?{sessionId:t??e,secret:n.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>y.current,"getPermissionMode")}),[f,e]);return G(()=>{S.current||!r||n||t||(S.current=new CC(b(),e))},[e,n,t,r,b,S]),{createContextEngineCallbacks:b}}Nt(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),__name(usePermissionMode,"usePermissionMode"),Nt(),__name(usePendingOps,"usePendingOps"),Nt(),__name(useOnboarding,"useOnboarding"),Nt(),__name(useExit,"useExit"),Nt(),_C(),__name(createKillShellPermissionRequest,"createKillShellPermissionRequest"),__name(buildShellPermissionRequest,"buildShellPermissionRequest"),__name(getFileAction,"getFileAction"),__name(buildFilePermissionRequest,"buildFilePermissionRequest"),__name(useContextEngine,"useContextEngine"),Nt(),Nt(),Nt(),$n();var sv=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(h.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await $.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 $.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await $.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 $.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await $.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await $.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(){return this.cleanupPromise||(this.cleanupPromise=this.performCleanup().finally(()=>{this.cleanupPromise=null})),this.cleanupPromise}async performCleanup(){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 sv}__name(createHistoryManager,"createHistoryManager"),CE(),Zo(),ar(),nr(),Nt(),Ot(),fC();var ov=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await $.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await $.access(r);const e=await $.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await $.writeFile(r,t,"utf-8")}catch{await $.writeFile(r,lC+"\n\n","utf-8")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await $.access(n),!0}catch{return!1}}};mo(),nr(),PC(),Nt(),_C(),Jo(),PC(),Nt(),Ot(),Jl(),bE(),ts();var{setText:iv}=Qe;async function loadShareInfo({contextEngineRef:e,setShareInfo:t}){const n=e.current?.getSessionManager();if(n){const e=await n.loadShareInfo();e&&t({url:e.url,secret:e.secret})}}async function handleShareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setShowShareNotification:s,contextEngineRef:o}){if(e){if(t)return await iv(t.url),r(""),s(!0),void setTimeout(()=>{s(!1)},3e3);try{r("Creating share link...");const t=o.current?.getMessages()||[],i=$l.sanitizeMessages(t,global.COMMAND_CODE_CWD||process.cwd()),a=new Vb({baseUrl:getApiBaseUrl()}),l=await a.post({endpoint:St.ALPHA.SHARE.CREATE,body:{sessionId:e,messages:i}});n({url:l.url,secret:l.secret});const u=o.current?.getSessionManager();u&&await u.saveShareInfo({url:l.url,secret:l.secret}),await iv(l.url),r(""),s(!0),setTimeout(()=>{s(!1)},5e3)}catch(e){r(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else r("No active session to share")}async function handleUnshareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setUnshareNotificationMessage:s,contextEngineRef:o}){if(e){if(!t)return s("NOT SHARED: Session is not currently shared"),void setTimeout(()=>s(""),5e3);try{r("Removing share link...");const i=new Vb({baseUrl:getApiBaseUrl()});await i.delete({endpoint:St.ALPHA.SHARE.DELETE,body:{sessionId:e,secret:t.secret}});const a=o.current?.getSessionManager();a&&await a.deleteShareInfo(),s("UNSHARED: Sharing has stopped"),r(""),n(null),setTimeout(()=>{s("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;r(t),setTimeout(()=>r(""),5e3)}}else r("No active session to unshare")}async function handleSelectSession({selectedSessionId:e,sessionLoadIdRef:t,contextEngineRef:n,setFeed:r,setLiveAgents:s,setSessionId:o,setShowSessionSelector:i,setSessionLoaded:a,setPermissionMode:l,setStaticKey:u,setShareInfo:d,createContextEngineCallbacks:m}){const p=crypto.randomUUID();t.current=p;try{r([]),s([]),n.current=null,l("standard"),o(e),i(!1),a(!0),n.current=new CC(m(e),e);const{feedEntries:g,corruptedLines:h,totalLines:f}=await n.current.loadSession(e);if(t.current!==p)return;await loadShareInfo({contextEngineRef:n,setShareInfo:d});const y=[];if(0===g.length&&f>0&&y.push(Lo(`Session could not be loaded. ${f} lines could not be parsed.`)),0===g.length&&0===f&&y.push(xo("Session loaded but contains no messages.")),g.length>0&&(h>0&&y.push(xo(`Warning: ${h} message(s) could not be loaded.`)),y.push(...g)),t.current!==p)return;r(y),kC(),u(e=>e+1)}catch(e){if(t.current!==p)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";r([Lo(`Failed to load session: ${n}. Starting fresh session.`)]),i(!1),a(!1),o(crypto.randomUUID())}}async function handleNewSession({contextEngineRef:e,setFeed:t,setLiveAgents:n,setSessionId:r,setShowSessionSelector:s,setSessionLoaded:o,setPermissionMode:i}){t([]),n([]),e.current=null,i("standard"),r(crypto.randomUUID()),s(!1),o(!1)}function useStartup({resume:e,continueLatest:t,trust:n,initialPrompt:r,stdout:s,feedState:o,sessionState:i,statusState:a,authState:l,onboarding:u,uiOverlays:d,permissionState:m,contextEngineRef:p,isSubmittingRef:g,initialPromptSubmittedRef:h,historyManagerRef:f,executeBash:y,createContextEngineCallbacks:w,setInput:S}){const b=V(async()=>{try{const e=await isTasteLearningEnabled();a.setTasteLearningEnabled(e),e&&await ov.initializeProject()}catch{}},[a.setTasteLearningEnabled]),E=V(async()=>{const e=await getConfiguredProvider();l.setCurrentProvider(e);const t=await isOAuthEnforced();l.setIsOAuthMode(t)},[l.setCurrentProvider,l.setIsOAuthMode]),C=V(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(()=>{})},[]),v=V(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:i.sessionLoadIdRef,contextEngineRef:p,setFeed:o.setFeed,setLiveAgents:o.setLiveAgents,setSessionId:i.setSessionId,setShowSessionSelector:d.setShowSessionSelector,setSessionLoaded:i.setSessionLoaded,setPermissionMode:m.setPermissionMode,setStaticKey:d.setStaticKey,setShareInfo:a.setShareInfo,createContextEngineCallbacks:w})},[i,o,d,m,a,p,w]),T=V(async()=>{if(t){const e=await Yb.listSessions();return void(e.length>0&&v(e[0].id))}e&&d.setShowSessionSelector(!0)},[t,e,v,d]);G(()=>{(async()=>{await Yb.isProjectInitialized()?(u.setProjectTrusted(!0),u.setCheckingProject(!1),b(),E(),C(),await T()):n?(await Yb.initializeProject(),u.setProjectTrusted(!0),u.setCheckingProject(!1),b(),E(),C(),await T()):isDirectoryEmpty()?(await Yb.initializeProject(),u.setProjectTrusted(!0),u.setCheckingProject(!1),b(),E(),C()):(u.setShowTrustPrompt(!0),u.setCheckingProject(!1))})()},[e,t,n]),G(()=>{if(!u.projectTrusted)return;const e=createHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[u.projectTrusted]),G(()=>{if(!s)return;const e=__name(()=>{d.showLearningFeed||(kC(),d.setStaticKey(e=>e+1))},"handleResize");return s.on("resize",e),()=>{s.off("resize",e)}},[s]),G(()=>{r&&u.projectTrusted&&!u.checkingProject&&p.current&&!d.showSessionSelector&&!h.current&&(h.current=!0,handleSubmit({role:"user",input:r,feed:o.feed,setFeed:o.setFeed,isCmdCodeBusy:o.isCmdCodeBusy,setIsCmdCodeBusy:o.setIsCmdCodeBusy,setQueuedMessages:o.setQueuedMessages,setStatus:a.setStatus,setInteractionTokens:a.setInteractionTokens,updateStatus:a.updateStatus,setUpdateStatus:a.setUpdateStatus,billingLink:a.billingLink,setBillingLink:a.setBillingLink,contextEngineRef:p,isSubmittingRef:g,setInput:S,setStaticKey:d.setStaticKey,executeBash:y}))},[r,u.projectTrusted,u.checkingProject,d.showSessionSelector]);const k=Q(null);k.current={feed:o.feed,setFeed:o.setFeed,isCmdCodeBusy:o.isCmdCodeBusy,setIsCmdCodeBusy:o.setIsCmdCodeBusy,setQueuedMessages:o.setQueuedMessages,setStatus:a.setStatus,setInteractionTokens:a.setInteractionTokens,updateStatus:a.updateStatus,setUpdateStatus:a.setUpdateStatus,billingLink:a.billingLink,setBillingLink:a.setBillingLink,contextEngineRef:p,isSubmittingRef:g,setInput:S,setStaticKey:d.setStaticKey,executeBash:y,role:"",input:""};const _=V(async({role:e,input:t,images:n,ideContext:r})=>handleSubmit({...k.current,role:e,input:t,images:n,ideContext:r}),[]);return{loadTasteStatus:b,loadCurrentProvider:E,initializeMcpInBackground:C,onSubmit:_}}__name(loadShareInfo,"loadShareInfo"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),__name(handleSelectSession,"handleSelectSession"),__name(handleNewSession,"handleNewSession"),IC(),__name(useStartup,"useStartup"),Nt(),dn(),Jo(),un(),Nt(),Ot(),$n(),Nt();var av={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return av[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Ne(t);return e.join(f.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 $.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(t,n=process.cwd()){try{const r=getGlobalProjectSettingsPath(n),s=e.dirname(r);await $.mkdir(s,{recursive:!0}),await $.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),ZE.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 $.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"),Nt(),$n(),tC(),Ot(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),Nt(),$n();var lv=e.join(h.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=_(e,{encoding:"utf8"}),n=Ge.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 $.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const s=await $.readdir(t);for(const o of s){if(!/^\d{4}$/.test(o))continue;const s=e.join(t,o);if(!(await $.stat(s)).isDirectory())continue;const i=await $.readdir(s);for(const t of i){if(!/^\d{2}$/.test(t))continue;const i=e.join(s,t);if(!(await $.stat(i)).isDirectory())continue;const a=await $.readdir(i);for(const s of a){if(!/^\d{2}$/.test(s))continue;const a=e.join(i,s);if(!(await $.stat(a)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${o}/${t}/${s}`});const l=(await $.readdir(a)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(a,t));r.push(...l)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const s=[];for(let o=0;o<e.length;o+=n){const i=e.slice(o,o+n),a=await Promise.all(i.map(t));for(const e of a)null!==e&&s.push(e);r?.(Math.min(o+n,e.length),e.length)}return s}async function findCodexSessions(t,n,r=0){const s=t||process.cwd(),o=[];dlog(`[Codex] scanning for project: ${s}`);const i=await findAllSessionFiles(lv,n);if(0===i.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${i.length} session files to scan`),n?.({phase:"reading",totalFiles:i.length,processedFiles:0,matchedSessions:0});let a=0;const l=await processFilesInBatches(i,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===s)try{const r=await $.stat(t),s=e.basename(t,".jsonl");return{id:n.id||s,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)=>{a=o.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:a})});o.push(...l);const u=r>0?o.slice(0,r):o;return dlog(`[Codex] matched ${u.length} sessions for project`),n?.({phase:"complete",totalFiles:i.length,processedFiles:i.length,matchedSessions:u.length}),u.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 $.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=e?.learnedSessions||{},n=e?.skippedSessions||{},r={};for(const e of new Set([...Object.keys(t),...Object.keys(n)]))r[e]=[...t[e]||[],...n[e]||[]];const s=await findNewSessions(r),o=(s["claude-code"]?.length||0)+(s.codex?.length||0);return o>0?(dlog(`[Onboarding] found ${o} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:o,hasTasteContent:!0,agentSessions:buildAgentSessionsList(s)}):(isOnboardingDone(e)?dlog(`[Onboarding] ${e?.skipped?"user skipped":"already completed"}, no new sessions`):dlog("[Onboarding] no sessions to learn from, skipping"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:isOnboardingDone(e),agentSessions:[]})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[]}}}async function getSessionFilesFromDir(e){try{return(await $.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"]||[],s=t.codex||[];try{const t=e.join(h.homedir(),".claude","projects");await $.access(t);const s=getProjectDirName(process.cwd()),o=(await $.readdir(t)).filter(e=>e===s);for(const s of o){const o=e.join(t,s);if((await $.stat(o)).isDirectory()){const e=await getSessionFilesFromDir(o);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=>!s.includes(e)));dlog(`[Sessions] codex: ${n.codex?.length||0} new, ${s.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]||[];if(n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.skippedSessions?.[e]){const r=new Set(t);n.tasteOnboarding.skippedSessions[e]=n.tasteOnboarding.skippedSessions[e].filter(e=>!r.has(e)),0===n.tasteOnboarding.skippedSessions[e].length&&delete n.tasteOnboarding.skippedSessions[e]}n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0;try{const t=e.tasteOnboarding.learnedSessions||{},n=await findNewSessions(t);e.tasteOnboarding.skippedSessions||(e.tasteOnboarding.skippedSessions={});for(const[t,r]of Object.entries(n))if(r.length>0){const n=e.tasteOnboarding.skippedSessions[t]||[];e.tasteOnboarding.skippedSessions[t]=Array.from(new Set([...n,...r]))}}catch{dlog("[Onboarding] failed to record skipped sessions, skip flag still set")}await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:s}){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})`),s(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:s,onboarding:o,uiOverlays:i,skipOnboarding:a}){G(()=>{if(n.shouldExit){r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),s.providerNotificationTimer.current&&clearTimeout(s.providerNotificationTimer.current),s.modelNotificationTimer.current&&clearTimeout(s.modelNotificationTimer.current);try{e()}catch{process.exit(0)}}},[n.shouldExit,e]),G(()=>()=>{r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),s.providerNotificationTimer.current&&clearTimeout(s.providerNotificationTimer.current),s.modelNotificationTimer.current&&clearTimeout(s.modelNotificationTimer.current)},[]),G(()=>{(async()=>{if("anthropic"===s.currentProvider&&s.isOAuthMode)try{await on.getValidAccessToken()||r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}catch{r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[s.currentProvider,s.isOAuthMode]),G(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(Wo())},7e3);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),G(()=>{a||triggerTasteOnboarding({projectTrusted:o.projectTrusted,onboardingComplete:o.onboardingComplete,isOnboardingMode:o.showTasteOnboarding,tasteOnboardingCheckedRef:o.tasteOnboardingCheckedRef,setIsOnboardingMode:o.setShowTasteOnboarding})},[o.projectTrusted,o.onboardingComplete,o.showTasteOnboarding,a]),G(()=>{if(o.showTasteOnboarding&&!o.tasteOnboardingEntryId){const e=Mo();o.setTasteOnboardingEntryId(e.id),t.setFeed(t=>[...t,e])}!o.showTasteOnboarding&&o.tasteOnboardingEntryId&&(t.setFeed(e=>e.filter(e=>e.id!==o.tasteOnboardingEntryId)),o.setTasteOnboardingEntryId(null))},[o.showTasteOnboarding,o.tasteOnboardingEntryId])}__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(triggerTasteOnboarding,"triggerTasteOnboarding"),__name(useLifecycle,"useLifecycle"),Nt(),PC(),CE(),Jo(),Nt(),ln(),ar(),PC(),Ot(),Nt();var cv=" ";function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showProviderSelector:n,showModelSelector:r,showMemorySelector:s,showMcpManager:o,showLearningFeed:i,showRewindSelector:a,showLoginOverlay:l,showAddDirModal:u,authComponentInfo:d,setShowLearningFeed:m,setShowModelSelector:p,setStaticKey:g,transcriptMode:h,setTranscriptMode:f,isCmdCodeBusy:y,liveAgents:w,queuedMessagesRef:S,setInput:b,setQueuedMessages:E,setFeed:C,setLiveAgents:v,setIsCmdCodeBusy:T,setRetryAttempt:k,setStatus:_,pendingExitKey:P,setPendingExitKey:A,pendingExitKeyRef:x,lastExitKeyTimeRef:I,exitConfirmationTimeoutRef:N,resetPendingExitKey:R,pendingPermission:$,setPendingPermission:L,pendingQuestion:M,setPendingQuestion:O,setShouldExit:D,contextEngineRef:q,handleToggleAutoAccept:F,handleDoubleEscapeEmpty:j,respondToPrompt:z,createErrorEntry:B}){const U=__name(()=>{if(!q.current)return;q.current.interrupt(!0);const e=w.length>0;if(T(!1),k(null),v([]),_("Interrupted by user"),!e){const e=B("Interrupted by user");C(t=>[...t,e])}if(S.current.length>0){const e=S.current.join("\n");b(t=>t?e+"\n"+t:e),E([]),S.current=[]}},"handleInterrupt");Z((w,S)=>{if(S.shift&&S.tab||""===w)F();else if(e||t||n||r||s||o||d||i||a||l||u)P&&R();else{if(""===w||S.ctrl&&"c"===w){if(y&&q.current)return void U();const e=Date.now(),t=e-I.current;return I.current=e,"ctrl-c"===x.current&&t<2e3?(N.current&&(clearTimeout(N.current),N.current=null),void D(!0)):(b(()=>""),x.current="ctrl-c",A("ctrl-c"),N.current&&clearTimeout(N.current),void(N.current=setTimeout(()=>{x.current=null,A(null),N.current=null},2e3)))}if(S.ctrl&&"t"===w)return kC(),m(!i),void g(e=>e+1);if(getIsExpandToolShortcut(S,w))return kC(),f("off"===h?"limited":"off"),void g(e=>e+1);if(S.ctrl&&"e"===w&&"off"!==h)return kC(),f("limited"===h?"full":"limited"),void g(e=>e+1);if(S.meta&&"p"===w||isAltP(w))p(!0);else if(S.escape){if(M)return M.reject(new Error("Question cancelled by user")),O(null),void _("Question cancelled");if($)return z({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),$.resolve(!1),L(null),void _("Permission denied");y&&q.current&&U()}}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:s,pendingOps:o,permissionState:i,statusState:a,authState:l,contextEngineRef:u,loadTasteStatus:d,loadCurrentProvider:m,setInput:p}){const g=V(()=>{i.setPermissionMode(e=>{let t="standard";if("standard"===e&&(t="auto-accept"),"auto-accept"===e&&(t="plan"),"auto-accept"===t&&o.pendingPermission){const e={label:"Yes",value:"yes",description:"Allow this action",scope:void 0};i.respondToPrompt(e),o.pendingPermission.resolve(!0),o.setPendingPermission(null)}return"plan"===t&&o.pendingPermission&&(o.pendingPermission.resolve(!1),o.setPendingPermission(null)),t})},[i.setPermissionMode,i.respondToPrompt,o.pendingPermission,o.setPendingPermission]),h=V(()=>{const e=!t.isCmdCodeBusy&&!o.pendingPermission&&!o.pendingQuestion,n=u.current?.hasCheckpoints()??!1;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,o.pendingPermission,o.pendingQuestion,r.setShowRewindSelector]),f=V(s=>{if(n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),kC(),s?.skipped){const e=xo("",{isTasteSkip:!0});t.setFeed(t=>[...t,e])}r.setStaticKey(e=>e+1),e&&r.setShowSessionSelector(!0)},[e,n,r,t]),y=V(async()=>{try{if(await Yb.initializeProject(),n.setShowTrustPrompt(!1),e)return console.log("No conversations found to resume."),void s.setShouldExit(!0);n.setProjectTrusted(!0),d(),m()}catch(e){console.error("Failed to initialize project:",e),n.setShowTrustPrompt(!1),s.setShouldExit(!0)}},[e,n,s,d,m]),w=V(()=>{s.setShouldExit(!0)},[s.setShouldExit]);return useKeyboard({showTasteConfig:r.showTasteConfig,showSkillsConfig:r.showSkillsConfig,showProviderSelector:r.showProviderSelector,showModelSelector:r.showModelSelector,showMemorySelector:r.showMemorySelector,showMcpManager:r.showMcpManager,showLearningFeed:r.showLearningFeed,showRewindSelector:r.showRewindSelector,showLoginOverlay:r.showLoginOverlay,showAddDirModal:r.showAddDirModal,authComponentInfo:l.authComponentInfo,setShowLearningFeed:r.setShowLearningFeed,setShowModelSelector:r.setShowModelSelector,setStaticKey:r.setStaticKey,transcriptMode:r.transcriptMode,setTranscriptMode:r.setTranscriptMode,isCmdCodeBusy:t.isCmdCodeBusy,liveAgents:t.liveAgents,queuedMessagesRef:t.queuedMessagesRef,setInput:p,setQueuedMessages:t.setQueuedMessages,setFeed:t.setFeed,setLiveAgents:t.setLiveAgents,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setRetryAttempt:a.setRetryAttempt,setStatus:a.setStatus,pendingExitKey:s.pendingExitKey,setPendingExitKey:s.setPendingExitKey,pendingExitKeyRef:s.pendingExitKeyRef,lastExitKeyTimeRef:s.lastExitKeyTimeRef,exitConfirmationTimeoutRef:s.exitConfirmationTimeoutRef,resetPendingExitKey:s.resetPendingExitKey,pendingPermission:o.pendingPermission,setPendingPermission:o.setPendingPermission,pendingQuestion:o.pendingQuestion,setPendingQuestion:o.setPendingQuestion,setShouldExit:s.setShouldExit,contextEngineRef:u,handleToggleAutoAccept:g,handleDoubleEscapeEmpty:h,respondToPrompt:i.respondToPrompt,createErrorEntry:Lo}),{handleToggleAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:w}}__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Nt(),Nt(),Ot(),Jo(),ir(),Nt();var uv='You are an expert code reviewer. Do follow these steps:\n\nGather PR context using the GitHub CLI:\n1. When no PR number is given, list open PRs with `gh pr list` and ask which one to review\n2. Fetch PR metadata via `gh pr view <number>`\n3. Retrieve the changeset with `gh pr diff <number>`\n4. One go gather context: Run gh pr view <number> && echo "---DIFF---" && gh pr diff <number>\n5. Analyze the changes and provide a thorough code review that includes:\n\t- Overview of the PR is doing\n\t- Analysis of the code quality and style\n\t- Give specific suggestions for improvement\n\t- Highlight any potential bugs/issues or risks\n\t- Score PR on a scale of 1-5 based on overall table with quality and readiness for merging\nKeep your review concise, less wordy, but thorough.\nFocus on:\n- Correctness of code\n- Following project conventions\n- Performance issues and implications\n- Test coverage\n- Security considerations\n\nBe less wordy. If you make a table, don\'t go over 60pts.\nFormat your review in sections and bullets.';function buildReviewPrompt({prNumber:e}){const t=e.trim();return t?`${uv}\n\nReview PR number: ${t}`:`${uv}\n\nReview PR number: `}function loadCustomCommands(){const e=[],n=t.join(process.cwd(),".commandcode","commands"),r=t.join(f.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,s=""){if(S.existsSync(n))try{const o=S.readdirSync(n,{withFileTypes:!0});for(const i of o){const o=t.join(n,i.name);if(i.isDirectory())loadCommandsFromDirectory(o,r,s?`${s}/${i.name}`:i.name);else if(i.isFile()&&i.name.endsWith(".md")){const n=t.basename(i.name,".md"),a=S.readFileSync(o,"utf-8").trim();e.push({name:n,source:r,content:a,subdirectory:s})}}}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}__name(buildReviewPrompt,"buildReviewPrompt"),Nt(),Nt(),Ot(),Nt(),Ot(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),ir(),Nt();var dv=["Code","Code - Insiders","VSCodium","Cursor"],mv="Code",pv={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},gv=__name(e=>m(e).href,"formatPathForTerminal"),hv=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),fv=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),yv=__name(({home:t,configSegments:n,variants:r})=>{for(const s of r){const r=fv({home:t,configSegments:n,variant:s});if(w.existsSync(e.dirname(r)))return s}return null},"findExistingVariant"),wv=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Sv(t.when)},"isTerminalShiftEnterBinding"),Sv=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),bv=__name(e=>{const t=He(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),Ev=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),Cv=__name(({error:e,content:t})=>{const n=e.message;return Ev(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"),vv=__name(e=>{let t="",n=!1,r=!1;for(let s=0;s<e.length;s++){const o=e[s];if(n)t+=o,r?r=!1:"\\"===o?r=!0:'"'===o&&(n=!1);else if('"'!==o){if(","===o){let t=s+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=o}else n=!0,t+=o}return t},"removeTrailingCommas"),Tv=__name(e=>{try{const t=He(e),n=vv(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:Cv({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),kv=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:gv(t)}),"createSuccessResult"),_v=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:gv(t)}),"createErrorResult"),Pv=__name(()=>{const t=h.homedir(),n=h.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=hv(n);if(!r)return fv({home:t,configSegments:[".config"],variant:mv});const s=yv({home:t,configSegments:r,variants:dv});return fv({home:t,configSegments:r,variant:s??mv})},"getVSCodeKeybindingsPath"),Av=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)wv(n)&&(n.command===pv.command&&n.args?.text===pv.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),xv=__name(t=>{try{if(!w.existsSync(t)){const n=e.dirname(t);return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=w.readFileSync(t,"utf-8");if(bv(n))return{rawContent:n,keybindings:[]};const r=Tv(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:_v({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):_v({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return _v({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),Iv=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(pv,null,2);if(bv(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return _v({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const s=e.lastIndexOf("}",r);return-1===s?_v({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,s+1)+",\n"+n+e.substring(s+1)},"generateNewContent");function setupVSCodeTerminal(){const e=Pv();try{const t=xv(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,s=Av(r);if(s.hasConflicting)return _v({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(s.hasCompatible)return kv({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const o=Iv({rawContent:n,keybindingsPath:e});return"string"!=typeof o?o:(w.writeFileSync(e,o,"utf-8"),kv({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return _v({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"),jr(),rr();var Nv=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear",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.MCP="/mcp",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.REVIEW="/review",e.PR_COMMENTS="/pr-comments",e))(Nv||{}),Rv=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/provider","/model","/memory","/init","/agents","/mcp","/compact","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/pr-comments"]),$v=[{command:"/add-dir",description:"Add directory to workspace context"},{command:"/agents",description:"Manage agent configurations"},{command:"/clear",description:"Clear the conversation history (reset, new)"},{command:"/compact",description:"Compact the conversation history"},{command:"/exit",description:"Exit Command Code"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/help",description:"Show available shortcuts"},{command:"/ide",description:"Install extension to fetch IDE context"},{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/memory",description:"Manage Command Code memory"},{command:"/model",description:"Switch between Command Code models"},{command:"/pr-comments",description:"Fetch all PR comments for current branch"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/resume",description:"Resume a past conversation"},{command:"/review",description:"Review a pull request (optional PR number)"},{command:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/unshare",description:"Stop sharing conversation"}],Lv=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[s,o]=W(0),[i,a]=W(0),{stdout:l}=X(),u=l?.columns??80,d=Math.max(20,u-22-2-1-2),m=H(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...$v.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!r)return e;const t=r.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let s=0;return n.startsWith("/"+t)?s+=100:n.includes(t)&&(s+=50),r.includes(t)&&(s+=25),{...e,score:s}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[r]),p=H(()=>{const e=i,t=Math.min(e+8,m.length);return m.slice(e,t)},[m,i]);return G(()=>{o(0),a(0)},[r]),Z((r,l)=>{if(l.escape)n();else if(l.upArrow)o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t});else if(l.downArrow)o(e=>{const t=Math.min(m.length-1,e+1);return t>=i+8&&a(Math.max(0,t-8+1)),t});else{if(l.return){const t=m[s];return void(t&&e(t.command))}if(l.tab||l.rightArrow){const e=m[s];return void(e&&t(e.command))}}}),0===m.length?B.createElement(K,{flexDirection:"column",paddingLeft:2},B.createElement(Y,{color:Ln.DIM},"No commands found")):(m.length,B.createElement(K,{flexDirection:"column",paddingLeft:1},B.createElement(K,{columnGap:2},B.createElement(K,{flexDirection:"column",width:22},p.map((e,t)=>{const n=i+t;return B.createElement(Y,{key:n,color:s===n?Ln.WHITE:Ln.DIM,wrap:"truncate"},e.command)})),B.createElement(K,{flexDirection:"column"},p.map((e,t)=>{const n=i+t;return B.createElement(Y,{key:n,color:s===n?Ln.WHITE:Ln.DIM,wrap:"truncate"},truncateString({text:e.description,maxChars:d}))})))))},"CommandMenu");qE(),Nt(),Nt(),ar(),rr();var Mv=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),Ov=__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"),Dv=__name(({icon:e,label:t,children:n})=>B.createElement(Y,null,B.createElement(Y,{color:Ln.CYAN},e," "),B.createElement(Y,{dimColor:!0},t.padEnd(12)),n),"Row"),qv=__name(({title:e})=>B.createElement(Y,null,B.createElement(Y,{color:Ln.GRAY},"───"),B.createElement(Y,{color:Ln.WHITE}," ",e," "),B.createElement(Y,{color:Ln.GRAY},"─".repeat(35))),"Header"),Fv=__name(({title:e,marginTop:t=0,children:n})=>B.createElement(K,{flexDirection:"column",marginTop:t},B.createElement(qv,{title:e}),B.createElement(K,{flexDirection:"column",paddingY:1},n)),"Section"),jv=__name(({cpuCount:e,totalMem:t})=>B.createElement(Fv,{title:"System Information"},B.createElement(Dv,{icon:be.bullet,label:"Date"},B.createElement(Y,null,formatDate())),B.createElement(Dv,{icon:be.pointer,label:"Platform"},B.createElement(Y,{color:Ln.GREEN},Mv(h.platform())),B.createElement(Y,{dimColor:!0}," ","(",h.platform(),", ",h.arch(),")")),B.createElement(Dv,{icon:be.triangleUp,label:"Hostname"},B.createElement(Y,null,h.hostname())),B.createElement(Dv,{icon:be.bullet,label:"User"},B.createElement(Y,{color:Ln.YELLOW},h.userInfo().username)),B.createElement(Dv,{icon:be.bullet,label:"CPUs"},B.createElement(Y,{color:Ln.MAGENTA},e," cores")),B.createElement(Dv,{icon:be.bullet,label:"Memory"},B.createElement(Y,{color:Ln.CYAN},t," GB")),B.createElement(Dv,{icon:be.play,label:"Uptime"},B.createElement(Y,null,Ov(h.uptime()))),B.createElement(Dv,{icon:be.arrowRight,label:"Home"},B.createElement(Y,{dimColor:!0},h.homedir())),B.createElement(Dv,{icon:be.pointer,label:"Shell"},B.createElement(Y,null,process.env.SHELL||"N/A")),B.createElement(Dv,{icon:be.bullet,label:"Node"},B.createElement(Y,{color:Ln.GREEN},process.version))),"SystemInfoSection"),zv=__name(({cpus:e})=>B.createElement(Fv,{title:"CPU Details",marginTop:1},e.map((e,t)=>B.createElement(Dv,{key:t,icon:be.bullet,label:`Core ${t}`},B.createElement(Y,null,e.model.trim()),B.createElement(Y,{color:Ln.YELLOW}," @ ",e.speed," MHz")))),"CPUDetailsSection"),Bv=__name(({networkInterfaces:e})=>B.createElement(Fv,{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)=>B.createElement(Dv,{key:`${e}-${n}`,icon:be.bullet,label:e},B.createElement(Y,{color:Ln.GREEN},t.address))):null})),"NetworkSection"),Uv=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>B.createElement(K,{flexDirection:"column"},B.createElement(Y,null,"System Information"),B.createElement(Y,null,"─".repeat(40)),B.createElement(Y,null,"Date ",formatDate()),B.createElement(Y,null,"Platform ",Mv(h.platform())," (",h.platform(),","," ",h.arch(),")"),B.createElement(Y,null,"Hostname ",h.hostname()),B.createElement(Y,null,"User ",h.userInfo().username),B.createElement(Y,null,"CPUs ",e.length," cores"),B.createElement(Y,null,"Memory ",t," GB"),B.createElement(Y,null,"Uptime ",Ov(h.uptime())),B.createElement(Y,null,"Home ",h.homedir()),B.createElement(Y,null,"Shell ",process.env.SHELL||"N/A"),B.createElement(Y,null,"Node ",process.version),r&&B.createElement(B.Fragment,null,B.createElement(Y,null,"\n","CPU Details"),B.createElement(Y,null,"─".repeat(40)),e.map((e,t)=>B.createElement(Y,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),B.createElement(Y,null,"\n","Network"),B.createElement(Y,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>B.createElement(Y,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Wv=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>B.createElement(K,{flexDirection:"column"},B.createElement(jv,{cpuCount:e.length,totalMem:t}),r&&B.createElement(zv,{cpus:e}),r&&B.createElement(Bv,{networkInterfaces:n})),"StyledInfo"),Qv=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=te();G(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=h.cpus(),s=h.networkInterfaces(),o=Math.round(h.totalmem()/1024/1024/1024);return t?B.createElement(Uv,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e}):B.createElement(Wv,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e})},"InfoUI"),Gv={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},Hv=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),Vv=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(Hv("__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"),Kv=__name(()=>{const e=Vv();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&Gv[t]?Gv[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),Yv=__name(()=>{if("win32"===f.platform()){const e=process.env.COMSPEC;return e?a(e):process.env.SHELL?a(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=I(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=a(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?a(e):"N/A"},"getShellName"),Jv=__name(()=>{const e=Vv();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),Xv=__name(()=>{try{const e=I("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:Mv(f.platform()),terminal:Kv(),shell:Yv(),version:Xv(),ide:Jv()}}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?"":""}`}function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",s=!1,o="";for(let e=0;e<t.length;e++){const i=t[e];'"'!==i&&"'"!==i||s?i===o&&s?(s=!1,o=""):" "!==i||s?r+=i:(r.trim()&&n.push(r.trim()),r=""):(s=!0,o=i)}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 s=n.substring(0,r),o=n.substring(r+1).trim();return{commandName:s,rawArguments:o,positionalArgs:parsePositionalArguments({input:o})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let s=t;return s=s.replace(/\$ARGUMENTS/g,n),s=s.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:s}}async function handleCompactCommand({contextEngineRef:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:s,setStaticKey:o}){if(e.current)if(e.current.isRequestInProgress())t(e=>[...e,xo("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{r(!0),n("Compacting conversation...");const i=await e.current.manualCompact();kC(),o(e=>e+1);let a="Compacted conversation.";i.didCompact||(a="Conversation is already compact."),i.didCompact&&i.tokensSaved>0&&(a=`Compacted conversation, saved ~${i.tokensSaved.toLocaleString()} tokens.`),t(e=>[...e,xo(a)]),r(!1),n("Ready..."),s({current:e.current.getContextTokensUsed()||0,limit:xE})}catch(e){const s=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;t(e=>[...e,Lo(s)]),r(!1),n("Ready...")}else t(e=>[...e,xo("No active conversation to compact.")])}function handleRewindCommand({contextEngineRef:e,setFeed:t,setShowRewindSelector:n}){e.current?e.current.hasCheckpoints()?n(!0):t(e=>[...e,xo("No checkpoints available. Start sending messages to create checkpoints.")]):t(e=>[...e,xo("No active conversation to rewind.")])}async function handleRewindSelect({messageId:e,mode:t,contextEngineRef:n,setFeed:r,setStatus:s,setShowRewindSelector:o,setStaticKey:i,setInput:a}){if(o(!1),n.current)try{const o=n.current.listCheckpoints().find(t=>t.messageId===e);s("Restoring checkpoint...");const l=await n.current.restoreToCheckpoint({messageId:e,mode:t});if(l.success){const e=n.current.getSessionManager(),t=n.current.getMessages();r(e.reconstructFeedFromMessages(t)),kC(),i(e=>e+1),o?.userPrompt&&a(o.userPrompt);const u=[];l.filesRestored>0&&u.push(`${l.filesRestored} file${l.filesRestored>1?"s":""} restored`),l.filesDeleted>0&&u.push(`${l.filesDeleted} file${l.filesDeleted>1?"s":""} deleted`),l.messagesRemoved>0&&u.push(`${l.messagesRemoved} message${l.messagesRemoved>1?"s":""} removed`);const d=u.length>0?`Restored to checkpoint: ${u.join(", ")}.`:"Restored to checkpoint.";return r(e=>[...e,xo(d)]),void s("Ready...")}r(e=>[...e,Lo(`Failed to restore: ${l.error}`)]),s("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;r(e=>[...e,Lo(t)]),s("Ready...")}}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}async function handleLoginCommand({setFeed:e,setShowLoginOverlay:t}){const n=Lt();if(await getAuthKey(n)){let t="";try{const e=await loadCredentials();t=e?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const n=t&&"API Key"!==t&&"Manual API Key"!==t?` as ${t}`:"";return void e(e=>[...e,xo(`Already logged in${n}`)])}t(!0)}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:s,contextEngineRef:o}){if(n(!1),!e)return r(e=>[...e,Lo(t)]),void s("Ready...");r(e=>[...e,xo(t)]),o.current&&o.current.refreshRequest(),s("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,xo("Authentication cancelled.")]),n("Ready...")}async function handleLogoutCommand({setFeed:e,contextEngineRef:t}){const n=await performLogout();if(!n.success)return void e(e=>[...e,Lo(`Logout failed: ${n.error}`)]);if(t.current&&t.current.refreshRequest(),!n.wasAuthenticated)return void e(e=>[...e,xo("Not currently authenticated.")]);const r=n.warnings.length>0?`Successfully logged out from Command Code. Warnings: ${n.warnings.join(", ")}`:"Successfully logged out from Command Code.";e(e=>[...e,xo(r)])}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),Nt(),__name(createOSC8Link,"createOSC8Link"),Nt(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),PC(),Nt(),Jo(),PC(),$E(),__name(handleCompactCommand,"handleCompactCommand"),Nt(),Jo(),PC(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Nt(),Jo(),Qs(),Jr(),xs(),Ot(),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Nt(),Sl(),$n(),nr();var Zv=Ve(x);function getVsixPath(){try{const e=t.dirname(u(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return S.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),dl.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await Zv(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp("commandcode.commandcode-vscode@([\\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 Zv(`${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}}__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled");var eT={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"};async function ensureExtensionInstalled(){if(process.env.CI)return;const e=sl();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:Be.green("✔"),installed:Be.green("✔"),needs_reload:Be.yellow("◌"),failed:Be.red("✖"),not_in_ide:Be.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=>Be.dim(` ${e}`)),""]}async function runIDESetup(){const e=sl(),t=e?eT[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new dl,r=await n.connect(500);if(n.disconnect(),r)return{status:"connected",ide:t};const{installed:s}=await checkInstalled(e);return s?{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."]}}async function handleHelpCommand({setFeed:e}){const{createSystemEntry:t}=await Promise.resolve().then(()=>(Jo(),Yo));e(e=>[...e,t("KEYBOARD SHORTCUTS\nCOMMANDS")])}async function handleTerminalSetupCommand({setFeed:e}){const t=Ao(`/${Tt.TERMINAL_SETUP}`),n=setupVSCodeTerminal(),r=Oo(n.message,!n.success,n.details);e(e=>[...e,t,r])}async function handleIDESetupCommand({setFeed:e}){const t=await runIDESetup(),n=Do(t.status,t.ide,t.details);e(e=>[...e,n])}async function handleClearCommand({setFeed:e,setLiveAgents:t,setShareInfo:n,setShowShareNotification:r,setUnshareNotificationMessage:s,setStaticKey:o,setContextUsage:i,setInteractionTokens:a,contextEngineRef:l,setSessionId:u,createContextEngineCallbacks:d,clearSessionPermissions:m}){if(e([]),t([]),kC(),n(null),r(!1),s(""),l.current){const e=l.current.getSessionManager();e&&await e.deleteShareInfo(),l.current=null;const t=crypto.randomUUID();u(t),m();const{ContextEngine:n}=await Promise.resolve().then(()=>(_C(),TC));l.current=new n(d(t),t)}o(e=>e+1),i(null),a(0)}async function handleInitCommand({setFeed:e}){try{const t=process.cwd(),n=`Created AGENTS.md at ${await initProjectMemory(t)}. You can now edit it with /memory or open it in your editor.`;e(e=>[...e,xo(n)])}catch(t){const n=`Error: Failed to initialize AGENTS.md: ${t instanceof Error?t.message:"Unknown error"}`;e(e=>[...e,xo(n)])}}async function handleFeedbackCommand({setFeed:e},t){const n=buildGitHubIssueUrl(t);try{await ie(n,{wait:!1,background:!0}),e(e=>[...e,xo(`Opened ${createOSC8Link(n,"GitHub issue")} in your browser`)])}catch{const{createSystemEntry:t,createErrorEntry:r}=await Promise.resolve().then(()=>(Jo(),Yo));e(e=>[...e,r("Failed to open browser"),t(createOSC8Link(n,"Open GitHub issue manually"))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const s=Mo();n(s.id),r(e=>[...e,s])}async function handleCommand(e,t){if(e.startsWith("/resume:")){const n=e.substring(8);return await handleSelectSession({selectedSessionId:n,sessionLoadIdRef:t.sessionLoadIdRef,contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setLiveAgents:t.setLiveAgents,setSessionId:t.setSessionId,setShowSessionSelector:t.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:t.setPermissionMode,setStaticKey:t.setStaticKey,setShareInfo:t.setShareInfo,createContextEngineCallbacks:t.createContextEngineCallbacks}),{status:"handled"}}const n=parseCommandInput({input:e});if(!n)return{status:"unknown"};const{commandName:r,rawArguments:s,positionalArgs:o}=n;if(Rv.has(r)&&s.trim().length>0)return{status:"unknown"};if("/exit"===r)return t.setShouldExit(!0),{status:"handled"};if("/clear"===r)return await handleClearCommand(t),{status:"handled"};if("/help"===r)return await handleHelpCommand(t),{status:"handled"};if("/share"===r)return await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/unshare"===r)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/taste"===r)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===r)return handleLearnCommand(t),{status:"handled"};if("/skills"===r)return t.setShowSkillsConfig(!0),{status:"handled"};if("/provider"===r)return isInternalTeamFlagEnforced()?(t.setShowProviderSelector(!0),{status:"handled"}):(t.setStatus("Provider selection not available"),{status:"handled"});if("/model"===r)return t.setShowModelSelector(!0),{status:"handled"};if("/memory"===r)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===r)return t.setShowSessionSelector(!0),{status:"handled"};if("/init"===r)return await handleInitCommand(t),{status:"handled"};if("/agents"===r)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===r)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===r)return await handleCompactCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setContextUsage:t.setContextUsage,setStaticKey:t.setStaticKey}),{status:"handled"};if("/rewind"===r)return handleRewindCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/login"===r)return await handleLoginCommand({setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay}),{status:"handled"};if("/logout"===r)return await handleLogoutCommand({setFeed:t.setFeed,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/feedback"===r)return await handleFeedbackCommand(t),{status:"handled"};if("/terminal-setup"===r)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===r)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===r)return t.setShowAddDirModal(!0),{status:"handled"};if("/review"===r){const e=s.trim(),{handleSubmit:n}=await Promise.resolve().then(()=>(IC(),xC));return await n({input:buildReviewPrompt({prNumber:s}),role:"user",displayMessage:e?`/review ${e}`:"/review",feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}if("/pr-comments"===r)return await handleSubmit({input:"Fetch and display all comments from the current GitHub pull request.\n\n Run these commands in order:\n\n 1. `gh pr view --json number,headRepository` — if this fails, reply \"No comments found.\" and stop.\n 2. `gh api --paginate '/repos/{owner}/{repo}/issues/NUMBER/comments' --jq '.[] | {body,\n user: .user.login, id, created_at}' > /tmp/pr-NUMBER-issue-comments.json`\n 3. `gh api --paginate '/repos/{owner}/{repo}/pulls/NUMBER/comments' --jq '.[] | {body,\n diff_hunk: (.diff_hunk | split(\"\n\") | .[-5:] | join(\"\n\")), path, line, user: .user.login,\n in_reply_to_id, id, created_at}' > /tmp/pr-NUMBER-review-comments.json`\n\n If both return empty, reply \"No comments found.\"\n\n `{owner}` and `{repo}` are gh template variables — write them literally, never substitute. Always\n use `--jq` (not piped `| jq`).\n\n Read the temp JSON files to build output comments directly in markdown using the format:\n\n ## PR Comments\n\n - @author (date):\n > body\n\n ## Review Comments\n\n - @author path#line:\n ```diff (replace ```suggestion code blocks with ```diff to avoid rendering errors)\n [diff_hunk]\n ```\n > body [replies indented by in_reply_to_id]\n\n Number the comments in the order they were created (created_at).\n No explanatory text, no horizontal rules. No extra space in the end.",role:"user",displayMessage:"/pr-comments",feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"};const i=getCustomCommandContent(r);if(i){const e=processCommandTemplate({template:i,rawArguments:s,positionalArgs:o}),{handleSubmit:n}=await Promise.resolve().then(()=>(IC(),xC));return await n({input:e.content,role:"user",feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}return{status:"unknown"}}function useCommandCtx({feedState:e,sessionState:t,statusState:n,uiOverlays:r,onboarding:s,exitState:o,permissionState:i,contextEngineRef:a,isSubmittingRef:l,executeBash:u,createContextEngineCallbacks:d,setInput:m}){const p=H(()=>({feed:e.feed,setFeed:e.setFeed,setLiveAgents:e.setLiveAgents,setQueuedMessages:e.setQueuedMessages,setStatus:n.setStatus,setInteractionTokens:n.setInteractionTokens,setContextUsage:n.setContextUsage,setStaticKey:r.setStaticKey,updateStatus:n.updateStatus,setUpdateStatus:n.setUpdateStatus,billingLink:n.billingLink,setBillingLink:n.setBillingLink,shareInfo:n.shareInfo,setShareInfo:n.setShareInfo,setShowShareNotification:n.setShowShareNotification,setUnshareNotificationMessage:n.setUnshareNotificationMessage,setShowTasteConfig:r.setShowTasteConfig,setShowSkillsConfig:r.setShowSkillsConfig,setShowProviderSelector:r.setShowProviderSelector,setShowModelSelector:r.setShowModelSelector,setShowMemorySelector:r.setShowMemorySelector,setShowAgentsConfig:r.setShowAgentsConfig,setShowMcpManager:r.setShowMcpManager,setShowRewindSelector:r.setShowRewindSelector,setShowAddDirModal:r.setShowAddDirModal,setShowLoginOverlay:r.setShowLoginOverlay,setShowTasteOnboarding:s.setShowTasteOnboarding,setAutoLearnTaste:s.setAutoLearnTaste,setTasteOnboardingEntryId:s.setTasteOnboardingEntryId,sessionId:t.sessionId,setSessionId:t.setSessionId,sessionLoadIdRef:t.sessionLoadIdRef,sessionLoaded:t.sessionLoaded,setSessionLoaded:t.setSessionLoaded,setShowSessionSelector:r.setShowSessionSelector,setPermissionMode:i.setPermissionMode,contextEngineRef:a,clearSessionPermissions:i.clearSessionPermissions,createContextEngineCallbacks:d,setShouldExit:o.setShouldExit,setInput:m,isSubmittingRef:l,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:u}),[e,t,n,r,s,o,i,a,l,u,d,m]),g=Q(p);return g.current=p,{commandCtx:p,onCommand:V(e=>handleCommand(e,g.current),[])}}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:s,setShowProviderNotification:o,providerNotificationTimer:i}){try{const a=getProviderConfig(e);if(a?.requiresAuth&&a.checkAuth&&!await a.checkAuth()&&a.authComponent)return void r({provider:e,Component:a.authComponent});await updateUserConfig({provider:e}),t(e),n(!1),s(`Provider set to ${getProviderDisplayName(e)}`),i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),s("Failed to set provider"),n(!1)}}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:s,setShowProviderNotification:o,providerNotificationTimer:i}){e&&(t(null),n(!1),r(e.provider),s(`${getProviderDisplayName(e.provider)} authentication successful`),i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},5e3))}function handleAuthCancel({setAuthComponentInfo:e}){e(null)}function getModelDisplayName(e){const t=Object.values(kt).find(t=>t.id===e);return t?t.name:e}async function handleModelSelect({modelId:e,setCurrentModel:t,setShowModelSelector:n,setStatus:r,modelNotificationTimer:s,setShowModelNotification:o}){try{await setSelectedModel({model:e}),t(e),n(!1),r(`Model set to ${getModelDisplayName(e)}`),s.current&&clearTimeout(s.current),o(!0),s.current=setTimeout(()=>{o(!1),s.current=null},5e3)}catch(e){console.error("Failed to set model:",e),r("Failed to set model"),n(!1)}}function handleModelCancel({setShowModelSelector:e}){e(!1)}__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup"),IC(),__name(handleHelpCommand,"handleHelpCommand"),__name(handleTerminalSetupCommand,"handleTerminalSetupCommand"),__name(handleIDESetupCommand,"handleIDESetupCommand"),__name(handleClearCommand,"handleClearCommand"),__name(handleInitCommand,"handleInitCommand"),__name(handleFeedbackCommand,"handleFeedbackCommand"),__name(handleLearnCommand,"handleLearnCommand"),__name(handleCommand,"handleCommand"),__name(useCommandCtx,"useCommandCtx"),Nt(),Nt(),ir(),nr(),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel"),Nt(),Ot(),nr(),__name(getModelDisplayName,"getModelDisplayName"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel");var tT=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l}){const u=Q({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l});return u.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l},{onSelectSession:V(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a}=u.current;handleSelectSession({selectedSessionId:e,sessionLoadIdRef:n.sessionLoadIdRef,contextEngineRef:i,setFeed:t.setFeed,setLiveAgents:t.setLiveAgents,setSessionId:n.setSessionId,setShowSessionSelector:s.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,setPermissionMode:o.setPermissionMode,setStaticKey:s.setStaticKey,setShareInfo:r.setShareInfo,createContextEngineCallbacks:a})},[]),onNewSession:V(()=>{const{feedState:e,sessionState:t,uiOverlays:n,permissionState:r,contextEngineRef:s}=u.current;handleNewSession({contextEngineRef:s,setFeed:e.setFeed,setLiveAgents:e.setLiveAgents,setSessionId:t.setSessionId,setShowSessionSelector:n.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:r.setPermissionMode})},[]),onRewindSelect:V(({messageId:e,mode:t})=>{const{feedState:n,statusState:r,uiOverlays:s,contextEngineRef:o,setInput:i}=u.current;handleRewindSelect({messageId:e,mode:t,contextEngineRef:o,setFeed:n.setFeed,setStatus:r.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:i})},[]),onRewindCancel:V(()=>{handleRewindCancel({setShowRewindSelector:u.current.uiOverlays.setShowRewindSelector})},[]),onLoginComplete:V((e,t)=>{const{feedState:n,statusState:r,uiOverlays:s,contextEngineRef:o}=u.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:s.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus,contextEngineRef:o})},[]),onLoginCancel:V(()=>{const{feedState:e,statusState:t,uiOverlays:n}=u.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),handleProviderSelect:V(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:r.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:n.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer})},[]),handleProviderCancel:V(()=>{handleProviderCancel({setShowProviderSelector:u.current.uiOverlays.setShowProviderSelector})},[]),handleModelSelect:V(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleModelSelect({modelId:e,setCurrentModel:t.setCurrentModel,setShowModelSelector:r.setShowModelSelector,setStatus:n.setStatus,modelNotificationTimer:t.modelNotificationTimer,setShowModelNotification:tT})},[]),handleModelCancel:V(()=>{handleModelCancel({setShowModelSelector:u.current.uiOverlays.setShowModelSelector})},[]),handleAuthSuccess:V(()=>{const{authState:e,statusState:t,uiOverlays:n}=u.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:n.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:t.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer})},[]),handleAuthCancel:V(()=>{handleAuthCancel({setAuthComponentInfo:u.current.authState.setAuthComponentInfo})},[])}}__name(useMainActionCallbacks,"useMainActionCallbacks"),Nt(),Nt(),Nt();var nT=__name(({staticKey:e})=>B.createElement(J,{items:[{staticKey:e}],key:e},()=>B.createElement(Y,{key:e},"\0")),"Responsive");Nt(),Ot(),rr();var rT=__name(({onTrust:e,onExit:t})=>{const{exit:n}=te(),[r,s]=W(1),o=process.cwd().replace(process.env.HOME||"","~");return Z((o,i)=>{i.upArrow||i.downArrow?s(1===r?2:1):i.return?1===r?e():(t(),n()):"1"===o?e():("2"===o||i.escape||i.ctrl&&"c"===o)&&(t(),n())}),B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.YELLOW,padding:1},B.createElement(Y,{color:Ln.YELLOW,bold:!0},"Do you trust the files in this folder?"),B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY},o)),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),B.createElement(K,{marginTop:1},B.createElement(Y,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{color:1===r?Ln.CYAN:Ln.GRAY},1===r?be.pointer:" "," 1. Yes, proceed")),B.createElement(K,null,B.createElement(Y,{color:2===r?Ln.CYAN:Ln.GRAY},2===r?be.pointer:" "," 2. No, exit"))))},"TrustPrompt"),sT=U(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return B.createElement(B.Fragment,null,B.createElement(nT,{staticKey:e}),B.createElement(rT,{onTrust:t,onExit:n}))},"TrustView"));Nt(),Nt(),CE(),jr(),rr();var oT=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=te(),[r,s]=W([]),[o,i]=W(0),[a,l]=W(!0),[u,d]=W(0),m=30;G(()=>{p()},[]);const p=__name(async()=>{l(!0);const e=await Yb.listSessions();s(e),l(!1)},"loadSessions");if(Z((t,s)=>{s.upArrow?i(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):s.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=u+m&&d(t-m+1),t}):s.return?r.length>0&&e(r[o].id):(s.escape||s.ctrl&&"c"===t)&&n()}),a)return B.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(Y,{color:Ln.GRAY},"Loading sessions..."));const g=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(n/36e5),o=Math.floor(n/864e5),i=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:s<24?`${s} hour${s>1?"s":""} ago`:o<7?`${o} day${o>1?"s":""} ago`:1===i?"1 week ago":`${i} weeks ago`},"formatRelativeTime"),h=__name(e=>truncateString({text:e,maxChars:Nr}),"truncateMessage");if(0===r.length)return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.GRAY},"No sessions available"));const f=r.slice(u,u+m),y=u;return B.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.DIM},"Showing ",u+1,"-",Math.min(u+m,r.length)," ","of ",r.length," sessions",u>0&&" (↑ for more)",u+m<r.length&&" (↓ for more)")),B.createElement(K,{columnGap:2,marginBottom:1},B.createElement(K,{width:7},B.createElement(Y,{color:Ln.GRAY}," ")),B.createElement(K,{width:13},B.createElement(Y,{color:Ln.GRAY},"Modified")),B.createElement(K,{width:11},B.createElement(Y,{color:Ln.GRAY},"# Messages")),B.createElement(K,{width:20},B.createElement(Y,{color:Ln.GRAY},"Git Branch")),B.createElement(K,null,B.createElement(Y,{color:Ln.GRAY},"Summary"))),B.createElement(K,{columnGap:2},B.createElement(K,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`sel-${n}`,color:o===n?Ln.CYAN:Ln.GRAY},o===n?`${be.pointer} ${n+1}.`:` ${n+1}.`)})),B.createElement(K,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`mod-${e.id}`,color:o===n?Ln.WHITE:Ln.GRAY},g(e.lastModified))})),B.createElement(K,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`msg-${e.id}`,color:o===n?Ln.WHITE:Ln.GRAY},e.messageCount)})),B.createElement(K,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`branch-${e.id}`,color:o===n?Ln.WHITE:Ln.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),B.createElement(K,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return B.createElement(Y,{key:`summary-${e.id}`,color:o===n?Ln.WHITE:Ln.GRAY},h(e.firstMessage))}))))},"SessionTable"),iT=U(__name(function SessionView2({onSelectSession:e,onNewSession:t}){return B.createElement(oT,{onSelectSession:e,onNewSession:t})},"SessionView"));Nt(),Nt(),vn(),rr();var aT=__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"),lT=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r,hideReview:s=!1})=>{if(s&&1===e.length)return null;const o=[];if(e.forEach((s,i)=>{const a=i===t&&!r,l=n.has(i);let u,d;a?(u=be.bullet,d=Ln.CYAN):l?(u=be.tick,d=Ln.GREEN):(u=be.circle,d=Ln.GRAY),o.push(B.createElement(Y,{key:i},B.createElement(Y,{color:d},u),B.createElement(Y,{color:a?Ln.CYAN:void 0}," ",s.header),i<e.length-1?B.createElement(Y,{dimColor:!0}," | "):null))}),!s){const e=r;o.push(B.createElement(Y,{key:"review"},B.createElement(Y,{dimColor:!0}," | "),B.createElement(Y,{color:e?Ln.CYAN:Ln.GRAY},e?be.bullet:be.circle),B.createElement(Y,{color:e?Ln.CYAN:void 0,bold:e}," ","Review")))}return B.createElement(K,null,o)},"TabIndicator"),cT=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,s]=W(0),[o,i]=W(new Map),a=Q(new Map),[l,u]=W(""),[d,m]=W(new Set),[p,g]=W(null),[h,f]=W(!1),[y,w]=W(!1),[S,b]=W(!1),[E,C]=W(null),[v,T]=W(!1),k=e[r],_=k?.multiSelect??!1,P=o.get(r),A=k?[...k.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],x=A.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),I=new Map(x.map((e,t)=>[e.label,A[t]])),N=__name(e=>{"submit"===e.value?D():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),R=__name(()=>{if(!P||0===P.length)return 0;const e=P[0],t=k.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),$=__name(e=>{if(!h)if(_){const t=aT(e.value,k.options.length-1);if(null===t)return;const n=k.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=aT(e.value,k.options.length-1);if(null===t)return;f(!0);const n=k.options[t]?.label||"";O([n])}},"handleSelect"),L=__name(()=>{if(h)return;f(!0);const e=Array.from(d);O(e)},"handleMultiSelectDone"),M=__name(()=>{if(!h&&l.trim())if(_){const e=new Set(k.options.map(e=>e.label));m(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(l.trim()),n})}else f(!0),O([l.trim()])},"handleOtherSubmit"),O=__name(t=>{a.current.set(r,t);const o=new Map(a.current);i(o);const l=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);u(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;l(e),s(e),f(!1),b(!1),C(null),T(!1)}else if(e.every((e,t)=>o.has(t))){if(n&&1===e.length)return void D();m(new Set),u(""),w(!0),f(!1)}else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(l(t),s(t)),f(!1),b(!1),C(null),T(!1)}},"finishQuestion"),D=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),q=__name(t=>{w(!1),s(t),T(!1),b(!1),C(null);const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}},"editQuestion"),F=__name(t=>{if(t<0||t>=e.length)return;_&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),f(!1),b(!1),C(null),T(!1);const n=e[t],o=a.current.get(t);if(n?.multiSelect&&o){m(new Set(o));const e=o.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==o?.length)u("");else{const e=o[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}s(t)},"navigateToQuestion"),j=__name(()=>{if(!p||!_)return;if("done"===p.value)return;const e=aT(p.value,k.options.length-1);if(null===e)return;const t=k.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return Z((t,s)=>{if(" "===t&&_&&!S&&j(),"d"!==t||!_||S||y||L(),!y&&!h){if(s.downArrow&&!S&&!v&&!n&&p&&x.length>0&&p.value===x[x.length-1]?.value&&b(!0),s.upArrow&&!S&&!v&&p&&x.length>0&&p.value===x[0]?.value&&(_?T(!0):n||(b(!0),C(x.length-1))),s.upArrow&&S){b(!1),C(x.length-1);const e=x[x.length-1];e&&g(e)}if(s.downArrow&&S)if(b(!1),_)T(!0);else{C(0);const e=x[0];e&&g(e)}if(s.upArrow&&v&&(T(!1),b(!0)),s.downArrow&&v){T(!1),C(0);const e=x[0];e&&g(e)}s.return&&v&&_&&L()}if(h||S||v||(y?s.leftArrow&&q(e.length-1):s.leftArrow&&r>0?F(r-1):s.rightArrow&&(r<e.length-1?F(r+1):(_&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),w(!0)))),s.escape&&!h)if(y)w(!1);else if(S){b(!1);const e=E??x.length-1;C(e);const t=x[e];t&&g(t)}else if(v){T(!1);const e=x[x.length-1];e&&g(e)}}),k||y?y?B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(lT,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>B.createElement(K,{key:t,marginBottom:1,flexDirection:"column"},B.createElement(Y,{dimColor:!0},t+1,". ",e.question),B.createElement(Y,{color:Ln.GREEN}," ",o.get(t)?.join(", ")||"No answer"))),B.createElement(Ke,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:N,initialIndex:0,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.CYAN},e?be.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(Y,{color:t?Ln.CYAN:Ln.WHITE},e)}),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},be.arrowLeft," to go back and edit"))):B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(lT,{questions:e,currentIndex:r,answeredQuestions:new Set(o.keys()),isReviewPage:!1,hideReview:n})),B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0},k.question)),S||v?B.createElement(K,{flexDirection:"column"},x.map((e,t)=>{const n=I.get(e.label),r=_&&n&&d.has(n.label),s=!_&&n&&P?.includes(n.label),o=r||s;return B.createElement(K,{key:t,flexDirection:"column"},B.createElement(K,null,B.createElement(Y,null," "),B.createElement(Y,{color:o?Ln.GREEN:Ln.WHITE}," ",t+1,"."," "),_&&(o?B.createElement(Y,{color:Ln.GREEN},"[",be.tick,"]"," "):B.createElement(Y,{dimColor:!0},"[ ] ")),B.createElement(Y,{color:o?Ln.GREEN:Ln.WHITE},n?.label||""),!_&&o&&B.createElement(Y,{color:Ln.GREEN}," ",be.tick)),n?.description&&B.createElement(K,null,B.createElement(Y,null," "),B.createElement(Y,{dimColor:!0},_?" ":" ",n.description)))})):B.createElement(Ke,{key:`${r}-${E??"default"}`,items:x,initialIndex:E??R(),onSelect:$,onHighlight:g,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.CYAN},e?be.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=I.get(e),r=_&&n&&d.has(n.label),s=!_&&n&&P?.includes(n.label),o=r||s,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return B.createElement(K,{flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{color:t?Ln.CYAN:o?Ln.GREEN:Ln.WHITE}," ",a,"."," "),_&&(o?B.createElement(Y,{color:Ln.GREEN},"[",be.tick,"]"," "):B.createElement(Y,{dimColor:!0},"[ ] ")),B.createElement(Y,{color:t?Ln.CYAN:o?Ln.GREEN:Ln.WHITE},l),!_&&o&&B.createElement(Y,{color:Ln.GREEN}," ",be.tick)),n?.description&&B.createElement(Y,{dimColor:!0},_?" ":" ",n.description))}}),!n&&B.createElement(K,null,B.createElement(Y,{color:Ln.CYAN},S?be.pointer:" "),B.createElement(Y,{color:S?Ln.CYAN:void 0}," ",x.length+1,"."," "),_&&(d.has(l.trim())?B.createElement(Y,{color:Ln.GREEN},"[",be.tick,"] "):B.createElement(Y,{dimColor:!0},"[ ] ")),B.createElement(TextInput,{value:l,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=l.trim();u(t),_&&m(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:M,placeholder:"Type something...",focus:S,stripBracketedPaste:!0})),_&&B.createElement(K,null,B.createElement(Y,{color:Ln.CYAN},v?be.pointer:" "),B.createElement(Y,{color:v?Ln.CYAN:void 0,bold:v}," ",r===e.length-1?"Submit":"Next")),e.length>1&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function QuestionView({pendingQuestion:e,setPermissionMode:t,setPendingQuestion:n,setStatus:r,setStaticKey:s}){return B.createElement(K,{marginY:1},B.createElement(cT,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,onResponse:o=>{if(e.params.exitPlanMode){const e=o.answers[0]?.selectedOptions[0]||"";e.startsWith("Yes, auto-accept")?(t("auto-accept"),kC(),s(e=>e+1)):e.startsWith("Yes, exit")&&(t("standard"),kC(),s(e=>e+1))}if(e.params.enterPlanMode){const e=o.answers[0]?.selectedOptions[0];e?.startsWith("Yes")&&(t("plan"),kC(),s(e=>e+1))}e.resolve(o),n(null),r("Answers submitted")}}))}PC(),__name(QuestionView,"QuestionView"),Nt(),Nt(),Ot(),rr(),Nt(),Jo(),en(),ar(),rr(),Nt(),rr();var uT=class extends Xe{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)}hr(){return"\n"+Be.dim("───")+"\n"}blockquote(e){return"object"==typeof e&&(e=this.parser.parse(e.tokens)),this.o.blockquote(e.trim()).split("\n").map(e=>`│ ${e}`).join("\n")+"\n\n"}listDepth=0;list(e,t=!1,n=""){let r;this.listDepth++;try{r=super.list(e,t,n),r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),1===this.listDepth&&(r=r.replace(/^ /gm,""))}finally{this.listDepth--}return r}},dT=new Je;dT.setOptions({renderer:new uT({strong:Be.bold,em:Be.italic,del:Be.dim.strikethrough,codespan:Be.hex(Yn.CODE),code:Be.hex(Yn.CODE),heading:Be.bold,firstHeading:Be.bold.hex(Yn.HEADING).underline,link:Be.hex(Ln.CYAN),href:Be.hex(Ln.CYAN).underline,blockquote:Be.hex(Ln.GRAY).italic,table:Be.reset,tableOptions:{style:{head:[Ln.CYAN],border:[Ln.GRAY]}},hr:Be.reset,paragraph:Be.reset,html:Be.hex(Ln.GRAY),showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var mT=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const s=H(()=>{if(!e)return"";const t=[],n=e.replace(mT,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=dT.parse(n);if("string"!=typeof r)return e;return r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").replace(/^(\s*)\* /gm,"$1- ").replace(/\n{3,}/g,"\n\n").trim()}catch{return e}},[e]);return B.createElement(Y,{color:t,dimColor:n,wrap:r},s)}__name(Markdown,"Markdown"),jr();var pT=" │ ";function computeSimilarity({strA:e,strB:t}){const n=e.trim(),r=t.trim();if(n===r)return 1;if(!n||!r)return 0;const s=Object.create(null);for(let e=0;e<n.length;e++){const t=n[e];s[t]=(s[t]??0)+1}let o=0;for(let e=0;e<r.length;e++){const t=r[e],n=s[t];n&&(o++,s[t]=n-1)}return 2*o/(n.length+r.length)}function buildSimilarityMatrix(e,t,n){const r=new Float64Array(e.length*n);for(let s=0;s<e.length;s++)for(let o=0;o<n;o++)r[s*n+o]=computeSimilarity({strA:e[s],strB:t[o]});return r}function collectSimilarityCandidates(e,t,n){const r=[];for(let s=0;s<t;s++)for(let t=0;t<n;t++){const o=e[s*n+t];o>=.3&&r.push({score:o,removedIdx:s,addedIdx:t})}return r}function buildLinePairs(e,t){const n=e.length,r=t.length,s=new Map;if(n*r>200){const e=Math.min(n,r);for(let t=0;t<e;t++)s.set(t,t);return s}const o=collectSimilarityCandidates(buildSimilarityMatrix(e,t,r),n,r);o.sort((e,t)=>t.score-e.score);const i=new Set,a=new Set;for(const{removedIdx:e,addedIdx:t}of o)i.has(e)||a.has(t)||(s.set(e,t),i.add(e),a.add(t));return s}function groupAdjacentChanges(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(!r.added&&!r.removed){const e=r.value.split("\n");""===e.at(-1)&&e.pop(),t.push({type:"context",contextLines:e,removedLines:[],addedLines:[]}),n++;continue}const s=[],o=[];for(;n<e.length&&(e[n].added||e[n].removed);){const t=e[n].value.split("\n");""===t.at(-1)&&t.pop(),e[n].removed?(s.push(...t),n++):(o.push(...t),n++)}t.push({type:"change",contextLines:[],removedLines:s,addedLines:o})}return t}function renderWordSegments({wordChanges:e,type:t,dimDiff:n}){const r="removed"===t?Fn.REMOVED_HIGHLIGHT_BG:Fn.ADDED_HIGHLIGHT_BG,s=[];let o=0;for(const i of e){if("removed"===t&&i.added)continue;if("added"===t&&i.removed)continue;const e="removed"===t?i.removed:i.added,a=i.value.replace(/\s/g," "),l=`${t}-${o++}-${e?"highlighted":"unchanged"}`;e?s.push(B.createElement(Y,{key:l,backgroundColor:r,dimColor:n},a)):s.push(B.createElement(Y,{key:l,color:Ln.WHITE,dimColor:n},a))}return s}function renderContextLine({line:e,lineNum:t,lineNumWidth:n,dimDiff:r,nodeKey:s}){return B.createElement(K,{key:s,width:"100%"},B.createElement(Y,{color:Fn.LINE_NUM,dimColor:r}," "+t.toString().padStart(n)),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:r},pT),B.createElement(Y,{color:Ln.WHITE,dimColor:r}," ",e.replace(/\s/g," ")))}function renderContextGroup({lines:e,leadCount:t,trailCount:n,lineNumWidth:r,dimDiff:s,counters:o}){const i=[];if(t+n>=e.length){for(const t of e)i.push(renderContextLine({line:t,lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;return i}for(let n=0;n<t;n++)i.push(renderContextLine({line:e[n],lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;const a=e.length-t-n;a>0&&(o.oldLineNum+=a,o.newLineNum+=a,i.push(B.createElement(K,{key:"sep-"+o.nodeKey++},B.createElement(Y,{color:Fn.LINE_NUM,dimColor:s}," ".repeat(r+1)),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:s},pT),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:s},`⋮ ${a} line${1===a?"":"s"}`))));for(let t=e.length-n;t<e.length;t++)i.push(renderContextLine({line:e[t],lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;return i}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:s=!1,marginLeft:o=2,startLine:i=1,dimDiff:a=!1,maxLines:l}){const u=Ye.diffLines(e,t);let d=0,m=0;for(const e of u)e.added&&(d+=e.count||1),e.removed&&(m+=e.count||1);const p=u.reduce((e,t)=>e+(t.added?0:t.count||1),0),g=u.reduce((e,t)=>e+(t.removed?0:t.count||1),0),h=Math.max(3,(i+p-1).toString().length,(i+g-1).toString().length),f=groupAdjacentChanges(u),y=[],w={oldLineNum:i,newLineNum:i,nodeKey:0};for(let e=0;e<f.length;e++){const t=f[e];if("context"===t.type){const n=t.contextLines,r=e>0&&"change"===f[e-1].type,s=e<f.length-1&&"change"===f[e+1].type;if(!r&&!s){w.oldLineNum+=n.length,w.newLineNum+=n.length;continue}const o=r?Math.min(3,n.length):0,i=s?Math.min(3,Math.max(0,n.length-o)):0;y.push(...renderContextGroup({lines:n,leadCount:o,trailCount:i,lineNumWidth:h,dimDiff:a,counters:w}));continue}const{removedLines:n,addedLines:r}=t,s=buildLinePairs(n,r),o=new Map,i=new Map;for(const[e,t]of s){const s=Ye.diffWordsWithSpace(n[e],r[t]);o.set(e,s),i.set(t,s)}for(let e=0;e<n.length;e++){const t=o.get(e);y.push(B.createElement(K,{key:"rm-"+w.nodeKey++,width:"100%",backgroundColor:Fn.REMOVED_BG},B.createElement(Y,{color:Fn.REMOVED_TEXT,dimColor:a}," "+w.oldLineNum.toString().padStart(h)),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:a},pT),B.createElement(Y,{color:Fn.REMOVED_TEXT,dimColor:a},"- "),t?renderWordSegments({wordChanges:t,type:"removed",dimDiff:a}):B.createElement(Y,{color:Fn.REMOVED_TEXT,dimColor:a},n[e].replace(/\s/g," ")))),w.oldLineNum++}for(let e=0;e<r.length;e++){const t=i.get(e);y.push(B.createElement(K,{key:"add-"+w.nodeKey++,width:"100%",backgroundColor:Fn.ADDED_BG},B.createElement(Y,{color:Fn.ADDED_TEXT,dimColor:a}," "+w.newLineNum.toString().padStart(h)),B.createElement(Y,{color:Fn.LINE_NUM,dimColor:a},pT),B.createElement(Y,{color:Fn.ADDED_TEXT,dimColor:a},"+ "),t?renderWordSegments({wordChanges:t,type:"added",dimDiff:a}):B.createElement(Y,{color:Fn.ADDED_TEXT,dimColor:a},r[e].replace(/\s/g," ")))),w.newLineNum++}}const S=void 0!==l&&y.length>l,b=S?y.slice(0,l):y;return{diffContent:B.createElement(K,{flexDirection:"column"},s&&!r&&B.createElement(Y,{color:Ln.GRAY},"Updated"," ",B.createElement(Y,{color:Ln.WHITE,bold:!0},n)," ","with ",B.createElement(Y,{color:Bn.SUCCESS},d)," ","addition",1!==d?"s":""," and"," ",B.createElement(Y,{color:Bn.ERROR},m)," removal",1!==m?"s":""),r&&B.createElement(Y,{color:Ln.RED},"Rejected update to",B.createElement(Y,{color:Ln.RED},` ${n}`)),B.createElement(K,{flexDirection:"column",marginLeft:o,marginRight:o+4,width:(process.stdout.columns||80)-2*o-8},b)),isTruncated:S,totalLines:y.length}}function formatTodosForDisplay(e){const t=Vo(e);return t?B.createElement(K,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?be.checkboxOn:be.checkboxOff;let r,s=!1;switch(e.status){case"completed":r=Bn.SUCCESS,s=!0;break;case"in_progress":r=Bn.IN_PROGRESS;break;default:r=Ln.WHITE}return B.createElement(K,{key:e.id||t,flexDirection:"row"},B.createElement(K,{width:2},B.createElement(Y,{color:r},n)),B.createElement(Y,{color:r,bold:"in_progress"===e.status,strikethrough:s},e.content))})):B.createElement(Y,null,e)}function computeDisplayInput({input:e,isAgent:t,isShell:n,expandedOutput:r}){if(!e)return e;if(t){const t=e.split(/[.\n]/)[0];return t?t+(e.includes(".")||e.includes("\n")?".":""):e}return n&&!r?truncateCommand({command:e}):e}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:s}){if(e)return{symbolColor:Ln.YELLOW,symbol:be.arrowRight};if(t)return{symbolColor:Ln.RED,symbol:be.nodejs};if(n)return{symbolColor:Dn,symbol:"✻"};if(r&&s){const e=Vo(s),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?Bn.SUCCESS:Bn.WARNING,symbol:be.nodejs}}return{symbolColor:Bn.SUCCESS,symbol:be.nodejs}}function renderToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,output:s,expandedOutput:o,expandKey:i}){if(e){const e=s?Math.max(1,Math.round(s.length/500)):1;return B.createElement(B.Fragment,null,B.createElement(Y,{color:Dn},`Thought for ${e} second${1!==e?"s":""}`," "),!o&&B.createElement(Y,{dimColor:!0},"(",`${i}+o to expand`,")"))}return t?B.createElement(B.Fragment,null,B.createElement(K,{flexShrink:0},B.createElement(Y,{backgroundColor:On.BADGE_BG,color:On.BADGE_FG,bold:!0},`${cv}Taste${cv}`)),B.createElement(Y,null," ","Using your taste"," ",n?"package of ":"packages",n&&B.createElement(Y,{bold:!0},n))):B.createElement(K,{flexShrink:0},B.createElement(Y,{backgroundColor:jn.BG,color:jn.FG,bold:!0},`${cv}${r}${cv}`))}function renderAgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:s}){const o=`${formatTime2(r)} | ${formatTokens(s)}`;return"running"===e?B.createElement(Y,{color:Ln.GRAY},"Running (",o,")"):"interrupted"===e||"Interrupted by user"===n?B.createElement(Y,{color:Ln.RED,wrap:"wrap"},"Interrupted by user"):"error"===e||t?B.createElement(Y,{color:Ln.RED,wrap:"wrap"},n," (",o,")"):B.createElement(B.Fragment,null,B.createElement(Y,{wrap:"wrap"},"Done"),B.createElement(Y,{color:Ln.GRAY}," (",o,")"))}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,hasError:r,expandKey:s}){if(n||r)return e;const o=dedentText(e),{text:i,isTruncated:a,remainingLines:l}=truncateToVisualLines({output:o,maxVisualLines:"Question"===t?_r:kr,maxChars:"Question"===t?1/0:Ir});if(!a||"Question"===t)return i;const u=l>0?`... +${l} lines (${s}+o to expand)`:`... (${s}+o to expand)`;return B.createElement(B.Fragment,null,i,B.createElement(Y,{dimColor:!0},"\n",u))}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:s,expandKey:o}){const i=n?void 0:Pr,{diffContent:a,isTruncated:l,totalLines:u}=generateDiff({filePath:e,showMetadata:!0,oldValue:t.oldValue,newValue:t.newValue,startLine:"number"==typeof t.startLine?t.startLine:1,dimDiff:r,permissionDenied:r,maxLines:i});return B.createElement(K,{flexDirection:"column"},a,l&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"… (",u-Pr," more lines) (",`${o}+o to expand`,")")),r&&s&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.RED,wrap:"wrap"},s)))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,metadata:r,output:s,expandedOutput:o,isPermissionDenied:i,input:a,hasError:l,name:u,expandKey:d}){return e?formatTodosForDisplay(s):t?o?B.createElement(K,{width:"100%",flexDirection:"column"},B.createElement(Y,null," "),B.createElement(Y,{color:Dn,wrap:"wrap",italic:!0},s)):null:n&&r?.oldValue&&r?.newValue?renderEditFileDiff({input:a,metadata:r,expandedOutput:o,isPermissionDenied:i,output:s,expandKey:d}):B.createElement(K,{width:"100%"},B.createElement(Y,{color:l?Ln.RED:"",wrap:"wrap"},renderTruncatedOutput({output:s,name:u,expandedOutput:o,hasError:l,expandKey:d})))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:s=!1,metadata:o,expandedOutput:i=!1}){const a="thinking…"===e,l="TODOS"===e,u="Edit"===e,d=!0===o?.isTasteFile,m=o?.tasteCategory,p=!0===o?.permissionDenied,g=!a&&!l&&!d,{name:h}=detectTerminal(),f="iTerm2"===h?"shift":"ctrl",y=!0===o?.isAgent,w=computeDisplayInput({input:t,isAgent:y,isShell:"Shell"===e,expandedOutput:i}),S=!a&&w&&!d,b=o?.status,E=o?.tokensUsed||0,C="number"==typeof o?.elapsedSeconds?Math.floor(o.elapsedSeconds):0,{symbolColor:v,symbol:T}=resolveSymbol({isPending:r,hasError:s,isThinking:a,isTodos:l,output:n});return B.createElement(K,null,a&&B.createElement(Y,{color:v},T),B.createElement(K,{flexDirection:"column",marginLeft:a?1:0},B.createElement(K,null,renderToolHeader({isThinking:a,isTasteFile:d,tasteCategory:m,name:e,output:n,expandedOutput:i,expandKey:f}),S&&B.createElement(Y,null," ",B.createElement(Markdown,null,`(${w})`))),y&&("running"===b||n)&&B.createElement(K,{columnGap:1,marginLeft:g?1:0},g&&B.createElement(Y,null,"⎿"," "),renderAgentStatus({agentStatus:b,hasError:s,output:n,elapsedSeconds:C,tokensUsed:E})),n&&!d&&!y&&B.createElement(K,{columnGap:1,marginLeft:g?1:0},g&&B.createElement(Y,null,"⎿"," "),renderOutputContent({isTodos:l,isThinking:a,isEditFile:u,metadata:o,output:n,expandedOutput:i,isPermissionDenied:p,input:t,hasError:s,name:e,expandKey:f})),r&&!y&&B.createElement(K,{columnGap:1,marginLeft:1},B.createElement(Y,null,"⎿"," "),B.createElement(Y,{color:Ln.GRAY},"Processing…"))))}__name(computeSimilarity,"computeSimilarity"),__name(buildSimilarityMatrix,"buildSimilarityMatrix"),__name(collectSimilarityCandidates,"collectSimilarityCandidates"),__name(buildLinePairs,"buildLinePairs"),__name(groupAdjacentChanges,"groupAdjacentChanges"),__name(renderWordSegments,"renderWordSegments"),__name(renderContextLine,"renderContextLine"),__name(renderContextGroup,"renderContextGroup"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(computeDisplayInput,"computeDisplayInput"),__name(resolveSymbol,"resolveSymbol"),__name(renderToolHeader,"renderToolHeader"),__name(renderAgentStatus,"renderAgentStatus"),__name(renderTruncatedOutput,"renderTruncatedOutput"),__name(renderEditFileDiff,"renderEditFileDiff"),__name(renderOutputContent,"renderOutputContent"),__name(ToolMessage,"ToolMessage"),Zo();var gT=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[s]=W(0),[o,i]=W(1);G(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&i(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=[{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}],l=__name(e=>{const t=a.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),u=__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"),d=__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"),m=__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 B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.GRAY,paddingX:1,width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,color:Ln.YELLOW},`${m()} ${"edit"===e.action?d():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&B.createElement(K,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:d(),marginLeft:0,startLine:o}).diffContent),B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0},"Do you want to ",u()," ",B.createElement(Y,{color:Ln.CYAN},d()),"?")),B.createElement(Ke,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:s,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.CYAN},e?be.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(Y,{color:t?Ln.CYAN:Ln.WHITE},e.includes("(shift+tab)")?B.createElement(B.Fragment,null,e.split("(shift+tab)")[0],B.createElement(Y,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?B.createElement(B.Fragment,null,e.split("(")[0],B.createElement(Y,{color:Ln.GRAY},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Nt(),Ot(),rr();var hT=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=W(0),s=[{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}],o=__name(e=>{const r=s.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),i=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"";return t?`${e.command} ${t}`:e.command},"getCommandDisplay");return B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.GRAY,paddingX:1,width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,color:Ln.YELLOW},"Execute Shell Command")),B.createElement(K,{marginBottom:1},B.createElement(Y,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",B.createElement(Y,{color:Ln.CYAN},i()),".")),e.workingDirectory&&B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.GRAY},"Working directory: ",e.workingDirectory)),e.description&&B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0,italic:!0},e.description)),B.createElement(Ke,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:r,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.CYAN},e?be.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(Y,{color:t?Ln.CYAN:Ln.WHITE},e.includes("(shift+tab)")?B.createElement(B.Fragment,null,e.split("(shift+tab)")[0],B.createElement(Y,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt");function getKillShellRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}function getFileAction2(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:s,permissionMode:o,showHintMessage:i,allowedStatus:a,deniedStatus:l}){r(e);const u="no"!==e.value;t(u),n(null),u?(s(a),"standard"===o&&i("Use shift+tab to enable auto-accept")):s(l)}__name(getKillShellRequest,"getKillShellRequest"),__name(getFileAction2,"getFileAction"),__name(handlePermissionResponse,"handlePermissionResponse");var fT=U(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:s,showHintMessage:o,handleToggleAutoAccept:i}){const a={resolve:e.resolve,setPendingPermission:n,respondToPrompt:s,setStatus:r,permissionMode:t,showHintMessage:o};if("shell_command"===e.toolName){const t=e.params;return B.createElement(K,{marginY:1},B.createElement(hT,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"}),onToggleAutoAccept:i}))}if("kill_shell"===e.toolName){const t=getKillShellRequest(e.params);return B.createElement(K,{marginY:1},B.createElement(hT,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"}),onToggleAutoAccept:i}))}const l=e.params,u={action:getFileAction2(e.toolName),filePath:String(l.filePath??l.file_path??l.path??l.absolutePath??l.notebook_path??"unknown"),description:`Allow ${e.toolName} operation`,oldContent:"edit_file"===e.toolName&&"string"==typeof l.oldContent?l.oldContent:void 0,newContent:"edit_file"===e.toolName&&"string"==typeof l.newContent?l.newContent:void 0};return B.createElement(K,{marginY:1},B.createElement(gT,{request:u,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onToggleAutoAccept:i}))},"PermissionView"));Nt(),PC(),Nt(),tC(),Nt(),rr();var yT=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:s=0,titleColor:o=Ln.GRAY,dividerChar:i="─",dividerColor:a=Ln.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*s),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",p=r?` ${r}`:"",g=d.length+m.length+p.length,h=i.repeat(Math.max(0,u-g));return B.createElement(K,{paddingLeft:s,paddingRight:s,marginBottom:1,...l},(t||n)&&B.createElement(Y,{color:a},d),e&&B.createElement(Y,{color:o},m),B.createElement(Y,{color:a},h),r&&B.createElement(Y,{dimColor:!0},p))},"Divider");PC(),rr(),Nt(),rr();var wT=[{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}],ST=__name(({onComplete:e,onExit:t})=>{const[n,r]=W(0),[s,o]=W(!1),i=n>=wT.length;return G(()=>{if(n>=wT.length)return;if(s)return;const e=wT[n],t=setTimeout(()=>{r(e=>Math.min(e+1,wT.length))},e.duration);return()=>clearTimeout(t)},[n,s]),Z((n,s)=>{""===n||s.ctrl&&"c"===n?t?t():e():s.escape?e():i?(s.return||" "===n)&&e():" "===n?o(e=>!e):s.return&&r(e=>Math.min(e+1,wT.length))}),B.createElement(K,{flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{bold:!0},"Meet Your Coding Taste")),B.createElement(K,null,B.createElement(Y,{dimColor:!0},"Command Code learns your coding style as you work.")),B.createElement(K,null,B.createElement(Y,{dimColor:!0},"Here's how your preferences evolve in real-time:")),B.createElement(K,{flexDirection:"column",marginY:1},wT.slice(0,n).map((e,t)=>"user"===e.type?B.createElement(K,{key:t},B.createElement(Y,null,be.pointer," ",e.text)):B.createElement(K,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},B.createElement(K,null,B.createElement(Y,{dimColor:!0},"⎿ "),B.createElement(Y,{color:On.TEXT},e.text)),e.details&&B.createElement(K,{marginLeft:3},B.createElement(Y,{dimColor:!0},"Saved(",e.details,")"))))),i?B.createElement(K,{flexDirection:"column",marginY:1},B.createElement(K,null,B.createElement(Y,{bold:!0,color:On.TEXT},"Demo Complete!")),B.createElement(K,null,B.createElement(Y,null,"Command Code will now use these preferences to generate")),B.createElement(K,null,B.createElement(Y,null,"better suggestions tailored to your coding style. The")),B.createElement(K,null,B.createElement(Y,null,"more you code, the smarter it gets.")),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press Enter to get started →"))):B.createElement(K,null,B.createElement(Y,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(s?" (paused)":""))))},"TasteDemoComponent"),bT=__name(({onClose:e,onExit:t})=>{const[n,r]=W(ZE.getEvents()),[s,o]=W(0);Z((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),G(()=>{const e=__name(()=>{r(ZE.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return ZE.on("new-event",e),ZE.on("cleared",t),()=>{ZE.off("new-event",e),ZE.off("cleared",t)}},[]),G(()=>{const e=__name(()=>{kC(),o(e=>e+1)},"handleResize");return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e)}},[]);const i=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),a=__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 s=n,o=null;if(r){s=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);o=`confidence: ${parseFloat(e).toString()}%`}const i={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:i,content:s,confidence:o}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),l=__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),s=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:s,diff:s-r}},"parsePercentageChange"),u=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),s=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:s,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails"),d=H(()=>(process.stdout.rows??24)-1,[s]);return B.createElement(K,{flexDirection:"column",width:"100%",height:d,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Ze,{name:"vice"},B.createElement(Y,null,BC()))),B.createElement(yT,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),B.createElement(K,{flexDirection:"column"},0===n.length?B.createElement(K,{flexDirection:"column"},B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(K,null,B.createElement(Y,null,"Start using Command Code and it will begin recording your coding taste.")),B.createElement(K,null,B.createElement(Y,{dimColor:!0},"Your preferences, patterns, and style will appear here in real-time."))),B.createElement(ne,{count:2}),B.createElement(yT,{title:"DEMO",titleColor:"white",subPrefix:!0}),B.createElement(ST,{onComplete:()=>{e()},onExit:t})):B.createElement(K,{flexDirection:"column"},n.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:s}=a(e.message),o="moved"===t?u(e.details):null,i="upgraded"===t||"downgraded"===t?l(r):null;return B.createElement(K,{key:e.id,marginBottom:1},B.createElement(K,{flexDirection:"column"},B.createElement(K,null,B.createElement(K,{flexShrink:0},B.createElement(Y,{backgroundColor:On.BADGE_BG,color:On.BADGE_FG,bold:!0},`${cv}${n}${cv}`)),o?B.createElement(Y,{dimColor:!0}," ","(",o.fullPath,")"):e.details?B.createElement(Y,{dimColor:!0}," ","(",e.details,")"):null),B.createElement(K,{marginLeft:1},B.createElement(Y,{dimColor:!0},"⎿"," "),o?B.createElement(B.Fragment,null,B.createElement(Y,null," ",o.category," ","package ("),B.createElement(Y,{dimColor:!0},o.oldPath),B.createElement(Y,null," ",be.arrowRight," ",o.newPath),B.createElement(Y,null,")")):i?B.createElement(B.Fragment,null,B.createElement(Y,null," ",i.text," ","("),B.createElement(Y,{dimColor:!0},"confidence:"," "),B.createElement(Y,{dimColor:!0},i.oldPercent,"%"),B.createElement(Y,null," ",be.arrowRight," "),B.createElement(Y,{color:i.diff>0?Ln.GREEN:Ln.RED},i.newPercent,"%"),B.createElement(Y,null,")")):B.createElement(B.Fragment,null,B.createElement(Y,null," ",r),s&&B.createElement(Y,{dimColor:!0}," ","(",s,")")))))}return B.createElement(K,{key:e.id,marginBottom:1},B.createElement(Y,{dimColor:!0},be.pointerSmall," ",e.message))}))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return B.createElement(bT,{onClose:()=>{kC(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Nt(),Nt(),rr(),PC(),nr();var ET=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,s]=W(!1),[o,i]=W(!0);G(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();s(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),Z((t,n)=>{if(!n.return&&" "!==t)return n.escape?(kC(),void e()):void 0;a()});const a=__name(async()=>{const e=!r;s(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){s(!e)}},"toggleTasteLearning");return o?B.createElement(K,{key:n,borderStyle:"single",borderColor:Ln.BLUE,padding:1,flexDirection:"column"},B.createElement(Y,{color:Ln.BLUE,bold:!0},"Taste Settings"),B.createElement(Y,{dimColor:!0},"Loading configuration...")):B.createElement(K,{key:n,borderStyle:"single",borderColor:Ln.GRAY,padding:1,flexDirection:"column"},B.createElement(Y,{bold:!0},"Taste Learning"),B.createElement(Y,{dimColor:!0},"Configure taste learning preferences for this project"),B.createElement(K,{marginTop:1}),B.createElement(K,{justifyContent:"space-between"},B.createElement(Y,null,"Taste learning",B.createElement(Y,{dimColor:!0}," - Learn from your interactions")),B.createElement(Y,{color:r?Ln.GREEN:Ln.GRAY},r?"enabled":"disabled")),B.createElement(K,{marginTop:1}),B.createElement(Y,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),B.createElement(Y,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return B.createElement(B.Fragment,null,B.createElement(nT,{staticKey:e}),B.createElement(K,{flexDirection:"column",width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"Press Esc to return to conversation")),B.createElement(ET,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}__name(TasteConfigView,"TasteConfigView"),Nt(),Nt(),gi(),PC(),Ot(),rr();var CT=__name(e=>Math.ceil(e.length/4),"estimateTokens"),vT=__name(({onClose:e})=>{const[t,n]=W([]),[r,s]=W(!0),[o,i]=W(null),[a,l]=W(0);G(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),r=[...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}))];n(r)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=t.filter(e=>"project"===e.location),d=t.filter(e=>"user"===e.location),m=[...u,...d],p=__name(async t=>{try{await et([{file:t.filePath,line:1}]),kC(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(g()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");Z((t,n)=>{if(n.escape)return kC(),void e();if(n.upArrow)l(e=>Math.max(0,e-1));else if(n.downArrow)l(e=>Math.min(m.length-1,e+1));else if(n.return){const e=m[a];e&&p(e)}});const g=__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 r?B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(Y,{color:Mn,bold:!0},"Agent Skills"),B.createElement(Y,{dimColor:!0},"Loading skills...")):o?B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(Y,{color:Ln.RED,bold:!0},"Agent Skills"),B.createElement(Y,{dimColor:!0},o),B.createElement(K,{marginTop:1}),B.createElement(Y,{dimColor:!0},"Press ",B.createElement(Y,{bold:!0},"Esc")," to close")):0===t.length?B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(Y,{color:Mn,bold:!0},"Agent Skills"),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"No skills found")),B.createElement(Y,{dimColor:!0},"Create skills in:"),B.createElement(Y,{dimColor:!0}," ~/",".commandcode","/","skills","/ (user)"),B.createElement(Y,{dimColor:!0}," ",".commandcode","/","skills","/ (project)"),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press ",B.createElement(Y,{bold:!0},"Esc")," to close"))):B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,null,B.createElement(Y,{color:Mn,bold:!0},"Skills "),B.createElement(Y,{dimColor:!0},m.length," skills")),u.length>0&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(K,null,B.createElement(Y,{color:Wn,bold:!0},"Project skills "),B.createElement(Y,{color:Wn},"(",".commandcode","/","skills",")")),u.map((e,t)=>{const n=a===t;return B.createElement(K,{key:e.value},B.createElement(Y,{color:n?Ln.GREEN:Ln.WHITE},e.label),B.createElement(Y,{dimColor:!0}," · ~",CT(e.description)," description tokens"))})),d.length>0&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(K,null,B.createElement(Y,{color:Wn,bold:!0},"User skills "),B.createElement(Y,{color:Wn},"(~/",".commandcode","/","skills",")")),d.map((e,t)=>{const n=a===u.length+t;return B.createElement(K,{key:e.value},B.createElement(Y,{color:n?Ln.GREEN:Ln.WHITE},e.label),B.createElement(Y,{dimColor:!0}," · ~",CT(e.description)," description tokens"))})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0,italic:!0},"Esc to close")))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t}){return B.createElement(B.Fragment,null,B.createElement(nT,{staticKey:e}),B.createElement(K,{flexDirection:"column",width:"100%"},B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"Press Esc to return to conversation")),B.createElement(vT,{onClose:()=>t(!1),staticKey:e})))}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:s}=e;return s<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),s=e.replace(/\\/g,"/");if(s.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${s.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:s};const o=s.lastIndexOf("/");return-1===o?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:s.slice(0,o+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),s=n.startsWith(".")||r.includes("/.");return S.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!s||!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?"[Del] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}__name(SkillsConfigView,"SkillsConfigView"),Nt(),Nt(),rr(),vn(),zt(),Nt(),zt(),__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 TT=__name(({onClose:e})=>{const[t,n]=W(""),[r,s]=W(null),[o,i]=W([]),[a,l]=W(getAdditionalDirectories()),[u,d]=W({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,p]=W(0);G(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),p(0)},[t]),G(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{s(null)},5e3);return()=>clearTimeout(e)},[r]);const g=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(s({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):s({tone:"warning",text:t.message}):s({tone:"error",text:t.message})},"submitPath"),h=__name(e=>{if(!removeAdditionalDirectory(e))return s({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());s({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),l(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");Z((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&o[u.suggestionIndex]?void g(o[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])h(a[u.activeDirIndex]);else{if(r.tab&&o.length>0){const e=o[u.suggestionIndex]??o[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),s(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:o.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:o.length,activeDirCount:a.length}))}}}),G(()=>{"suggestions"===u.zone&&p(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:o.length}))},[u,o.length]),G(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=o.length?{...e,zone:"input",suggestionIndex:Math.max(0,o.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[o.length,a.length]);const f=o.slice(m,m+8),y=getFooterText({focusZone:u.zone});return B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.CYAN,paddingX:1,paddingY:0},B.createElement(Y,{bold:!0,color:Ln.CYAN},"Add directory to workspace"),B.createElement(Y,{color:Ln.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,{color:Ln.GRAY},"Added directories"),0===a.length?B.createElement(Y,{color:Ln.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return B.createElement(Y,{key:e,color:n?Ln.YELLOW:Ln.GREEN,bold:n},n?` ${be.pointer} `:" ",formatDirectoryForDisplay(e))})),B.createElement(K,{marginTop:1},B.createElement(Y,{bold:!0,color:Ln.WHITE},"Path")),B.createElement(K,null,B.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?be.pointer:" "} `,prefixColor:"input"===u.zone?Ln.CYAN:Ln.GRAY,onChange:e=>{n(e),s(null)},onSubmit:g})),!t&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:{error:Ln.RED,warning:Ln.YELLOW,success:Ln.GREEN}[r.tone]},r.text)),o.length>0&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Suggestions"),f.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return B.createElement(Y,{key:e,color:r?Ln.CYAN:Ln.GRAY,bold:r},r?` ${be.pointer} `:" ",e)})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},y)))},"AddDirModal");Nt(),Nt(),Ot(),Nt(),Nt(),Ot(),JE(),rr();var kT=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),_T=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),PT=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[s,o]=W("idle"),[i,a]=W(""),l=[...WE.map(e=>e.name),...QE.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void a("Agent configuration is incomplete");o("saving");try{const r="personal"===e.location?kT():_T();await L.mkdir(r,{recursive:!0});const s=`${e.agentType}.md`,o=t.join(r,s),i=Array.from(e.selectedTools).map(e=>VE[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(i),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await L.writeFile(o,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");Z((e,t)=>{r||!t.return||"idle"!==s&&"error"!==s||u()});const d=Array.from(e.selectedTools).map(e=>VE[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return B.createElement(K,{flexDirection:"column",gap:1},B.createElement(K,{flexDirection:"column"},B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Name:"),B.createElement(Y,{color:Ln.GRAY},e.agentType)),B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Location:"),B.createElement(Y,{color:Ln.GRAY},m)),B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Tools:"),B.createElement(Y,{color:Ln.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Description"),B.createElement(Y,{color:Ln.GRAY},"(Tells ","Command Code"," when to use this agent):")),B.createElement(Y,{color:Ln.GRAY},e.ccToolDefinition),B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"System Prompt:")),B.createElement(Y,{color:Ln.GRAY},e.sysPrompt),!r&&B.createElement(K,{marginTop:1},"idle"===s&&B.createElement(K,{gap:1},B.createElement(Y,{color:Ln.GREEN,dimColor:!0},"Press"),B.createElement(Y,{color:Ln.GREEN,bold:!0},"Enter"),B.createElement(Y,{color:Ln.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===s&&B.createElement(Y,{color:Ln.YELLOW},"Saving agent..."),"saved"===s&&B.createElement(Y,{color:Ln.GREEN},be.tick," ",i),"error"===s&&B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.RED},be.cross," Error: ",i),B.createElement(Y,{color:Ln.GRAY},"Press Enter to retry"))))},"AgentSummary");JE(),rr();var AT=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[s,o]=W("menu"),i=[...WE.map(e=>e.name),...QE.map(e=>e.name)];let a=new Set;if("*"===e.tools||'"*"'===e.tools)a=new Set(i);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>KE[e]||e);a=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a},u=[{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?o("view"):"edit"===e.value?o("edit"):"delete"===e.value&&o("delete")},"handleMenuSelect");if(Z((e,n)=>{n.escape&&("menu"===s?t():o("menu")),n.return&&"view"===s&&o("menu")}),"view"===s)return B.createElement(K,{flexDirection:"column"},B.createElement(PT,{config:l,onSaveComplete:()=>o("menu"),viewOnly:!0}),B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Press Enter to go back")));if("edit"===s)return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.YELLOW},"Edit functionality coming soon..."),B.createElement(Y,{color:Ln.GRAY},"Press Esc to go back"));if("delete"===s){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],s=__name(async r=>{if("confirm-delete"===r.value)try{await L.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return B.createElement(K,{flexDirection:"column",gap:1},B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.RED},"Delete agent"),B.createElement(Y,{color:Ln.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),B.createElement(K,null,B.createElement(Ke,{items:r,onSelect:s,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},` ${t}`)})))}return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.WHITE,bold:!0},e.name),B.createElement(K,{marginTop:1},B.createElement(Ke,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},` ${t}`)})),B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");_l(),rr();var xT=__name(({handleSelect:e,createdAgentName:n})=>{const[r,s]=W([]),[o,i]=W([]),[a,l]=W([]),[u,d]=W(!0),[m,p]=W(!1),[g,h]=W(null),[y,w]=W(!1),S=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),b=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),E=__name(async(e,n)=>{try{p(!1);const r=(await L.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await L.readFile(s,"utf-8"),{data:i,content:a}=$e(o);let l=i.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:i.name||r.replace(".md",""),description:i.description||"",tools:l,sysPrompt:a.trim(),location:n,filePath:s}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");G(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([E(S(),"personal"),E(b(),"project")]),n=vl.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}`}));s(e),i(t),l(n),d(!1)},"loadAgents")()},[m]);const C=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{C.push({label:e.name,value:e.filePath})}),o.forEach(e=>{C.push({label:e.name,value:e.filePath})});const v=r.length+o.length,T=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...o].find(e=>e.filePath===t.value);e&&(h(e),w(!0))}},"handleAgentSelect");if(u)return B.createElement(Y,{color:Ln.GRAY},"Loading agents...");if(y&&g){const e=g.filePath.startsWith("__builtin__:");return B.createElement(AT,{agent:g,onBack:()=>{w(!1),h(null)},setRevalidateAgent:p,isReadOnly:e})}const k=__name(({isSelected:e,label:t})=>{const n=C.find(e=>e.label===t),s=n?.value||"",i=r[0]?.filePath===s,a=o[0]?.filePath===s;return B.createElement(K,{flexDirection:"column"},i&&r.length>0&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY,bold:!0},"User agents")),a&&o.length>0&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.GRAY,bold:!0},"Project agents")),B.createElement(K,null,B.createElement(Y,{color:Ln.WHITE},e?">":" "),B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY}," ",t)))},"CustomItemComponent");return B.createElement(K,{flexDirection:"column"},B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Agents"),v>0?B.createElement(Y,{color:Ln.GRAY}," ","(",v," agent",v>1?"s":"",")"):B.createElement(Y,{color:Ln.GRAY}," (No custom agents)")),n&&B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{color:Ln.GREEN,dimColor:!0},"Created agent: ",n)),B.createElement(Ke,{items:C,onSelect:T,indicatorComponent:()=>null,itemComponent:k}),a.length>0&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(Y,{color:Ln.GRAY,bold:!0},"Default agents"),a.map(e=>B.createElement(Y,{key:e.filePath,color:Ln.GRAY}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(Y,{color:Ln.GRAY},"Create specialized subagents that Command Code can delegate to."),B.createElement(Y,{color:Ln.GRAY},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Nt(),Ot(),rr(),JE(),Nt(),Nt(),Ot(),rr();var IT=__name(({onSelect:e})=>B.createElement(Ke,{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})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},` ${t}`)}),"LocationSelector");Nt(),vn(),Ot(),JE(),_n(),Nn(),Pl(),rr();var NT=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:s,onSysPromptChange:o,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=W(!1),[p,g]=W(!1),h=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?o(e):t.cleanedContent&&o(t.cleanedContent))}o(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?o(e):t.cleanedContent&&o(t.cleanedContent))}},[d,o]),f=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||p){if(!p||t.isPasteEnd){if(p&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[p,i]);return"agentType"===e?B.createElement(B.Fragment,null,B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(VE).some(e=>Ne(e)===Ne(t))||Object.keys(VE).some(e=>Ne(e)===Ne(t)))&&B.createElement(Y,{color:Ln.RED},be.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Ne(t))&&B.createElement(Y,{color:Ln.RED},be.warning," This name is reserved. Reserved names:"," ",Cl.join(", "))),B.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Ne(t);Object.values(VE).some(t=>Ne(t)===e)||Object.keys(VE).some(t=>Ne(t)===e)||isReservedAgentName(e)||a()},onChange:s,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?B.createElement(B.Fragment,null,B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.WHITE},"Enter the system prompt for your agent:"),B.createElement(Y,{color:Ln.GRAY},"Be comprehensive for best results.")),B.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:h,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?B.createElement(B.Fragment,null,B.createElement(Y,{color:Ln.WHITE},"When should ","Command Code"," use this agent?"),B.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:f,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Nt(),rr();var RT=__name(({onSelect:e})=>B.createElement(Ke,{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})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY},` ${t}`)}),"MethodSelector");Nt(),vn(),Nt(),rr();var $T=["·","○","◇","☆","✧","☆","◇","○","⌘"],LT=[12,5,4,4,4,4,4,5,16],MT=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<LT.length;e++)if(n+=LT[e],t<n)return $T[e];const r=t-58;n=0;for(let e=0;e<MT.length;e++)if(n+=MT[e],r<n)return $T[7-e];return $T[0]}function ShimmerText({text:e,offset:t}){const n=__name(e=>{const n=e-(t-5);return n>=0&&n<Jn.length?Jn[n]:Xn},"getCharColor");return B.createElement(Y,null,e.split("").map((e,t)=>B.createElement(Y,{key:t,color:n(t)},e)))}function CMDIcon({frame:e}){return B.createElement(Y,{color:Mn,bold:!0},getWaveSymbol(e)+" ")}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`}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon"),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");var OT=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,s]=W(0),[o,i]=W(0),a=Q(n);a.current=n;const l=getTerminalWidth();G(()=>{const e=setInterval(()=>{s(e=>(e+1)%88),i(e=>{const t=a.current;if(e===t)return e;const n=t-e,r=e+Math.sign(n)*Math.max(1,Math.ceil(Math.abs(n)/10));return n>0?Math.min(r,t):Math.max(r,t)})},80);return()=>clearInterval(e)},[]);const u=r%(e.length+10),d=l>70,m=l>40&&l<=70;return B.createElement(K,{width:l,height:1,paddingLeft:0,marginLeft:0},B.createElement(CMDIcon,{frame:4*r}),B.createElement(K,{marginRight:1},B.createElement(ShimmerText,{text:e,offset:u})),d?B.createElement(B.Fragment,null,B.createElement(K,{columnGap:1},B.createElement(Y,{dimColor:!0},`(${formatTime3(t)}`),B.createElement(Y,{dimColor:!0},"•"),B.createElement(Y,{color:Ln.GRAY},be.arrowDown),B.createElement(Y,{dimColor:!0},`${formatToken(Math.round(o))}`),B.createElement(Y,{dimColor:!0},"•"),B.createElement(K,{columnGap:1},B.createElement(Y,{bold:!0,color:Ln.GRAY},"esc"),B.createElement(Y,{dimColor:!0},"to interrupt)")))):m?B.createElement(K,{columnGap:1},B.createElement(Y,{dimColor:!0},`(${formatToken(Math.round(o))})`)):B.createElement(B.Fragment,null))},"Status");Nn(),_n(),rr();var DT=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:s})=>{const[o,i]=W(!1),[a,l]=W(0),[u,d]=W(0);G(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=V(()=>{0!==e.trim().length&&n()},[e,n]),p=V(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||o){if(!o||n.isPasteEnd){if(o&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[o,t]);return B.createElement(K,{flexDirection:"column"},r?B.createElement(K,null,B.createElement(CMDIcon,{frame:u}),B.createElement(Y,{color:Ln.WHITE},"Generating agent from description...")):B.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:p,onSubmit:m}),s&&B.createElement(K,{marginTop:1},B.createElement(Y,{color:Ln.RED},`${be.warning} ${s}`)))},"RecommendedFlow");Nt(),JE(),rr();var qT=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[s,o]=W(!1),[i,a]=W(0),l=H(()=>[...WE.map(e=>e.name),...QE.map(e=>e.name)],[]),u=H(()=>[{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))}].filter(e=>e.tools.length>0),[l]),d=H(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),s?(u.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:"}),l.forEach(t=>{e.push({type:"tool",value:t})})):(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[s,u,e,l]),m=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=u.find(e=>e.name===t.value),s=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${s?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${VE[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),p=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return Z((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?p.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=p.length?0:t});else if(l.return||" "===e){const e=p[i];if(e){const i=d[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(o(!s),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),B.createElement(K,{flexDirection:"column"},m.map((e,t)=>{const n=p.findIndex(t=>t.value===e.value),r=-1!==n&&n===i;if("divider"===e.type)return B.createElement(K,{key:`divider-${t}`},B.createElement(Y,{color:Ln.GRAY}," ",e.label));if("spacer"===e.type)return B.createElement(K,{key:`spacer-${t}`,height:1});if("label"===e.type)return B.createElement(K,{key:`label-${t}`},B.createElement(Y,{color:Ln.GRAY}," ",e.label));const s="continue"===e.type;return B.createElement(K,{key:`item-${t}`},B.createElement(Y,{color:r?Ln.WHITE:Ln.GRAY,bold:s&&r},r?">":" "," ",e.label))}),B.createElement(K,{marginTop:1},e.size===l.length&&B.createElement(Y,{color:Ln.GRAY},"All tools selected"),e.size>0&&e.size<l.length&&B.createElement(Y,{color:Ln.GRAY},e.size," tools selected"),0===e.size&&B.createElement(Y,{color:Ln.GRAY},"No tools selected")))},"ToolsSelector");ar(),dn(),ts(),bE(),hi(),un(),nr();var FT=__name(({onComplete:e})=>{const[t,n]=W("location"),[r,s]=W(!1),[o,i]=W(null),[a,l]=W("agentType"),u=H(()=>[...WE.map(e=>e.name),...QE.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,p]=W(d()),g=__name(t=>{n("location"),l("agentType"),p(d()),e(t)},"resetToDefaults"),h=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),f=__name(e=>{p({...m,location:e}),n("method")},"handleLocationSelect"),y=__name(e=>{p({...m,method:e}),n("configuration")},"handleMethodSelect"),w=__name(async()=>{try{i(null),s(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===Ct.ANTHROPIC&&(r=await on.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const o={[wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(o[wt.OAUTH_TOKEN]=`Bearer ${r}`);const a=getApiBaseUrl(),l=new Vb({baseUrl:a}),u=await l.post({headers:o,endpoint:St.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});p({...m,agentType:Ne(u.agentName),sysPrompt:u.systemPrompt,ccToolDefinition:u.toolDescription}),n("tools")}catch(e){e instanceof oi&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?i(nn):i("An error occurred while generating the agent. Please try again.")}finally{s(!1)}},"handleRecommendedSubmit"),S=__name(()=>{p({...m,agentType:Ne(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),b=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),E=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),C=__name(()=>{n("summary")},"handleToolsComplete"),v=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),p({...m,selectedTools:t})},"handleToggleTool"),T=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.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(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),p({...m,selectedTools:n})},"handleToggleCategory");return B.createElement(K,{flexDirection:"column",gap:1},B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.WHITE,bold:!0},"Create new agent"),B.createElement(Y,{color:Ln.GRAY},h())),B.createElement(K,null,"location"===t&&B.createElement(IT,{onSelect:f}),"method"===t&&B.createElement(RT,{onSelect:y}),"configuration"===t&&"recommended"===m.method&&B.createElement(DT,{description:m.recommendedMethodDescription,onChange:e=>p({...m,recommendedMethodDescription:e}),loading:r,errorMessage:o,onSubmit:w}),"configuration"===t&&"manual"===m.method&&B.createElement(K,{flexDirection:"column",gap:1},B.createElement(NT,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>p({...m,agentType:e}),onSysPromptChange:e=>p({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>p({...m,ccToolDefinition:e}),onAgentTypeSubmit:S,onSysPromptSubmit:b,onCCToolDefinitionSubmit:E})),"tools"===t&&B.createElement(qT,{selectedTools:m.selectedTools,onToggleTool:v,onToggleCategory:T,onComplete:C}),"summary"===t&&B.createElement(PT,{config:m,onSaveComplete:g})))},"AgentNew");rr();var jT=__name(({onCancel:e})=>{const[t,n]=W(null),[r,s]=W(null),o=__name(e=>{n(e.value),s(null)},"handleSelect");return Z((t,n)=>{n.escape&&e()}),B.createElement(K,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:Ln.GRAY,borderStyle:"single",flexDirection:"column"},null===t&&B.createElement(xT,{handleSelect:o,createdAgentName:r}),"create_new_agent"===t&&B.createElement(FT,{onComplete:e=>{s(e),n(null)}}))},"AgentsConfig");rr(),Nt(),Nt(),Ot(),bE(),ts(),dn(),CE(),$n(),en(),nr(),ar();var zT=null;function getRequest2(){return zT||(zT=new Vb({baseUrl:getApiBaseUrl()})),zT}function extractText(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t="";for(const n of e){const e=n;"text"===e.type&&e.text&&(t+=e.text)}return t}async function buildAuthHeaders2(){const e=await getConfiguredProvider(),t=await isOAuthEnforced();let n;e===Ct.ANTHROPIC&&(n=await on.getValidAccessToken(),validateOAuthToken({token:n,provider:e}));const r={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(r[wt.OAUTH_TOKEN]=`Bearer ${n}`),r}function buildConversationSummary(e){return e.slice(-6).filter(e=>"user"===e.message.role||"assistant"===e.message.role).map(e=>{const t="user"===e.message.role?"User":"Command Code",n=extractText(e.message.content).slice(0,300).replace(/\s+\S*$/,"").replace(/\n+/g," ").trim();return n?`${t}: ${n}`:null}).filter(e=>null!==e).join("\n")}function hasAssistantMessage(e){return e.some(e=>"assistant"===e.message.role)}async function predictNextPrompt({messages:e,sessionId:t}){if(!hasAssistantMessage(e))return null;const n=buildConversationSummary(e);if(!n)return null;const r=`Conversation:\n${n}\n\nSuggestion:`;try{const e=getRequest2(),n=await buildAuthHeaders2(),s={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],system:'Suggest what the user might naturally type next into Command Code.\n\nLook at the user\'s recent messages and original request. Predict what THEY would type — not what you think they should do. The test: would they think "I was just about to type that"?\n\nRules:\n- Write ONLY the suggestion, no quotes, no labels, no explanation\n- 2-12 words, match the user\'s style\n- Be specific: "run the tests" beats "continue"\n- Stay silent (reply with nothing) if the next step isn\'t obvious from what the user said\n\nNEVER suggest:\n- Evaluative responses ("looks good", "thanks")\n- Questions ("what about...?")\n- Assistant-voice ("Let me...", "I\'ll...", "Here\'s...")\n- New ideas they didn\'t ask about\n- Multiple sentences\n\nExamples:\n- User asked "fix the bug and run tests", bug is fixed → "run the tests"\n- After code written → "try it out"\n- Command Code offers options → the one the user would likely pick\n- Command Code asks to continue → "yes" or "go ahead"\n- Task complete, obvious follow-up → "commit this" or "push it"\n- After error or misunderstanding → nothing',messages:[{role:"user",content:r}],model:vt,max_tokens:30,temperature:.7,stream:!0},threadId:t||crypto.randomUUID()},o=new AbortController,i=e.post({endpoint:St.ALPHA.GENERATE,body:s,headers:n,stream:!0,signal:o.signal});let a;const l=new Promise((e,t)=>{a=setTimeout(()=>{o.abort(),t(new Error("Timeout"))},5e3)});let u;try{u=await Promise.race([i,l])}finally{clearTimeout(a)}if(!u)return dlog("[PromptPredictor] no response stream"),null;const d=je.fromReadableStream(u);let m="";d.on("text",e=>{m+=e}),await d.finalMessage();const p=m.trim().replace(/^["']|["']$/g,"").replace(/\n.*$/,"");if(!p)return null;const g=p.replace(/[.?!]+$/,"").trim();return g?(dlog(`[PromptPredictor] predicted: "${g}"`),g):null}catch(e){return dlog(`[PromptPredictor] failed: ${e instanceof Error?e.message:String(e)}`),null}}__name(getRequest2,"getRequest"),__name(extractText,"extractText"),__name(buildAuthHeaders2,"buildAuthHeaders"),__name(buildConversationSummary,"buildConversationSummary"),__name(hasAssistantMessage,"hasAssistantMessage"),__name(predictNextPrompt,"predictNextPrompt"),$n();var BT=['Try "how to log errors?"','Try "text diagram how <@file> works?"','Try "add tests for <@file>"','Try "refactor this to use async/await"','Try "what does this function do?"','Try "find all usages of <function>"','Try "fix the TypeScript errors"','Try "explain the architecture"','Try "write docs for <@file>"','Try "optimize this for performance"','Try "review this code for bugs"','Try "how does <feature> work?"'];function getRandomSuggestion(){const e=Math.floor(Math.random()*BT.length);return BT[e]??BT[0]??""}function usePredictedPlaceholder({contextEngineRef:e,isCmdCodeBusy:t}){const[n,r]=W(()=>(e.current?.getMessages().length??0)>0?"":getRandomSuggestion()),[s,o]=W(!1),i=Q(t);return G(()=>{const n=i.current;if(i.current=t,dlog(`[usePredictedPlaceholder] wasBusy: ${n}, isCmdCodeBusy: ${t}`),!n||t)return;if(!e.current)return;const s=e.current.getMessages(),a=e.current.getSessionId();dlog(`[usePredictedPlaceholder] Triggering prediction with ${s.length} messages`),r(""),o(!1);let l=!1;return predictNextPrompt({messages:s,sessionId:a}).then(e=>{dlog(`[usePredictedPlaceholder] Prediction result: ${e}`),e&&!l&&(r(e),o(!0))}).catch(e=>{dlog(`[usePredictedPlaceholder] Prediction error: ${e}`)}),()=>{l=!0}},[t,e]),{placeholder:n,isPrediction:s,onAccepted:V(()=>{r(""),o(!1)},[])}}function useTerminalWidth(){const{stdout:e}=X(),[t,n]=W(()=>e.columns??80);return G(()=>{const t=__name(()=>n(e.columns??80),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}__name(getRandomSuggestion,"getRandomSuggestion"),__name(usePredictedPlaceholder,"usePredictedPlaceholder"),Nt(),__name(useTerminalWidth,"useTerminalWidth"),Nt(),Nt(),vn(),Ot(),_n(),ln(),Nt();var UT=n(y(),"commandcode-images"),WT={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{E(UT)||C(UT,{recursive:!0});const r=WT[e.mediaType]||".png",s=`image-${t}-${Date.now()}${r}`,o=n(UT,s),i=Buffer.from(e.data,"base64");return v(o,i),o}catch{return null}}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,detectedContent:n,setInput:r,setDetectedImages:s,setDetectedContent:o,incrementInputKey:i}=e,a=V((e,t)=>{s(t=>[...t,e]),r(t),i()},[s,r,i]),l=Q(!1),u=Q(""),d=Q(null),m=Q(""),p=V(async(e,t)=>{let s=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectDroppedImageFile(s);if(l)return void a(l,t);const u=await detectClipboardImage();if(u)return void a(u,t);let d=s;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#${n.length+1}]`;o(e=>[...e,d]),r(t+e)}else r(t+d);i()}},[a,n.length,o,r,i]),g=V(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(l.current){const e=u.current,t=m.current;u.current="",m.current="",l.current=!1,d.current=null,e&&await p(e,t)}},500)},[p]);return{handlePaste:V(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return l.current&&(l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)),await p(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!l.current)return l.current=!0,m.current=n.textBeforePaste??t,u.current=n.pastedContent??n.cleanedContent,g(),!0;if(l.current&&!n.isPasteEnd)return void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current)),g(),!0;if(l.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current));const e=u.current,t=m.current;return u.current="",m.current="",l.current=!1,await p(e,t),!0}if(n.isPasteEnd&&!n.isPasteStart&&!l.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return a(e,t),!0}return!1},[t,p,g,a]),resetPasteState:V(()=>{l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:V(()=>l.current,[])}}__name(saveTempImage,"saveTempImage"),ar(),Nt(),Nn(),_n(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),Nn(),Nt(),Nt();var QT=["code --wait","cursor --wait","nano"],GT=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return GT.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 I(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of QT)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var HT=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 HT;t=ensureWaitFlag(t);const r=n(y(),`commandcode-${Date.now()}.md`);return await M(r,e),new Promise((e,n)=>{const s=t.split(" ").filter(e=>e.length>0),o=s[0],i=s.slice(1),a=N(o,[...i,r],{stdio:"inherit"});a.on("close",async()=>{try{const t=await O(r,"utf-8");await D(r),e(t.trimEnd())}catch(e){n(e)}}),a.on("error",async e=>{try{await D(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[s,o]=W(!1),[i,a]=W(null),l=V(async()=>{if(!s){o(!0),a(null);try{const s=e.replace(/\n+$/,""),o=await openInEditor2(s);t(o),n(e=>e+1),r?.()}catch(e){a(e instanceof HT?"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{o(!1)}}},[e,t,r,s]),u=V(()=>{a(null)},[]);return{isEditorOpen:s,editorError:i,handleOpenInEditor:l,clearEditorError:u}}__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"),Nt(),Nt(),Nt(),Nt(),Ot(),$n(),lr(),yr(),Nt(),Ot();var VT=t.join(f.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(VT);S.existsSync(e)||S.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!S.existsSync(VT))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=S.readFileSync(VT,"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(),S.writeFileSync(VT,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"),lr();var KT=Ve(x),YT=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!process.env.COMMANDCODE_SKIP_UPDATES||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=I("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return YT.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(tt.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&tt.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&tt.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:s,updateAvailable:o}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:s,updateAvailable:o}}async function executeUpdate(e){try{return await KT(`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(!tt.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=Ie(`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 s=n||await checkForUpdateAvailable();return s?.updateAvailable?(r?.(s.latestVersion),await executeUpdate(s.latestVersion)?{success:!0,updateInfo:s}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:s})):{success:!1}}function getCurrentGitBranch(){try{return I("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()}}__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");var JT=new Set(["OPEN","MERGED","CLOSED"]),XT=null;function getCachedPRInfo(e){if(XT&&XT.branch===e){if(!(Date.now()-XT.timestamp>3e5))return XT.result;XT=null}}function setPRCache(e,t){XT={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((s,o)=>{R(e,[...t],{encoding:n,timeout:r},(e,t)=>{e?o(e):s(t.trim())})})}function parsePRResponse(e){try{const t=JSON.parse(e);return t.number&&t.url&&t.state&&JT.has(t.state)?{number:t.number,title:t.title||"",url:t.url,state:t.state}:null}catch{return null}}__name(getCachedPRInfo,"getCachedPRInfo"),__name(setPRCache,"setPRCache"),__name(execFileAsync,"execFileAsync"),__name(parsePRResponse,"parsePRResponse");var ZT=__name(async()=>{const e=getCurrentGitBranch();if(!e)return null;if("main"===e||"master"===e)return null;const t=getCachedPRInfo(e);if(void 0!==t)return t;try{const t=parsePRResponse(await execFileAsync({cmd:"gh",args:["pr","view","--json","number,title,url,state"],encoding:"utf-8",timeout:3e3}));return setPRCache(e,t),t}catch{return setPRCache(e,null),null}},"detectPR"),ek=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=W(null),s=Q(!1);return G(()=>{if(!t||s.current)return;let e=!0;return s.current=!0,ZT().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=nt(),r=n(e,".gitignore");if(E(r))try{const e=b(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}rr(),Nt(),rr(),__name(loadGitignore,"loadGitignore");var tk=__name(({onSelectFile:e,onClose:t,searchQuery:i=""})=>{const[a,l]=W(process.cwd()),[u,d]=W([]),[m,p]=W(0),[g,h]=W(0),f=i.trim()?15:10,y=V((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const o=n(t,e);try{const e=T(o),i=[];return e.forEach(e=>{const a=n(o,e);try{const e=k(a),n=s(t,a);if(r.ignores(n))return;i.push({name:n,path:a,isDirectory:e.isDirectory()})}catch{}}),i.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),i.slice(0,50)}catch{}}if(e.includes("/")){const o=e.split("/"),i=o.pop()||"",a=n(t,o.join("/"));try{const e=T(a),o=[],l=i.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!i||u.includes(l)){const i=n(a,e);try{const e=k(i),n=s(t,i);if(r.ignores(n))return;o.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),o.slice(0,50)}catch{}}const o=[],i=e.toLowerCase(),a=__name((e,l=0)=>{if(!(l>8))try{T(e).forEach(u=>{const d=n(e,u);try{const e=k(d),n=s(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(i)||m.includes(i))&&o.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==u&&a(d,l+1)}catch(e){}})}catch(e){}},"searchRecursively");return a(t),o.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),s=n===i,o=r===i;if(s&&!o)return-1;if(!s&&o)return 1;const a=n.split("/").pop()||"",l=r.split("/").pop()||"",u=a.includes(i),d=l.includes(i);if(u&&!d)return-1;if(!u&&d)return 1;const m=e.name.split("/").length,p=t.name.split("/").length;return m!==p?m-p:e.name.localeCompare(t.name)}),o.slice(0,50)},[]),w=V(e=>{try{const t=T(e),o=[],i=process.cwd(),a=loadGitignore(i);"/"!==e&&o.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=k(r),n=s(i,r);if(a.ignores(n))return;o.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(o),p(0),h(0)}catch{}},[]);G(()=>{if(i.trim()){const e=y(i);d(e),p(0),h(0)}else w(a)},[a,w,i,y]),Z((n,r)=>{if(r.escape)t();else if(r.upArrow)p(e=>{const t=Math.max(0,e-1);return t<g&&h(t),t});else if(r.downArrow)p(e=>{const t=Math.min(u.length-1,e+1);return t>=g+f&&h(t-f+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!i.trim()&&l(o(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const S=u.slice(g,g+f);return B.createElement(K,{flexDirection:"column",paddingLeft:1},B.createElement(K,{marginBottom:1,flexDirection:"column"},B.createElement(Y,{color:Ln.DIM},i.trim()?`Searching for: "${i}"`:`Files: ${a}`),B.createElement(Y,{color:Ln.DIM},i.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===S.length?B.createElement(Y,{color:Ln.DIM},i.trim()?`No files found matching "${i}"`:"No files found in this directory"):S.map((e,t)=>{const n=g+t,r=e.name,s=n===m;return B.createElement(Y,{key:e.path,color:s?Ln.GREEN:Ln.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Nt(),Ot(),ir(),rr(),Nt(),rr();var nk=__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?Ln.RED:e>=70?Ln.YELLOW:Ln.DIM,"getColor"),s=`context: ${n}% left before auto-compact`;return B.createElement(K,{paddingRight:1},B.createElement(Y,{color:r(t)},s))},"ContextUsage");Nt(),tC(),jr(),rr();var rk=__name(()=>{const[e,t]=W("continuous learning"),n=Q([]),r=Q(0),s=Q(null),o=Q(!1);G(()=>{const e=__name(e=>"analyzing"===e.type?(o.current=!0,n.current=[],r.current=0,s.current&&(clearTimeout(s.current),s.current=null),void t(e.message)):o.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(o.current=!1,void(n.current.length>0?(r.current=0,i()):t("continuous learning"))):void 0,"handleNewEvent"),i=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const o="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;s.current=setTimeout(()=>{r.current++,i()},o)},"cycleThroughNextEvent");return ZE.on("new-event",e),()=>{ZE.off("new-event",e),s.current&&clearTimeout(s.current)}},[]);const i=`${be.bullet} taste: `,a=i.length+e.length+9>Rr;let l=e;return l=truncateString(a?{text:e,maxChars:Rr}:{text:e,maxChars:Rr-i.length-9-10}),B.createElement(K,{paddingRight:3},!a&&B.createElement(Y,{color:On.TEXT},i),B.createElement(Y,null,l),!a&&B.createElement(Y,{dimColor:!0}," (ctrl+t)"))},"LearningFeedMini");Nt(),rr();var sk=__name(({mode:e,pendingExitKey:t})=>t?B.createElement(Y,{dimColor:!0},"Press Ctrl+C again to exit"):"auto-accept"===e?B.createElement(K,{flexDirection:"row"},B.createElement(Y,{color:Hn},"» accept edits on "),B.createElement(Y,{dimColor:!0},"(shift+tab)")):"plan"===e?B.createElement(K,{flexDirection:"row"},B.createElement(Y,{color:Gn},"plan mode "),B.createElement(Y,{dimColor:!0},"(shift+tab)")):B.createElement(Y,{color:Ln.DIM},"? for shortcuts"),"ModeIndicator");Nt(),rr(),Nt();var ok=__name(({url:e,text:t,dimColor:n=!1,color:r})=>{const s=`]8;;${e}${t}]8;;`;return B.createElement(Y,{dimColor:n,color:r},s)},"TerminalLink"),ik=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?Vn.OPEN:Vn.MERGED;return B.createElement(B.Fragment,null,t&&B.createElement(Y,{dimColor:!0}," · "),B.createElement(Y,{color:n},"PR "),B.createElement(ok,{url:e.url,text:`#${e.number}`,dimColor:!0}))},"PRLinkBadge"),ak=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?B.createElement(B.Fragment,null,t&&B.createElement(Y,{dimColor:!0}," · "),B.createElement(Y,{color:"connected"===e.type?Ln.GREEN:Ln.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),lk=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:s,tasteLearning:o,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:p,isBashMode:g,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w})=>{const S=e>=60;return B.createElement(B.Fragment,null,B.createElement(K,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r||l?B.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(K,{flexDirection:"row",columnGap:0},n&&!l?B.createElement(Y,{color:Un},t):B.createElement(sk,{mode:r,pendingExitKey:l}),!l&&B.createElement(ik,{prInfo:s}),!l&&B.createElement(ak,{indicator:a})),S&&B.createElement(K,{flexDirection:"column",alignItems:"flex-end"},o&&B.createElement(rk,null),i&&B.createElement(nk,{usage:i}))):B.createElement(B.Fragment,null,B.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(sk,{mode:r}),S&&o&&B.createElement(rk,null)),B.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(K,{flexDirection:"row",columnGap:0},B.createElement(Y,{color:n?Un:void 0,dimColor:!n},t),B.createElement(ik,{prInfo:s}),B.createElement(ak,{indicator:a})),S&&i&&B.createElement(nk,{usage:i}))),(u||d||p&&m)&&B.createElement(K,{flexDirection:"row",columnGap:1},u&&B.createElement(Y,null,be.tick," ","Command Code"," updated:"," ",B.createElement(Y,{dimColor:!0},"v",u.updatedFrom),B.createElement(Y,{dimColor:!0}," ",be.arrowRight," "),B.createElement(Y,null,"v",u.updatedTo)),!u&&d&&B.createElement(Y,{color:Ln.YELLOW,dimColor:!0},be.info," Update available:"," ",d.currentVersion," ",be.arrowRight," ",d.latestVersion),p&&m&&B.createElement(Y,{color:Ln.GREEN,dimColor:!0},be.bullet," Provider:"," ",getProviderDisplayName(m)))),g&&B.createElement(K,{paddingLeft:2},B.createElement(Y,{color:Ln.GREEN},"! for bash mode")),f&&h&&B.createElement(K,{paddingLeft:2},B.createElement(Y,{color:Mn},"SHARED: ",h.url," (copied to clipboard)")),y&&B.createElement(K,{paddingLeft:2},B.createElement(Y,{color:y.includes("NOT SHARED")?Ln.RED:Mn},y)),w&&B.createElement(K,{paddingLeft:2},B.createElement(Y,{color:Mn},w)))},"BottomIndicator");Nt(),CE(),jr(),rr();var ck=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=W([]),[s,o]=W(0),[i,a]=W(!0);G(()=>{l()},[]);const l=__name(async()=>{a(!0);const e=await Yb.listSessions();r(e.slice(0,30)),a(!1)},"loadSessions");if(Z((r,i)=>{i.escape?t():i.upArrow?o(e=>Math.max(0,e-1)):i.downArrow?o(e=>Math.min(n.length-1,e+1)):i.return&&n.length>0&&s<n.length&&e(n[s].id)}),i)return B.createElement(K,{flexDirection:"column",paddingLeft:2},B.createElement(Y,{color:Ln.GRAY},"Loading sessions..."));if(0===n.length)return B.createElement(K,{flexDirection:"column",paddingLeft:2},B.createElement(Y,{color:Ln.GRAY},"No previous sessions found"),B.createElement(Y,{color:Ln.DIM,dimColor:!0},"Press ESC to go back"));const u=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(n/36e5),o=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:s<24?`${s}h ago`:`${o}d ago`},"formatRelativeTime"),d=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),m=__name(e=>truncateString({text:d(e),maxChars:Nr}),"truncateMessage"),p=__name(e=>e.title?d(e.title):m(e.firstMessage),"getSessionSummary");return B.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},B.createElement(Y,{color:Ln.CYAN,bold:!0},"Resume Session"),B.createElement(Y,{color:Ln.DIM,dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),B.createElement(K,{marginTop:1}),B.createElement(K,{columnGap:2,marginBottom:1},B.createElement(K,{width:5},B.createElement(Y,{color:Ln.GRAY}," ")),B.createElement(K,{width:13},B.createElement(Y,{color:Ln.GRAY},"Modified")),B.createElement(K,{width:20},B.createElement(Y,{color:Ln.GRAY},"Git Branch")),B.createElement(K,{width:11},B.createElement(Y,{color:Ln.GRAY},"# Messages")),B.createElement(K,null,B.createElement(Y,{color:Ln.GRAY},"Summary"))),B.createElement(K,{columnGap:2},B.createElement(K,{flexDirection:"column",width:5},n.map((e,t)=>B.createElement(Y,{key:`sel-${t}`,color:s===t?Ln.WHITE:Ln.GRAY},s===t?`${be.pointer} ${t+1}.`:` ${t+1}.`))),B.createElement(K,{flexDirection:"column",width:13},n.map((e,t)=>B.createElement(Y,{key:`mod-${e.id}`,color:s===t?Ln.WHITE:Ln.GRAY},u(e.lastModified)))),B.createElement(K,{flexDirection:"column",width:20},n.map((e,t)=>B.createElement(Y,{key:`branch-${e.id}`,color:s===t?Ln.WHITE:Ln.GRAY,wrap:"truncate-end"},e.gitBranch||"-"))),B.createElement(K,{flexDirection:"column",width:11},n.map((e,t)=>B.createElement(Y,{key:`msg-${e.id}`,color:s===t?Ln.WHITE:Ln.GRAY},e.messageCount))),B.createElement(K,{flexDirection:"column"},n.map((e,t)=>B.createElement(Y,{key:`summary-${e.id}`,color:s===t?Ln.WHITE:Ln.GRAY,wrap:"truncate-end"},p(e))))))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],s=0;for(let o=0;o<e;o++){const e=`[Image #${o+1}]`.length,i=e+(r.length>0?1:0);r.length>0&&s+i>t?(n.push(r),r=[o],s=e):(r.push(o),s+=i)}return r.length>0&&n.push(r),n}function shouldSelectImageOnUpArrow({isOnFirstLine:e,imageCount:t,selectedImageIndex:n,historyIndex:r}){return e&&t>0&&-1===n&&-1===r}function nextImageIndex({currentIndex:e,imageCount:t}){return e===t-1?0:e+1}function prevImageIndex({currentIndex:e,imageCount:t}){return 0===e?t-1:e-1}function removeImageAt({images:e,index:t}){const n=e.filter((e,n)=>n!==t);return{remainingImages:n,nextSelectedIndex:n.length>0?n.length-1:-1}}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const s=`[Image #${e+1}]`,o=n?createOSC8Link(`file://${n}`,s,!1):s;return B.createElement(Y,null,r?" ":"",t?B.createElement(Y,{inverse:!0},s):o)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:s}){if(0===e.length)return null;const o=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:s}),i=Math.max(1,r-(o.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return B.createElement(K,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>B.createElement(K,{key:r,flexDirection:"row"},B.createElement(K,{flexShrink:0,marginRight:1},0===r&&B.createElement(Y,{color:Ln.DIM},o)),B.createElement(K,{flexDirection:"row"},e.map((e,r)=>B.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Nt(),rr(),Nt(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Nt(),Sl();var uk=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,s]=W(null),[o,i]=W(!1),a=Q(!1),l=Q(null),[u,d]=W(!1),[m,p]=W("connected"),g=Q(null),h=Q(null),f=V((e,t)=>{h.current&&(clearTimeout(h.current),h.current=null),p(e),d(!0),void 0!==t&&(h.current=setTimeout(()=>{d(!1)},t))},[]),y=V(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),w=V(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new dl,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=g.current;if(null===r?n&&f("connected",3e3):r!==n&&(n?f("connected",2e3):f("disconnected",5e3)),g.current=n,i(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),s(r)}else s(null)}catch{!0===g.current&&f("disconnected",5e3),g.current=!1,i(!1),s(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[f]);G(()=>{if(!t||n)return;w(!0);const e=setInterval(()=>w(!1),500);return()=>{clearInterval(e),y(),l.current?.disconnect(),l.current=null}},[t,n,w,y]);const S={visible:u,message:"connected"===m?`IDE ${be.tick}`:"IDE disconnected",type:m};return{context:r,connected:o,refresh:w,connectionIndicator:S}},"useVSCodeContext");Nt();var dk=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:s}=e.activeFile;t.push(`File: ${n} (${r}, line ${s.line})`)}if(e.selection){const{text:n,startLine:r,endLine:s}=e.selection,o=e.activeFile?.language??"";t.push(`Selected lines ${r}-${s}:`),t.push(`\`\`\`${o}`);const i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"&lt;/ide-context&gt;");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Nt();var mk=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),pk=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const s=e?t?.activeFile:null;if(s?.relativePath){const e=s.relativePath.split("/").pop()||"",t=n<80?15:n<120?25:40;return`In ${e.length>t?e.slice(0,t-1)+"…":e}`}return"? for shortcuts"},"getIndicatorText"),gk=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var hk=__name(()=>B.createElement(K,{flexDirection:"column",paddingLeft:1},B.createElement(Y,{color:Ln.DIM,bold:!0},"Available Shortcuts:"),B.createElement(K,{columnGap:4},B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.DIM},"! for bash mode"),B.createElement(Y,{color:Ln.DIM},"/ for commands"),B.createElement(Y,{color:Ln.DIM},"@ for file paths"),B.createElement(Y,{color:Ln.DIM},"shift + tab to toggle auto-accept")),B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.DIM},"double tap esc to clear input"),B.createElement(Y,{color:Ln.DIM},"ctrl + j / shift + ⏎ for newline"),B.createElement(Y,{color:Ln.DIM},"ctrl + g to open in editor"),B.createElement(Y,{color:Ln.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),fk=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",isPlaceholderPrediction:i=!1,onPlaceholderAccepted:a,showFileList:l,setShowFileList:u,fileSearchQuery:d,setFileSearchQuery:m,onCommand:p,contextUsage:g,tasteLearning:h=!1,tasteUsage:f=!1,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,permissionMode:k="standard",onToggleAutoAccept:_,hintMessage:P,historyManager:A,pendingExitKey:x=null,onOverlayVisibilityChange:I,onDoubleEscapeEmpty:N,onAltP:R,isProcessing:$=!1,ideContextEnabled:L=!0})=>{const[M,O]=W(0),[D,q]=W(!1),[F,j]=W(!1),[z,U]=W(!1),[J,ee]=W(!1),[te,ne]=W(""),[re,se]=W(!1),oe=Q(0),ie=Q(0),[ae,le]=W([]),[ce,ue]=W([]),[de,me]=W(-1),[pe,ge]=W(""),he=Q(!1),fe=Q(!1),[ye,we]=W(-1),[Se,Ee]=W(""),Ce=Q(0),{isEditorOpen:ve,editorError:Te,handleOpenInEditor:ke,clearEditorError:_e}=useExternalEditor({input:e,setInput:n,setInputKey:O,onEditorClose:__name(()=>{he.current=!1},"onEditorClose")}),{handlePaste:Pe,resetPasteState:Ae,isPasting:xe}=useBracketedPaste({input:e,detectedContent:ae,setInput:n,setDetectedImages:ue,setDetectedContent:le,incrementInputKey:__name(()=>O(e=>e+1),"incrementInputKey")}),{context:Ie,connected:Ne,refresh:Re,connectionIndicator:$e}=uk({enabled:L,paused:$}),{stdout:Le}=X(),Me=Le?.columns??80,{pr:Oe}=ek();G(()=>{const e=l||J||re;I?.(e)},[l,J,re,I]);const De=V(()=>{ue([]),me(-1)},[]),qe=V(()=>{n(""),j(!1),ee(!1),ne(""),se(!1),le([]),De(),ge(""),Ae(),we(-1),Ee(""),O(e=>e+1)},[n,Ae,De]),Fe=V(()=>{he.current=!0,n(e+"\n"),O(e=>e+1),setTimeout(()=>{he.current=!1},0)},[e,n]);Z(async(t,r)=>{if(-1!==de&&r.leftArrow)return void me(prevImageIndex({currentIndex:de,imageCount:ce.length}));if(-1!==de&&r.rightArrow)return void me(nextImageIndex({currentIndex:de,imageCount:ce.length}));if(r.upArrow){if(l||J||re)return;const t=e.indexOf("\n"),r=-1===t||Ce.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ce.length,selectedImageIndex:de,historyIndex:ye}))return void me(ce.length-1);if(-1!==de&&me(-1),0!==e.length&&-1===ye&&!r)return;const s=A?.count()??0;if(0===s)return;-1===ye&&Ee(e);const o=Math.min(ye+1,s-1);return void(o!==ye&&(we(o),n(A?.getAt(o)||""),O(e=>e+1)))}if(r.downArrow){if(l||J||re)return;if(-1===ye)return;const t=e.lastIndexOf("\n");if(!(-1===t||Ce.current>t))return;const r=ye-1;return we(r),n(-1===r?Se:A?.getAt(r)||""),void O(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void De();if(r.tab&&!r.shift&&0===e.length&&i&&o&&o.length>0&&!l&&!J&&!re)return he.current=!0,n(o),O(e=>e+1),a?.(),void setTimeout(()=>{he.current=!1},0);if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return he.current=!0,void ke();if(getIsExpandToolShortcut(r,t))return he.current=!0,n(e),O(e=>e+1),void setTimeout(()=>{he.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:xe()}))return fe.current=!0,Fe(),void setTimeout(()=>{fe.current=!1},0);if(r.meta&&r.backspace)return void qe();if(r.meta&&"w"===t)return he.current=!0,void qe();const s=r.ctrl&&"v"===t||gk.includes(t),u=r.meta&&"v"===t;if(s||u){if(s&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();return r&&(ue(e=>[...e,r]),n(t),O(e=>e+1)),void(he.current=!0)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return U(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==de&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ce,index:de});return ue([...e]),void me(t)}if(r.escape){if(-1!==de)return void me(-1);if(J)return;if(re)return se(!1),n(pe),void O(e=>e+1);const t=Date.now();return t-oe.current<500?(e.length>0?qe():N?.(),oe.current=0,ie.current=0):(oe.current=t,D||F||(ie.current=t)),q(!1),void j(!1)}D&&(r.backspace||r.delete)&&0===e.length&&q(!1)}});const je=V(async t=>{if(ve)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void R?.();const s=processBracketedPaste(t);if((s.isPasteStart||s.isPasteEnd||xe())&&await Pe(t))return;if(he.current)return void(he.current=!1);-1!==ye&&we(-1);const o=1===t.length,i=t.slice(-1);if(o){if("?"===i&&!D)return q(!0),n(""),void O(e=>e+1);if("!"===i&&!F)return q(!1),j(!0),n(""),void O(e=>e+1)}if("/"!==i||J||"/"!==t||(ee(!0),ne("")),J&&!t.startsWith("/")&&(ee(!1),ne("")),J&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(ee(!1),ne("")):ne(e)}"@"!==i||l||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(u(!0),m(""));const a=t.lastIndexOf("@");if(t.length<e.length&&-1!==a&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(a+1),n=!e.includes(" "),r=a>0?t[a-1]:"";n&&isPrecededByWhitespace(r)&&(u(!0),m(e))}if(l)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)u(!1),m("");else{const n=t.substring(e+1);m(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);m(e),u(!1)}else m(n)}}D&&(t!==e||t.length<e.length)&&q(!1),Te&&_e(),0===t.length&&(j(!1),ee(!1),ne(""),se(!1),De(),le([]),m(""),ge(""),Ae()),n(t)},[D,e,n,l,u,J,F,ce,ye,Pe,Ae,R,Te,_e,ve,De]),ze=V(async()=>{if(Re(),ie.current=0,D)return void q(!1);let n=e.trim();if(!F&&n.startsWith("/")&&p&&"handled"===(await p(n)).status)return A?.add(n),j(!1),ee(!1),ne(""),De(),le([]),we(-1),void Ee("");n.length>0&&A?.add(n),we(-1),Ee("");let r=[];const s=ce.length>0,o=ae.length>0;if(!F&&s&&(r=[...ce]),!F&&o){let e=n;ae.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:F?"bash":"user",images:r,ideContext:Ie?dk(Ie):void 0}),j(!1),ee(!1),ne(""),De(),le([])},[t,p,D,e,F,ce,ae,A,Re,De]),Be=V(t=>{const r=s(process.cwd(),t);let o;if(l&&""!==d){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),u(!1),m(""),O(e=>e+1)},[n,u,e,l,d,m]),Ue=V(()=>{u(!1),m("")},[u,m]),We=V(t=>{if("/resume"===t)A?.add(t),we(-1),Ee(""),ge(e),ee(!1),ne(""),se(!0),n(""),O(e=>e+1);else{const e=Object.values(Nv).includes(t);ee(!1),ne(""),e?(A?.add(t),we(-1),Ee(""),n(""),O(e=>e+1),p&&p(t)):(n(t+" "),O(e=>e+1))}},[p,n,e,A]),Qe=V(e=>{ee(!1),ne(""),n(e+" "),O(e=>e+1)},[n]),Ge=V(()=>{ee(!1),ne(""),n(""),we(-1),Ee(""),O(e=>e+1)},[n]),He=V(e=>{se(!1),n(""),ge(""),we(-1),Ee(""),O(e=>e+1),p&&p(`/resume:${e}`)},[p,n]),Ve=V(()=>{se(!1),n(pe),we(-1),Ee(""),O(e=>e+1)},[pe,n]),Ke=V(e=>{Ce.current=e},[]),Ye=H(()=>{const t=Oe&&("OPEN"===Oe.state||"MERGED"===Oe.state);return"auto-accept"===k||"plan"===k||Ne||t?!D&&!re:!D&&0===e.length&&!F&&!re},[D,e,F,re,k,Ne,Oe]),Je=Q(new Map),Xe=H(()=>ce.map((e,t)=>{if(Je.current.has(e))return Je.current.get(e)??null;const n=saveTempImage(e,t+1);return Je.current.set(e,n),n}),[ce]),Ze=__name(()=>D||l||J||re||z?0:Ye||x||F?3:4,"getBottomMargin");return B.createElement(K,{width:"100%",flexDirection:"column",marginBottom:Ze()},!re&&B.createElement(K,{flexDirection:"column",width:"100%"},B.createElement(ImageRowsDisplay,{detectedImages:ce,selectedImageIndex:de,imageTempPaths:Xe,termWidth:Me,inHistory:-1!==ye}),B.createElement(Y,{color:F?Ln.GREEN:Ln.GRAY},be.line.repeat(Me)),B.createElement(TextInput,{key:M,value:e,placeholder:ve?"Save and close the editor to continue...":o,onChange:je,onSubmit:()=>{if(!fe.current)return Date.now()-ie.current<100?(ie.current=0,void Fe()):void(l||J||re||ve||ze());fe.current=!1},showCursor:!ve&&r&&-1===de,onCursorChange:Ke,prefix:`${F?"!":be.pointer} `,prefixColor:F?Ln.GREEN:Ln.WHITE}),B.createElement(Y,{color:F?Ln.GREEN:Ln.GRAY},be.line.repeat(Me))),D&&B.createElement(hk,null),z&&B.createElement(K,{paddingTop:1},B.createElement(Y,{color:Ln.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),l&&B.createElement(tk,{onSelectFile:Be,onClose:Ue,searchQuery:d}),J&&B.createElement(Lv,{onSelectCommand:We,onInsertCommand:Qe,onClose:Ge,searchQuery:te}),re&&B.createElement(ck,{onSelectSession:He,onClose:Ve}),(Ye||x)&&B.createElement(lk,{termWidth:Me,indicatorText:pk(Ne,Ie,Me),isIDEIndicator:mk(Ne,Ie),permissionMode:k,prInfo:Oe,tasteLearning:h,contextUsage:g,connectionIndicator:$e,pendingExitKey:x,updateStatus:E,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,isBashMode:F,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:b}),Te&&B.createElement(K,{paddingLeft:1,flexDirection:"column"},B.createElement(Y,{color:Ln.YELLOW},Te)))},"InputBox");Nt(),jr(),rr();var yk=__name(({messages:e})=>0===e.length?null:B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(K,{marginBottom:0},B.createElement(Y,{color:qn,dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>B.createElement(K,{key:t},B.createElement(Y,{dimColor:!0},be.pointerSmall," "),B.createElement(Y,{dimColor:!0},truncateString({text:e,maxChars:80}))))),"QueuedMessages"),wk=B.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:s,setInput:o,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:p=0,contextUsage:g,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,permissionMode:k,onToggleAutoAccept:_,hintMessage:P,historyManager:A,pendingExitKey:x,onResetPendingExitKey:I,onDoubleEscapeEmpty:N,retryAttempt:R,onAltP:$,placeholder:L="Ask your question...",isPlaceholderPrediction:M=!1,onPlaceholderAccepted:O})=>{const[D,q]=W(0),F=Q(s);return G(()=>{x&&s!==F.current&&s.length>0&&I?.(),F.current=s},[s,x,I]),G(()=>{if(!t)return void q(0);const e=setInterval(()=>{q(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),B.createElement(K,{flexDirection:"column"},B.createElement(yk,{messages:e}),B.createElement(K,{flexDirection:"row",justifyContent:"space-between"},B.createElement(K,{flexDirection:"column"},(t||n.isExecuting)&&null===R&&B.createElement(OT,{tokens:p,timeElapsed:D,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),P&&B.createElement(K,{marginLeft:1},B.createElement(Y,{dimColor:!0}," ","⎿"," ","Tip: ",P)))),B.createElement(fk,{input:s,setInput:o,onSubmit:i,placeholder:L,isPlaceholderPrediction:M,onPlaceholderAccepted:O,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:g,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:b,updateStatus:E,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,permissionMode:k,onToggleAutoAccept:_,hintMessage:P,historyManager:A,pendingExitKey:!x||t||n.isExecuting?null:x,onDoubleEscapeEmpty:N,onAltP:$,isProcessing:t}))});Nt(),ns(),ls(),sr(),ir();var Sk=__name(({onComplete:e,onCancel:t})=>{const[n,r]=W(!1),[s,o]=W(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:p}=useAuthFlow({onSuccess:__name((t,n)=>{const s=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";o(s),isInternalTeamFlagEnforced()?r(!0):e(!0,s?`Logged in as ${s}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return Z((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,s?`Logged in as ${s}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");p()}}),n?B.createElement(er,{onSuccess:()=>{e(!0,s?`Logged in as ${s} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,s?`Logged in as ${s}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,s?`Logged in as ${s}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):B.createElement(ss,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");async function discoverOAuthMetadata(e){const t=new d(e),n=`${t.protocol}//${t.host}`;try{const e=`${n}/.well-known/oauth-authorization-server`,t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(e.authorization_endpoint&&e.token_endpoint)return{authorizationEndpoint:e.authorization_endpoint,tokenEndpoint:e.token_endpoint,registrationEndpoint:e.registration_endpoint,scopes:e.scopes_supported}}}catch(e){dlog("[MCP] OAuth discovery endpoint not available",e)}try{const e=`${n}/.well-known/openid-configuration`,t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(e.authorization_endpoint&&e.token_endpoint)return{authorizationEndpoint:e.authorization_endpoint,tokenEndpoint:e.token_endpoint,registrationEndpoint:e.registration_endpoint,scopes:e.scopes_supported}}}catch(e){dlog("[MCP] OIDC discovery not available",e)}return null}async function checkServerAuthRequirements(e){try{const t=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"initialize",id:0,params:{protocolVersion:Ds,capabilities:{},clientInfo:qs}})});return 401===t.status||403===t.status?{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}:{requiresAuth:!1}}catch(e){return{requiresAuth:!1,error:`Server unreachable: ${e instanceof Error?e.message:String(e)}`}}}async function registerOAuthClient({registrationEndpoint:e,clientName:t,redirectUris:n}){try{const r=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:t,redirect_uris:n,token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]})});if(r.ok){const e=await r.json();return{clientId:e.client_id,clientSecret:e.client_secret}}}catch(e){dlog("[MCP] OAuth client registration failed",e)}return null}Nt(),rr(),Nt(),Vs(),Hs(),eo(),Ys(),to(),uo(),mo(),po(),Nt(),mo(),po(),Js(),co(),Nt(),so(),Hs(),$n(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient");var bk=__name(({onClose:e})=>{const[t,n]=W([]),[r,s]=W(!0),[o,i]=W(0),[a,l]=W("list"),[u,d]=W(null);G(()=>{m()},[]);const m=__name(async()=>{s(!0);try{const e=await listMcpServers(),t=getMcpConnectionManager().getConnectedServers(),r=await Promise.all(e.map(async e=>{const n=t.find(t=>t.name===e.name);let r,s,o="disconnected";return n&&"connected"===n.status?(o="connected",r=n.tools.length):n&&"error"===n.status?(o="error",s=n.error):e.config.oauth&&(o=await hasTokens(e.name)?"authenticated":"requires_auth"),{name:e.name,config:e.config,scope:e.scope,status:o,toolCount:r,error:s}}));n(r)}catch{}finally{s(!1)}},"loadServers"),p=H(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),g=p[o]??null;Z((t,n)=>{n.ctrl&&"c"===t?e():n.escape?"actions"===a||"confirm-remove"===a?(l("list"),d(null)):e():"list"===a&&(n.upArrow&&(i(e=>Math.max(0,e-1)),d(null)),n.downArrow&&(i(e=>Math.min(p.length-1,e+1)),d(null)),n.return&&g&&(l("actions"),d(null)))});const h=__name(e=>{switch(e){case"connected":return B.createElement(Y,{color:Ln.GREEN},be.tick);case"authenticated":return B.createElement(Y,{color:Ln.CYAN},be.tick);case"requires_auth":return B.createElement(Y,{color:Ln.YELLOW},be.warning);case"error":return B.createElement(Y,{color:Ln.RED},be.cross);default:return B.createElement(Y,{color:Ln.GRAY},be.circle)}},"getStatusIcon"),f=__name(e=>{switch(e.status){case"connected":return"connected"+(void 0!==e.toolCount?` · ${e.toolCount} tools`:"");case"authenticated":return"authenticated · not connected";case"requires_auth":return"requires authentication";case"error":return e.error||"error";default:return"not connected"}},"getStatusText"),y=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),w=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),S=__name(async e=>{if(g)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)"remove"!==e.value||l("confirm-remove");else{if(!g.config.oauth)return void d({text:"No OAuth configured for this server",color:Ln.YELLOW});d({text:`Authenticating ${g.name}...`,color:Ln.CYAN,loading:!0});try{const e={authorizationUrl:g.config.oauth.authorizationUrl,tokenUrl:g.config.oauth.tokenUrl,clientId:g.config.oauth.clientId,clientSecret:g.config.oauth.clientSecret,scopes:g.config.oauth.scopes},t=await performOAuthFlow(g.name,e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`${be.tick} Authenticated with ${g.name}`,color:Ln.GREEN});try{const e=getMcpConnectionManager();await e.reconnectServer(g.name)}catch{}await m()}else d({text:`${be.cross} Auth failed: ${t.error}`,color:Ln.RED})}catch(e){d({text:`${be.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:Ln.RED})}}else{d({text:`Connecting ${g.name}...`,color:Ln.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.reconnectServer(g.name),d({text:`${be.tick} Connected to ${g.name}`,color:Ln.GREEN}),await m()}catch(e){d({text:`${be.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:Ln.RED})}}else d({text:"Already authenticated",color:Ln.GREEN});else d({text:"Already connected",color:Ln.GREEN});else l("list")},"handleActionSelect"),b=__name(async e=>{if(g)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===g.status&&await e.disconnectServer(g.name),await removeMcpServer({name:g.name,scope:g.scope}),l("list"),await m(),i(e=>Math.min(e,Math.max(0,p.length-2)))}catch(e){d({text:`${be.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:Ln.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Mn,bold:!0},"Manage MCP servers"),B.createElement(Y,{dimColor:!0},"Loading..."));if("confirm-remove"===a&&g)return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Ln.RED,bold:!0},"Remove ",g.name,"?"),B.createElement(Y,{dimColor:!0},"This will remove the server from ",g.scope," config."),B.createElement(K,{marginTop:1},B.createElement(Ke,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:b,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY}," ",t)})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&g){const e=[];return"connected"===g.status?e.push({label:"Connected",value:"connected"}):e.push({label:"Connect",value:"connect"}),g.config.oauth&&("authenticated"===g.status||"connected"===g.status?e.push({label:"Authenticated",value:"authenticated"}):e.push({label:"Authenticate",value:"auth"})),e.push({label:"Remove",value:"remove"}),e.push({label:"Back",value:"back"}),B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Mn,bold:!0},g.name),B.createElement(K,null,h(g.status),B.createElement(Y,{dimColor:!0}," ",f(g))),B.createElement(K,{marginTop:1},B.createElement(Ke,{items:e,onSelect:S,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:Ln.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.WHITE:Ln.GRAY}," ",t)})),u&&B.createElement(K,{marginTop:1},u.loading&&B.createElement(Y,{color:u.color},B.createElement(Se,{type:"dots"})," "),B.createElement(Y,{color:u.color},u.text)),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to go back")))}let E=null;return B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:Mn,bold:!0},"Manage MCP servers"),B.createElement(Y,{dimColor:!0},t.length," ",1===t.length?"server":"servers"),0===t.length?B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,{dimColor:!0},"No MCP servers configured."),B.createElement(Y,{dimColor:!0},'Use "cmd mcp add" to add a server.'),B.createElement(Y,{dimColor:!0},"Docs: https://commandcode.ai/docs/mcp")):B.createElement(K,{marginTop:1,flexDirection:"column"},p.map((e,t)=>{const n=e.scope!==E;E=e.scope;const r=t===o;return B.createElement(B.Fragment,{key:e.name},n&&B.createElement(K,{marginTop:0===t?0:1},B.createElement(Y,{bold:!0},y(e.scope)),B.createElement(Y,{dimColor:!0}," (",w(e.scope),")")),B.createElement(K,{paddingLeft:1},B.createElement(Y,{color:r?Ln.WHITE:Ln.GRAY},r?"› ":" "),B.createElement(Y,{color:r?Ln.WHITE:void 0,bold:r},e.name),B.createElement(Y,{dimColor:!0}," · "),h(e.status),B.createElement(Y,{color:"connected"===e.status?Ln.GREEN:"authenticated"===e.status?Ln.CYAN:"requires_auth"===e.status?Ln.YELLOW:Ln.GRAY}," ",f(e))))})),u&&B.createElement(K,{marginTop:1},u.loading&&B.createElement(Y,{color:u.color},B.createElement(Se,{type:"dots"})," "),B.createElement(Y,{color:u.color},u.text)),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Nt(),qE(),Ot(),un(),rr();var Ek=__name(({onClose:e})=>{const[t,n]=W([]),[r,s]=W(0),[o,i]=W(!0),[a,l]=W(null);G(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const u=__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(Z((t,n)=>{n.escape?e():n.upArrow?s(e=>Math.max(0,e-1)):n.downArrow?s(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&u(d[r]),"1"===t&&d[0]&&u(d[0]),"2"===t&&d[1]&&u(d[1]))}),o)return B.createElement(K,{paddingLeft:1,paddingTop:1},B.createElement(Y,{color:Ln.DIM},"Loading memory files..."));if(a)return B.createElement(K,{paddingLeft:1,paddingTop:1},B.createElement(Y,{color:Ln.RED},be.cross," ",a));const m=d.map((e,t)=>{const n=t+1;let r="",s="";return"project"===e.type?(r=`${n}. Project memory`,s=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,s=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:s}});return B.createElement(K,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:Ln.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},B.createElement(K,null,B.createElement(Y,{color:Ln.WHITE,bold:!0},"Select memory to edit:")),B.createElement(K,{columnGap:4,marginTop:1},B.createElement(K,{flexDirection:"column"},m.map((e,t)=>B.createElement(Y,{key:t,color:r===t?Ln.WHITE:Ln.DIM},r===t?`${sn} `:" ",e.label))),B.createElement(K,{flexDirection:"column"},m.map((e,t)=>B.createElement(Y,{key:t,color:r===t?Ln.WHITE:Ln.DIM},e.description)))))},"MemorySelector");Nt(),Nt();var Ck=rt()?"∴":"#";function AssistantMessage({content:e}){return B.createElement(K,null,B.createElement(Y,null,Ck),B.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Markdown,null,e)))}__name(AssistantMessage,"AssistantMessage"),Nt(),un(),rr();var vk={"Interrupted by user":"Interrupted by user","Insufficient credits":nn};function UserMessage({content:e,images:t,imageCount:n=0}){const r="Interrupted by user"===e,s="Insufficient credits"===e,o=e.startsWith("Error:"),i=r||s||o,a=i&&vk[e]||e,l=null!=t?t.length:n,u=Q(null);null===u.current&&t&&t.length>0&&(u.current=t.map((e,t)=>saveTempImage(e,t+1)));const d=u.current??[];return B.createElement(K,{flexDirection:"column"},B.createElement(K,{backgroundColor:i?void 0:Qn.BG,paddingRight:1},B.createElement(Y,{color:i?Ln.RED:Qn.POINTER,bold:!i},be.pointer),B.createElement(K,{marginLeft:1},B.createElement(Y,{color:i?Ln.RED:Ln.WHITE,wrap:"wrap"},a))),l>0&&B.createElement(K,{marginLeft:1},B.createElement(Y,{dimColor:!0},"⎿"," ",Array.from({length:l},(e,t)=>{const n=d[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let s,o;return n?(s=Ln.YELLOW,o=be.arrowRight):r?(s=Ln.RED,o=be.cross):(s=Ln.GREEN,o=be.tick),B.createElement(K,null,B.createElement(Y,{color:s},o),B.createElement(K,{flexDirection:"column",marginLeft:1},B.createElement(K,null,B.createElement(Y,{color:Ln.GRAY},"$ "),B.createElement(Y,{color:s,bold:!0},e)),B.createElement(K,{columnGap:1,marginLeft:1},B.createElement(Y,null,"⎿"," "),B.createElement(Y,{color:r?Ln.RED:n?Ln.YELLOW:"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(UserMessage,"UserMessage"),Nt(),rr(),__name(BashMessage,"BashMessage"),Nt(),Nt(),Ot();rr(),Nt(),Ot();var Tk="Coding agent that continuously learns your taste of writing code.",kk=34,_k=[{key:"Shift+Tab",description:"Toggle mode (default → auto-accept → plan)"},{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:"Press Esc twice",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],Pk=[{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:"--plan",description:"Start in plan mode"},{key:"--permission-mode <mode>",description:"Set permission mode (standard, plan, auto-accept)"},{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"}],Ak=[{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 (Press Esc twice)"},{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:"/mcp",description:"Manage MCP server connections"},{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:"/review [pr]",description:"Review a pull request (optional PR number)"},{key:"/pr-comments",description:"Fetch all PR comments for current branch"},{key:"/add-dir",description:"Manage additional directory scope"},{key:"/help",description:"Display help information"},{key:"/exit",description:"Exit Command Code"}],xk=[{key:"cmd info",description:"Display system information"},{key:"cmd status",description:"Show authentication status"},{key:"cmd help",description:"Display help information"},{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 mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Ik=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Nk=[{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"}],Rk='Start with a prompt: cmd "fix the login bug"';Nt(),yr();var $k="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]:[$k]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||$k;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||$k}catch{return $k}}function HelpMessage(){const e=getInvokedCommandName(),t=H(()=>Ak.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return B.createElement(K,{flexDirection:"column",paddingY:1},B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(K,null,B.createElement(Y,{bold:!0},"Command Code"),B.createElement(Y,{color:Ln.GRAY}," v","0.17.3")),B.createElement(Y,{color:Ln.GRAY},Tk)),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Usage"),B.createElement(K,{paddingLeft:2},B.createElement(Y,null,e," <command> [options]"))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Options"),B.createElement(K,{flexDirection:"column",paddingLeft:2},Pk.map(t=>B.createElement(K,{key:t.key},B.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},t.description))))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Commands"),B.createElement(K,{flexDirection:"column",paddingLeft:2},xk.map(t=>B.createElement(K,{key:t.key},B.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},t.description))))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Slash Commands"),B.createElement(K,{flexDirection:"column",paddingLeft:2},t.map(e=>B.createElement(K,{key:e.key},B.createElement(Y,null,e.key.padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},e.description))))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Keyboard Shortcuts"),B.createElement(K,{flexDirection:"column",paddingLeft:2},_k.map(e=>B.createElement(K,{key:e.key},B.createElement(Y,null,e.key.padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},e.description))))),B.createElement(K,{flexDirection:"column",marginBottom:1},B.createElement(Y,{bold:!0},"Examples"),B.createElement(K,{flexDirection:"column",paddingLeft:2},Nk.map(t=>B.createElement(K,{key:t.key},B.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(kk)),B.createElement(Y,{color:Ln.GRAY},t.description))))),B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Ln.CYAN},be.pointer),B.createElement(Y,{color:Ln.GRAY}," ",Rk.replace(/cmd/,e))),B.createElement(K,{flexDirection:"column"},B.createElement(Y,{bold:!0},"Links"),B.createElement(K,{flexDirection:"column",paddingLeft:2},Ik.map(e=>B.createElement(K,{key:e.key},B.createElement(Y,null,e.key.padEnd(kk)),B.createElement(Y,{color:Ln.CYAN},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?B.createElement(HelpMessage,null):B.createElement(K,{flexDirection:"column"},B.createElement(Y,{wrap:"wrap"},B.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return B.createElement(K,null,B.createElement(Y,{color:Ln.RED},t?be.pointer:be.warning),B.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?B.createElement(Y,{color:Ln.RED,wrap:"wrap"},e):B.createElement(Markdown,{color:Ln.RED},e)))}function AutoCompactMessage({content:e}){return B.createElement(K,null,B.createElement(Y,{dimColor:!0},be.info),B.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Y,{dimColor:!0},e)))}function TasteSkipMessage(){return B.createElement(K,null,B.createElement(K,{flexShrink:0},B.createElement(Y,{backgroundColor:On.BADGE_BG,color:On.BADGE_FG,bold:!0},`${cv}TASTE${cv}`)),B.createElement(Y,{dimColor:!0}," Skipped. Run "),B.createElement(Y,{color:Yn.CODE},"/learn-taste"),B.createElement(Y,{dimColor:!0}," or "),B.createElement(Y,{color:Yn.CODE},"cmd learn-taste"),B.createElement(Y,{dimColor:!0}," anytime."))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?B.createElement(TasteSkipMessage,null):t?.isAutoCompact?B.createElement(AutoCompactMessage,{content:e}):B.createElement(K,null,B.createElement(Y,{dimColor:!0},be.info),B.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Y,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return B.createElement(K,{flexDirection:"column",marginBottom:0,marginTop:-1},B.createElement(K,{columnGap:1},B.createElement(Y,null,"⎿"," "),B.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Y,{color:n?Ln.YELLOW:void 0},e))),t&&B.createElement(K,{marginLeft:3},B.createElement(Y,{dimColor:!0},"See ",t)))}function IDEStatusMessage({status:e,ide:t,details:n}){return B.createElement(K,{flexDirection:"column"},B.createElement(K,null,"connected"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.GREEN},be.tick),B.createElement(Y,null," Connected to "),B.createElement(Y,{color:Ln.CYAN},t)),"installed"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.GREEN},be.tick),B.createElement(Y,null," Installed for "),B.createElement(Y,{color:Ln.CYAN},t)),"needs_reload"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.YELLOW},be.circle),B.createElement(Y,null," "),B.createElement(Y,{color:Ln.CYAN},t),B.createElement(Y,null," extension needs reload")),"failed"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.RED},be.cross),B.createElement(Y,null," Install failed")),"not_in_ide"===e&&B.createElement(Y,null,B.createElement(Y,{color:Ln.YELLOW},be.circle),B.createElement(Y,null," Not in IDE"))),n?.map((e,t)=>B.createElement(Y,{key:t,dimColor:!0}," ",e)))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0;return B.createElement(UserMessage,{content:e.input,images:t})}return"assistant"===e.role?B.createElement(AssistantMessage,{content:e.input}):"tool"===e.role?B.createElement(ToolMessage,{name:Qo(e.name||""),input:e.input,output:e.output||"",isPending:Bo(e),hasError:zo(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?B.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:Bo(e),hasError:zo(e)}):"system"===e.role?B.createElement(SystemMessage,{content:e.input}):"info"===e.role?B.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?B.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?B.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?B.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName(e){const t=Object.values(kt).find(t=>t.id===e);return t?t.name.toLowerCase().replace(" ","-"):e.includes("sonnet-4-6")?"sonnet-4.6":e.includes("sonnet")?"sonnet-4.5":e.includes("opus-4-6")?"opus-4.6":e.includes("opus")?"opus-4.5":"sonnet-4.6"}function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages (ctrl+e to expand more) `,r=Math.max(0,Math.floor((t-n.length)/2)),s="─".repeat(r);return B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},s,n,s))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),ir(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Jo(),Nt(),rr(),__name(ErrorMessage,"ErrorMessage"),Nt(),rr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(InfoMessage,"InfoMessage"),Nt(),rr(),__name(CommandResultMessage,"CommandResultMessage"),Nt(),rr(),__name(IDEStatusMessage,"IDEStatusMessage"),yr(),Ot(),ir(),rr(),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName,"getModelShortName"),__name(TranscriptDivider,"TranscriptDivider");var Lk=B.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:s,hiddenCount:o=0})=>{const i=o>0?{role:"transcript-divider",count:o}:null,a=[...t?["header"]:[],...i?[i]:[],...e],l=useTerminalWidth(),u=H(()=>BC(l),[l]),d=H(()=>getPackageJson().version||"0.0.0",[]),m=H(()=>getGitHeaderInfo(),[]),p=H(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),g=s?getModelShortName(s):"sonnet-4.5";return B.createElement(J,{items:a,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return B.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:l});if("header"===e)return B.createElement(K,{key:"header",marginBottom:1,flexDirection:"column"},B.createElement(Ze,{name:"vice"},B.createElement(Y,null,u.trimEnd())),B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(K,null,B.createElement(Y,{color:Wn},"# "),B.createElement(Y,{bold:!0},"Command Code"),B.createElement(Y,{color:Wn}," v",d)),B.createElement(Y,{color:Wn},"# models: ",g," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),B.createElement(K,null,B.createElement(Y,{color:Wn},"# ",p,m&&m.isLocal&&m.branch&&B.createElement(Y,{color:Wn}," (branch: ",m.branch,")")))));const t=e,n=renderFeedEntry(t,r);return B.createElement(K,{key:t.id,marginBottom:1,width:"90%"},n)})});Nt(),Jo(),ar(),rr();var Mk=U(__name(function LiveAgentStatusInner2({entry:e}){const t=Qo(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],s=r?r+(n.includes(".")||n.includes("\n")?".":""):n,o=e.metadata?.tokensUsed||0,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=W(".");return G(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),B.createElement(K,{flexDirection:"column",marginBottom:1,width:"90%"},B.createElement(K,null,B.createElement(Y,{backgroundColor:zn.BG,color:zn.FG,bold:!0},` ${t} `),s&&B.createElement(Y,null," ","(",s,")")),B.createElement(K,{columnGap:1,marginLeft:1},B.createElement(Y,null,"⎿"," "),B.createElement(Y,{color:Ln.GRAY},"Running (",formatTime2(i)," | ",formatTokens(o),")",l)),a.length>0&&B.createElement(K,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=Qo(e.name);return B.createElement(K,{key:t,columnGap:1},B.createElement(Y,{color:Ln.GRAY},"⎿"),B.createElement(Y,{color:Ln.GRAY}," ",n),e.input&&B.createElement(Y,{color:Ln.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),Ok=U(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:B.createElement(Mk,{entry:e})},"LiveAgentStatus"));function getModelOptions(){return Object.values(kt).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}Nt(),Ot(),rr(),__name(getModelOptions,"getModelOptions");var Dk=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),s=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0;return B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,null,B.createElement(Y,{color:Mn,bold:!0},"Select model")),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),B.createElement(Ke,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:e?Ln.GREEN:Ln.GRAY},e?be.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>{const s=r.find(e=>e.label===t),o=s?.value===n,i=e?Ln.GREEN:Ln.GRAY;return B.createElement(K,null,B.createElement(Y,{color:i},` ${(s?.label||t).padEnd(24)}`),B.createElement(Y,{dimColor:!0},s?.description),o&&B.createElement(Y,{color:Ln.GREEN}," ",be.tick))}}),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press "),B.createElement(Y,{dimColor:!0,bold:!0},"Esc"),B.createElement(Y,{dimColor:!0}," to cancel")))},"ModelSelector");Nt(),ir(),rr();var qk=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),s=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0,i=n&&-1===o;return B.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},B.createElement(K,null,B.createElement(Y,{bold:!0},"Select AI Provider")),n&&B.createElement(K,{flexDirection:"row"},B.createElement(Y,{dimColor:!0},"Current: "),B.createElement(Y,{color:Ln.GREEN},getProviderDisplayName(n)),i&&B.createElement(Y,{color:Ln.YELLOW}," [OAuth enforced]"))),B.createElement(K,{marginBottom:0},B.createElement(Y,{dimColor:!0},"Available Providers:")),B.createElement(Ke,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>B.createElement(Y,{color:e?Ln.CYAN:Ln.GRAY,bold:e},e?be.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>B.createElement(Y,{color:e?Ln.CYAN:Ln.GRAY,bold:e},` ${t}`)}),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=W(0);if(G(()=>{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 B.createElement(K,{marginBottom:1},B.createElement(Y,{color:Kn,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Nt(),rr(),__name(RetryMessage,"RetryMessage"),Nt(),Oi(),jr(),un(),rr();var Fk=[{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"}],jk=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=H(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[s,o]=W(Math.max(0,r.length-1)),[i,a]=W(Math.max(0,r.length-8)),[l,u]=W("checkpoint"),[d,m]=W(null),[p,g]=W(0),h=H(()=>{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]),f=H(()=>h?Fk:Fk.filter(e=>"conversation"===e.mode),[h]);if(G(()=>{if(r.length>0){const e=r.length-1;o(e),a(Math.max(0,r.length-8))}},[r.length,8]),Z((e,h)=>{h.escape?"mode"===l?(u("checkpoint"),m(null),g(0)):n():"checkpoint"===l?h.upArrow?o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):h.downArrow?o(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):h.return&&r.length>0&&(m(r[s]),u("mode"),g(0)):"mode"===l&&(h.upArrow?g(e=>Math.max(0,e-1)):h.downArrow?g(e=>Math.min(f.length-1,e+1)):h.return&&d&&f[p]&&t({messageId:d.messageId,mode:f[p].mode}))}),0===r.length)return B.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(Y,{color:Mn,bold:!0},"Rewind"),B.createElement(Y,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press "),B.createElement(Y,{dimColor:!0,bold:!0},"Esc"),B.createElement(Y,{dimColor:!0}," to close")));if("mode"===l&&d)return B.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(Y,{color:Mn,bold:!0},"Rewind"),B.createElement(K,{marginBottom:1},B.createElement(Y,{dimColor:!0},"Restore to: "),B.createElement(Y,{color:Ln.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),B.createElement(K,{flexDirection:"column"},f.map((e,t)=>{const n=p===t,r=t===f.length-1;return B.createElement(K,{key:e.mode,flexDirection:"column"},B.createElement(K,{flexDirection:"row"},B.createElement(Y,{color:n?Mn:void 0},n?`${sn} `:" "),B.createElement(K,{flexDirection:"column"},B.createElement(Y,{color:n?Mn:Ln.WHITE},e.label),B.createElement(Y,{dimColor:!0},e.description))),!r&&B.createElement(Y,null," "))})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press "),B.createElement(Y,{dimColor:!0,bold:!0},"Enter"),B.createElement(Y,{dimColor:!0}," to confirm, "),B.createElement(Y,{dimColor:!0,bold:!0},"Esc"),B.createElement(Y,{dimColor:!0}," to go back")));const y=r.slice(i,i+8);return B.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(Y,{color:Mn,bold:!0},"Rewind"),B.createElement(Y,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),B.createElement(K,{marginTop:1}),B.createElement(K,{flexDirection:"column"},y.map((e,t)=>{const n=i+t,o=s===n,a=e.filesModified.length,l=t===y.length-1,u=n===r.length-1;return B.createElement(K,{key:e.messageId,flexDirection:"column"},B.createElement(K,{flexDirection:"row"},B.createElement(Y,{color:o?Mn:void 0},o?`${sn} `:" "),B.createElement(K,{flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{color:o?Mn:Ln.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),B.createElement(Y,{dimColor:!0}," • "),B.createElement(Y,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),B.createElement(Y,{dimColor:!0},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&B.createElement(Y,null," "))})),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Press "),B.createElement(Y,{dimColor:!0,bold:!0},"Enter"),B.createElement(Y,{dimColor:!0}," to select, "),B.createElement(Y,{dimColor:!0,bold:!0},"Esc"),B.createElement(Y,{dimColor:!0}," to cancel")))},"RewindSelector");Nt(),$n(),Nt(),Nt(),tC();var zk=__name(e=>{const[t,n]=W(e),[r,s]=W(null);return G(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),s(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}):s(e.message)},"handleNewEvent");return ZE.on("reset",t),ZE.on("new-event",r),()=>{ZE.off("reset",t),ZE.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:s}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new Vb({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let s;if(n===Ct.ANTHROPIC)try{const e=await on.getValidAccessToken();validateOAuthToken({token:e,provider:n}),s=e}catch(e){dlog("Failed to get or validate Anthropic OAuth token:",e instanceof Error?e.message:String(e))}const o={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(o[wt.OAUTH_TOKEN]=`Bearer ${s}`),{request:t,headers:o}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const s of e){const e=estimateTokens(s);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([s])):r+e>2e3?(n.length>0&&t.push(n),n=[s],r=e):(n.push(s),r+=e)}return n.length>0&&t.push(n),t}Nt(),Nt(),gC(),bE(),ts(),$E(),$n(),tC(),Nt(),$n(),tC(),$E(),Nt(),Nt(),Ot(),bE(),ts(),dn(),CE(),$n(),nr(),ar(),__name(createRequestClient,"createRequestClient"),Nt(),$E(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Nt(),Nt(),Ot(),$n(),en(),tC(),Nt();var Bk="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 buildRequestBody2(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:`anthropic:${Bk}`,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}`),ZE.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()}`),ZE.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=je.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 ${St.ALPHA.GENERATE} with model: ${Bk}`);const r=buildRequestBody2(n);let s;try{s=await e.post({endpoint:St.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(s),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,s){let o=0;for(const e of n)o+=estimateTokens(e);dlog(`[Observer] batch ${r}/${s}: ${n.length} prompts`);const i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(ZE.observerHasRun)return;ZE.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 s=Math.min(r.length,6);for(let t=0;t<s;t++){if(ZE.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const s=r[t];try{await processBatch(e,n,s,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),ZE.addEvent({type:"progress",message:"Continuing without live observations..."})}}__name(buildObserverPrompt,"buildObserverPrompt"),__name(buildRequestBody2,"buildRequestBody"),__name(createInsightEmitter,"createInsightEmitter"),__name(processStream,"processStream"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var Uk=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(h.homedir(),".claude","projects");await $.access(r);const s=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${s}`);const o=(await $.readdir(r)).filter(e=>e===s);for(const s of o){const o=e.join(r,s);try{if(!(await $.stat(o)).isDirectory())continue;const r=(await $.readdir(o)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const s of r){const r=e.join(o,s),i=await $.stat(r),a=s.replace(".jsonl","");if(n.push({id:a,filePath:r,createdAt:i.birthtime,lastModified:i.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{ZE.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&ZE.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 $.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=[],s=0;for(const o of e){const e=estimateTokens(o);if(e>t){r.length>0&&(n.push(r),r=[],s=0);const e=this.splitLargePrompt(o,t);for(const t of e)n.push([t])}else s+e<=t?(r.push(o),s+=e):(r.length>0&&n.push(r),r=[o],s=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let s="",o=0;for(const e of r){const r=estimateTokens(e);o+r<=t?(s+=(s?"\n":"")+e,o+=r):(s&&n.push(s),s=e,o=r)}return s&&n.push(s),n}static async importAndLearn(){const e=[],t=[],n=[],r=[];try{ZE.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const s=await loadProjectSettings(),o=s.tasteOnboarding?.learnedSessions||{},i=o["claude-code"]?.length||0,a=o.codex?.length||0;dlog(`[Import] loaded settings: claude-code=${i} learned, codex=${a} learned`);const l=await findNewSessions(o),u=l["claude-code"]||[],d=l.codex||[],m=u.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${u.length} new, codex=${d.length} new`),0===m){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}`);ZE.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:n>0?`From ${r.join(" + ")} sessions`:"No sessions found for this project"});const s=[];return e.length>0&&s.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&s.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:n,learnedSessions:i+a,agentSessions:s,status:"already-learned"}}if(u.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>u.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 p=n.length+r.length;dlog(`[Import] total sessions: ${p} (claude-code: ${n.length}, codex: ${r.length})`),ZE.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){ZE.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 h=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${h.length} batches`);const f=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});ZE.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${h.length} batch${1===h.length?"":"es"}`});try{const s=getApiBaseUrl(),o=new Vb({baseUrl:s});let i=!0;for(let e=0;e<h.length;e++){const t=h[e],n=e+1,r=h.length;r>1&&ZE.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const s=this.formatBatchLearning(t),a=new rC({request:o,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:s}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await a.checkAndProcess({messages:l})).success||(i=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${i}`),ZE.markLearningComplete(),await f,i){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 a=await this.extractLearningSummary(),l=[];if(n.length>0&&l.push(`Claude Code (${n.length})`),r.length>0&&l.push(`Codex (${r.length})`),!i){const s="Learning failed - sessions not marked as learned";return e.push(s),ZE.addEvent({type:"error",message:s}),{success:!1,totalPrompts:t.length,preferencesLearned:a.totalLearnings,errors:e,totalSessions:p,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 ZE.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${l.join(" + ")}`,learningCount:a.totalLearnings,categories:a.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:a.totalLearnings,errors:e,totalSessions:p,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),ZE.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 $.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),s=r?r.length:0;return{totalLearnings:s,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")}};tC();var Wk=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),Qk=__name(e=>{const[t,n]=W({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return G(()=>{ZE.reset(),ZE.markImportStarted(),(async()=>{try{const t=await Promise.race([Uk.importAndLearn(),Wk(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");Nt();var Gk=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{Z((r,s)=>{n&&(s.escape&&e(),(s.return||"\n"===r)&&t())})},"useKeyboardInput");Nt(),$n();var Hk=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=W(null),[s,o]=W(null),i=Q(!1);return G(()=>{if(i.current)return;let n=null;return(async()=>{try{i.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),o(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:s,isLoading:!n&&!s}},"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{ZE.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{ZE.reset(),e()}}Nt(),$n(),Nt(),$n(),tC(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var Vk=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=Q(n),s=V(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),o=V(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=V(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=V(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=V(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:s,handleImportComplete:o,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Nt(),$n();var Kk=__name(({conditions:e,autoLearn:t})=>{const[n,r]=W("checking"),s=Q(!1);return G(()=>{if(e&&!s.current){if(s.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),G(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Nt(),Nt(),rr();var Yk=__name(({error:e})=>B.createElement(K,{padding:1},B.createElement(K,{flexDirection:"column",borderColor:Ln.RED,padding:1},B.createElement(K,{marginBottom:1},B.createElement(Y,null,"Error initializing onboarding: ",e)),B.createElement(K,null,B.createElement(Y,null,"Continuing without onboarding...")))),"OnboardingError");Nt(),Nt(),Ot(),rr();var Jk=__name(()=>`(run /${Tt.LEARN_TASTE} anytime)`,"getSkipHint"),Xk=__name(()=>B.createElement(Y,null,"Skip for now"," ",B.createElement(Y,{dimColor:!0},Jk())),"SkipOptionText"),Zk=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[s,o]=W(1);return Z((e,t)=>{t.escape?r():t.upArrow||t.downArrow?o(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===s?n():r()):r():n()}),B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:On.TEXT,paddingX:1,paddingY:0},B.createElement(Y,{color:On.TEXT,bold:!0},"Build Your Coding Taste"),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(Y,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),B.createElement(K,{marginTop:1},B.createElement(Y,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),B.createElement(K,{marginTop:1,flexDirection:"column"},B.createElement(K,null,B.createElement(Y,{color:1===s?On.TEXT:Ln.GRAY},1===s?be.pointer:" "," 1. Yes, learn from my sessions (recommended)")),B.createElement(K,null,B.createElement(Y,{color:2===s?On.TEXT:Ln.GRAY},2===s?be.pointer:" "," 2."," ",B.createElement(Xk,null)))),B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice");Nt(),Nt(),rr();var e_=__name(({error:e})=>B.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:Ln.RED,paddingX:2,paddingY:1,marginBottom:2},B.createElement(Y,{color:Ln.RED,bold:!0},"Oops, something went wrong:"),B.createElement(K,{marginTop:1},B.createElement(Y,null,e))),"ErrorSection");Nt(),Nt(),rr(),Nt(),Nt(),Nt(),rr();var t_=[be.bullet,be.squareSmallFilled,be.lozenge,be.star,be.triangleRight,be.triangleUp,be.circleFilled,be.pointer],n_=__name(()=>B.createElement(Y,{backgroundColor:On.BADGE_BG,color:On.BADGE_FG},`${cv}TASTE${cv}`),"TasteBadge"),r_=["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"],s_=__name(()=>{const[e,t]=W(()=>Math.floor(Math.random()*r_.length));G(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*r_.length))},2e3);return()=>clearInterval(e)},[]);const n=r_[e];return B.createElement(Y,{color:Ln.YELLOW},n,"...")},"PulsingText"),o_=__name(e=>String(e).padStart(3," "),"padNum"),i_=__name(e=>t_[e%t_.length],"getSymbol"),a_=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${o_(t)} ↓${o_(n)} (↑↓ scroll)`,"buildStatusLine"),l_=__name(({insights:e})=>{const[t,n]=W(0),[r,s]=W(!0),o=e.length,i=o>10,a=Math.max(0,o-10);if(G(()=>{r&&i&&n(a)},[o,r,i,a]),Z((e,t)=>{if(i)return t.upArrow?(s(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&s(!0),t}))}),0===o)return null;const l=e.slice(t,t+10),u=t,d=o-t-10;return B.createElement(K,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&B.createElement(Y,{dimColor:!0},a_(o,u,d,r)),l.map((e,n)=>{const r=t+n;return B.createElement(K,{key:r,marginBottom:0},B.createElement(Y,{dimColor:!0},i_(r)," ",e))}))},"ScrollableInsights"),c_=__name(({label:e,message:t,active:n,complete:r,items:s,insights:o,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return B.createElement(K,{flexDirection:"column",marginBottom:0},B.createElement(n_,null),B.createElement(K,{marginTop:0},B.createElement(Y,{dimColor:!0},"⎿"),B.createElement(K,{marginLeft:2},a?B.createElement(Y,{color:On.TEXT},"learned your coding taste"):B.createElement(s_,null))));const u=__name(()=>{const[e,t]=W(!0);return G(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),B.createElement(Y,{color:Ln.YELLOW},e?be.circleFilled:be.circle)},"PulsingDot"),d=__name(()=>r?B.createElement(Y,{color:On.TEXT},be.nodejs):n?B.createElement(u,null):B.createElement(Y,{dimColor:!0},be.circle),"getStatusIcon"),m=s.length>0||o.length>0||t||l&&l.learningCount>0;return!r||n||m?B.createElement(K,{flexDirection:"column",marginBottom:0},(n||r)&&B.createElement(K,{marginBottom:0},B.createElement(K,{marginRight:1},d()),B.createElement(Y,{color:r?Ln.WHITE:n?Ln.YELLOW:Ln.DIM},e)),r&&t&&(!l||0===l.learningCount)&&B.createElement(K,{marginLeft:3,marginBottom:0},B.createElement(Y,{dimColor:!0},t)),s.length>0&&B.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},s.map((e,t)=>B.createElement(Y,{key:t,dimColor:!0},`${be.bullet} ${e}`))),o.length>0&&B.createElement(l_,{insights:o}),r&&l&&l.learningCount>0&&B.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},B.createElement(K,{marginBottom:1,flexDirection:"row"},B.createElement(Y,null,"⎿"),B.createElement(K,{marginLeft:2},B.createElement(Y,{color:On.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),B.createElement(K,{flexDirection:"column",marginLeft:1},B.createElement(Y,{dimColor:!0},be.pointerSmall," Stored in"," ",l.storage),B.createElement(Y,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),u_=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return B.createElement(K,{flexDirection:"column",marginBottom:1},e.map((e,n)=>B.createElement(K,{key:e.id,marginLeft:0===n?0:3},B.createElement(c_,{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"),d_=__name(({steps:e})=>B.createElement(u_,{steps:e}),"ProgressSection");Nt();var m_=__name(({isImporting:e=!1,waitingForInput:t=!1})=>B.createElement(B.Fragment,null,e&&B.createElement(K,{marginTop:1},B.createElement(Y,{dimColor:!0},"ESC to cancel")),t&&B.createElement(K,{marginTop:1},B.createElement(Y,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Nt();var p_=[{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"}}],g_=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:s}=zk(p_),{isImporting:o,waitingForInput:i,error:a}=Qk(t);return Gk({onEscape:e,onEnter:__name(()=>{i&&(a&&n?n():e())},"onEnter"),enabled:o||i}),B.createElement(K,{flexDirection:"column",padding:1},s&&B.createElement(e_,{error:s}),!s&&B.createElement(d_,{steps:r}),B.createElement(m_,{isImporting:o,waitingForInput:i}))},"ImportProgress"),h_=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:s,onErrorDismiss:o,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?B.createElement(Zk,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?B.createElement(g_,{onComplete:r,onError:s,onErrorDismiss:o}):null,"OnboardingStepRenderer"),f_=__name(({onComplete:e,autoLearn:t=!1})=>{G(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:s}=Hk({autoLearn:t,onShouldSkip:e}),{step:o,setStep:i}=Kk({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=Vk({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${o}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),s?null:r?B.createElement(Yk,{error:r}):"done"===o?null:B.createElement(h_,{step:o,conditions:n,onImportStart:a,onImportComplete:l,onImportError:u,onErrorDismiss:d,onSkip:m})},"TasteOnboarding");function getEntryCharCount(e){return("input"in e?e.input??"":"").length+("output"in e?e.output??"":"").length+("command"in e?e.command??"":"").length}function getBudgetedFeed(e,t){if(0===e.length)return[];const n=[...e].reverse();let r=t;const s=[];for(const e of n)if(s.unshift(e),r-=getEntryCharCount(e),r<=0)break;return s}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var y_=U(__name(function MainView2({feed:e,liveAgents:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:s,transcriptMode:o,tasteOnboardingEntryId:i,autoLearnTaste:a,retryAttempt:l,input:u,setInput:d,fileSearchQuery:m,setFileSearchQuery:p,showFileList:g,setShowFileList:h,showProviderSelector:f,showModelSelector:y,showMemorySelector:w,showMcpManager:S,showAgentsConfig:b,showRewindSelector:E,showLoginOverlay:C,showAddDirModal:v,authComponentInfo:T,status:k,currentProvider:_,currentModel:P,showProviderNotification:A,shareInfo:x,showShareNotification:I,unshareNotificationMessage:N,updateStatus:R,updateFailedInfo:$,permissionMode:L,hintMessage:M,pendingExitKey:O,tasteLearningEnabled:D,interactionTokens:q,contextUsage:F,historyManagerRef:j,executionState:z,contextEngineRef:U,onSubmit:W,onCommand:Q,onToggleAutoAccept:G,onResetPendingExitKey:J,onDoubleEscapeEmpty:X,onTasteOnboardingComplete:Z,permissionPanel:ee,questionPanel:te,onRewindSelect:ne,onRewindCancel:re,onLoginComplete:se,onLoginCancel:oe,setShowProviderSelector:ie,setShowModelSelector:ae,setShowMemorySelector:le,setShowMcpManager:ce,setShowAgentsConfig:ue,setShowAddDirModal:de,handleProviderSelect:me,handleProviderCancel:pe,handleModelSelect:ge,handleModelCancel:he,handleAuthSuccess:fe,handleAuthCancel:ye}){const we=H(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Se=useTerminalWidth(),{placeholder:be,isPrediction:Ee,onAccepted:Ce}=usePredictedPlaceholder({contextEngineRef:U,isCmdCodeBusy:r}),ve=H(()=>"off"===o?we:getBudgetedFeed(we,"limited"===o?15e3:5e4),[we,o]),Te=H(()=>"off"===o?0:Math.max(0,we.length-ve.length),[we.length,ve.length,o]),ke=H(()=>0===Te?ve:ve.filter(e=>"user"!==e.role),[ve,Te]),_e=V(()=>ue(!1),[ue]),Pe=V(()=>le(!1),[le]),Ae=V(()=>ce(!1),[ce]),xe=V(()=>de(!1),[de]),Ie=V(()=>ae(!0),[ae]),Ne=!("off"!==o||ee||te||f||y||T||w||S||b||E||C||v||i);return B.createElement(K,{flexDirection:"column",width:"100%"},B.createElement(Lk,{staticKey:s,feed:ke,showHeader:!0,expandedToolOutput:"off"!==o,currentModel:P,hiddenCount:Te}),i&&B.createElement(f_,{onComplete:Z,autoLearn:a}),t.map(e=>B.createElement(Ok,{key:e.id,entry:e})),B.createElement(RetryMessage,{attempt:l}),te,ee,"off"!==o&&B.createElement(K,{flexDirection:"column",marginTop:1},B.createElement(K,null,B.createElement(Y,{dimColor:!0},"─".repeat(Se))),B.createElement(K,{paddingRight:1},B.createElement(Y,{backgroundColor:jn.BG,color:jn.FG,bold:!0},`${cv}DETAILED TRANSCRIPT${cv}`),B.createElement(Y,{dimColor:!0}," · "),B.createElement(Y,{bold:!0},"ctrl+o"),B.createElement(Y,{dimColor:!0}," to toggle"),B.createElement(Y,{dimColor:!0}," · "),B.createElement(Y,{bold:!0},"ctrl+e"),B.createElement(Y,{dimColor:!0}," ","to"," ","limited"===o?"show all":"collapse"))),Ne&&B.createElement(wk,{queuedMessages:n,isProcessing:r,executionState:z,status:k,input:u,setInput:d,onSubmit:W,showFileList:g,setShowFileList:h,fileSearchQuery:m,setFileSearchQuery:p,onCommand:Q,outputTokens:q,contextUsage:F,tasteLearning:D,shareInfo:x,showShareNotification:I,unshareNotificationMessage:N,updateStatus:R,updateFailedInfo:$,currentProvider:_,showProviderInfo:A,permissionMode:L,onToggleAutoAccept:G,hintMessage:M,historyManager:j.current,pendingExitKey:O,onResetPendingExitKey:J,onDoubleEscapeEmpty:X,retryAttempt:l,onAltP:Ie,placeholder:be,isPlaceholderPrediction:Ee,onPlaceholderAccepted:Ce}),f&&B.createElement(K,{marginY:1},B.createElement(qk,{onSelect:me,onCancel:pe,currentProvider:_})),y&&B.createElement(K,{marginY:1},B.createElement(Dk,{onSelect:ge,onCancel:he,currentModel:P})),b&&B.createElement(K,{marginY:1},B.createElement(jT,{onCancel:_e})),w&&B.createElement(K,{marginY:1},B.createElement(Ek,{onClose:Pe})),S&&B.createElement(K,{marginY:1},B.createElement(bk,{onClose:Ae})),E&&U.current&&B.createElement(K,{marginY:1},B.createElement(jk,{checkpoints:U.current.listCheckpoints(),onSelect:ne,onCancel:re})),T&&B.createElement(K,{marginY:1},B.createElement(T.Component,{onSuccess:fe,onCancel:ye})),C&&B.createElement(K,{marginY:1},B.createElement(Sk,{onComplete:se,onCancel:oe})),v&&B.createElement(K,{marginY:1},B.createElement(TT,{onClose:xe})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,onboarding:o,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:p,onSubmit:g,onCommand:h,input:f,setInput:y,fileSearchQuery:w,setFileSearchQuery:S,updateFailedInfo:b,handleTrust:E,handleNoTrust:C,handleToggleAutoAccept:v,handleDoubleEscapeEmpty:T,handleTasteOnboardingComplete:k,loadTasteStatus:_}){if(i.shouldExit)return null;if(o.checkingProject)return null;if(o.showTrustPrompt)return B.createElement(sT,{staticKey:s.staticKey,onTrust:E,onExit:C});if(s.showSessionSelector)return B.createElement(iT,{onSelectSession:p.onSelectSession,onNewSession:p.onNewSession});if(!o.projectTrusted)return null;const P=a.pendingQuestion?B.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:s.setStaticKey}):null,A=a.pendingPermission?B.createElement(fT,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:v}):null;return s.showLearningFeed?B.createElement(LearningView,{setShowLearningFeed:s.setShowLearningFeed,setStaticKey:s.setStaticKey,onExit:()=>i.setShouldExit(!0)}):s.showTasteConfig?B.createElement(TasteConfigView,{staticKey:s.staticKey,setShowTasteConfig:s.setShowTasteConfig,loadTasteStatus:_}):s.showSkillsConfig?B.createElement(SkillsConfigView,{staticKey:s.staticKey,setShowSkillsConfig:s.setShowSkillsConfig}):B.createElement(y_,{feed:e.feed,liveAgents:e.liveAgents,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:s.staticKey,transcriptMode:s.transcriptMode,tasteOnboardingEntryId:o.tasteOnboardingEntryId,autoLearnTaste:o.autoLearnTaste,retryAttempt:n.retryAttempt,input:f,setInput:y,fileSearchQuery:w,setFileSearchQuery:S,showFileList:s.showFileList,setShowFileList:s.setShowFileList,showProviderSelector:s.showProviderSelector,showModelSelector:s.showModelSelector,showMemorySelector:s.showMemorySelector,showMcpManager:s.showMcpManager,showAgentsConfig:s.showAgentsConfig,showRewindSelector:s.showRewindSelector,showLoginOverlay:s.showLoginOverlay,showAddDirModal:s.showAddDirModal,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:b,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:g,onCommand:h,onToggleAutoAccept:v,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:T,onTasteOnboardingComplete:k,permissionPanel:A,questionPanel:P,onRewindSelect:p.onRewindSelect,onRewindCancel:p.onRewindCancel,onLoginComplete:p.onLoginComplete,onLoginCancel:p.onLoginCancel,setShowProviderSelector:s.setShowProviderSelector,setShowModelSelector:s.setShowModelSelector,setShowMemorySelector:s.setShowMemorySelector,setShowMcpManager:s.setShowMcpManager,setShowAgentsConfig:s.setShowAgentsConfig,setShowRewindSelector:s.setShowRewindSelector,setShowLoginOverlay:s.setShowLoginOverlay,setShowAddDirModal:s.setShowAddDirModal,handleProviderSelect:p.handleProviderSelect,handleProviderCancel:p.handleProviderCancel,handleModelSelect:p.handleModelSelect,handleModelCancel:p.handleModelCancel,handleAuthSuccess:p.handleAuthSuccess,handleAuthCancel:p.handleAuthCancel})}__name(renderView,"renderView");var w_=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:s,updateFailedInfo:o,initialPrompt:i,skipOnboarding:a=!1,initialPermissionMode:l})=>{const{exit:u}=te(),{stdout:d}=X(),[m,p]=W(""),[g,h]=W(""),f=Q(!1),y=Q(!1),w=Q(null),S=Q(null),b=useUiOverlays(),E=useFeed(),C=useSession(),v=useStatus(s),T=useAuth(),k=usePendingOps(),_=useOnboarding(),P=useExit(),{executeBash:A,executionState:x}=tv(),I=usePermissionMode({initialPermissionMode:l,dangerouslySkipPermissions:r,setPendingPermission:k.setPendingPermission,setStatus:v.setStatus,contextEngineRef:S}),{createContextEngineCallbacks:N}=useContextEngine({sessionId:C.sessionId,sessionLoaded:C.sessionLoaded,showSessionSelector:b.showSessionSelector,projectTrusted:_.projectTrusted,setFeed:E.setFeed,setLiveAgents:E.setLiveAgents,setQueuedMessages:E.setQueuedMessages,queuedMessagesRef:E.queuedMessagesRef,setStatus:v.setStatus,pinnedStatusRef:v.pinnedStatusRef,setRetryAttempt:v.setRetryAttempt,setInteractionTokens:v.setInteractionTokens,setContextUsage:v.setContextUsage,setCurrentProvider:T.setCurrentProvider,shareInfoRef:v.shareInfoRef,permissionsService:I.permissionsService,permissionModeRef:I.permissionModeRef,setPendingQuestion:k.setPendingQuestion,contextEngineRef:S}),{loadTasteStatus:R,loadCurrentProvider:$,onSubmit:L}=useStartup({resume:e,continueLatest:t,trust:n,initialPrompt:i,stdout:d,feedState:E,sessionState:C,statusState:v,authState:T,onboarding:_,uiOverlays:b,permissionState:I,contextEngineRef:S,isSubmittingRef:f,initialPromptSubmittedRef:y,historyManagerRef:w,executeBash:A,createContextEngineCallbacks:N,setInput:p});useLifecycle({exit:u,feedState:E,exitState:P,statusState:v,authState:T,onboarding:_,uiOverlays:b,skipOnboarding:a});const{handleToggleAutoAccept:M,handleDoubleEscapeEmpty:O,handleTasteOnboardingComplete:D,handleTrust:q,handleNoTrust:F}=useHandlers({resume:e,feedState:E,onboarding:_,uiOverlays:b,exitState:P,pendingOps:k,permissionState:I,statusState:v,authState:T,contextEngineRef:S,loadTasteStatus:R,loadCurrentProvider:$,setInput:__name(e=>p(e),"setInput")}),{onCommand:j}=useCommandCtx({feedState:E,sessionState:C,statusState:v,uiOverlays:b,onboarding:_,exitState:P,permissionState:I,contextEngineRef:S,isSubmittingRef:f,executeBash:A,createContextEngineCallbacks:N,setInput:p});return renderView({feedState:E,sessionState:C,statusState:v,authState:T,uiOverlays:b,onboarding:_,exitState:P,pendingOps:k,permissionState:I,contextEngineRef:S,historyManagerRef:w,executionState:x,actionCallbacks:useMainActionCallbacks({feedState:E,sessionState:C,statusState:v,authState:T,uiOverlays:b,permissionState:I,contextEngineRef:S,createContextEngineCallbacks:N,setInput:p}),onSubmit:L,onCommand:j,input:m,setInput:p,fileSearchQuery:g,setFileSearchQuery:h,updateFailedInfo:o,handleTrust:q,handleNoTrust:F,handleToggleAutoAccept:M,handleDoubleEscapeEmpty:O,handleTasteOnboardingComplete:D,loadTasteStatus:R})},"InteractiveCLI");Nn(),Sn(),CE();var S_=__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"),b_=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),E_=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),C_=__name(({options:e})=>{let t;return e.permissionMode?t=e.permissionMode:e.plan&&(t="plan"),{resume:e.resume,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:t}},"buildInteractiveCLIProps"),v_=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),T_=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),k_=__name(()=>{T_()},"initializeTerminal"),__=__name(async(e={})=>{const t=S_(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),k_(),b_(e)){const e=await Yb.isProjectInitialized(),t=e?await Yb.listSessions():[],n=E_({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=C_({options:e}),r=v_();ee(B.createElement(w_,{...n}),r)},"interactiveMode");Nt(),Es(),bE(),ts(),Ot(),Gs(),dn(),nr(),ar(),en(),qE(),SC(),gi(),JE(),CE(),hi();var P_=null,A_=!1,x_=new Set([Is.EDIT_FILE,Is.WRITE_FILE,Is.SHELL_COMMAND]);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(A_)return;A_=!0;const e=__name(e=>{P_?.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(),P_=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));try{const n=await processQuery({query:t,signal:P_.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 ii&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof ai&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof di&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof si&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof mi&&(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 I_=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===Ct.ANTHROPIC&&(r=await on.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const s=getEnvironmentContext(),o=await getMemoryContent([]),i=await getTasteContent(),a=generateSkillsXML(await loadAllSkillSummaries())||null,l=crypto.randomUUID(),u=await isTasteLearningEnabled(),d={[wt.PROJECT_SLUG]:Yb.getCurrentProjectDirName(),[wt.TASTE_LEARNING]:u.toString(),[wt.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(d[wt.OAUTH_TOKEN]=`Bearer ${r}`),{tools:e,config:s,memory:o,taste:i,skills:a,headers:d,sessionId:l}}async function callApi(e,t,n,r){const s={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:`anthropic:${getConfiguredModel()}`},o={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:s,threadId:t.sessionId},i=await e.post({body:o,stream:!0,endpoint:St.ALPHA.GENERATE,headers:t.headers,signal:r});return je.fromReadableStream(i).finalMessage()}async function executeToolCall(e,t,n){if(x_.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 ii||t instanceof ai||t instanceof di||t instanceof si||t instanceof mi)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,s=getApiBaseUrl(),o=new Vb({baseUrl:s}),i=[{role:"user",content:t}],a=await setupConversationContext();let l=0,u="";for(;l<I_;){if(l++,n.aborted)throw new Error("Cancelled");const e=await callApi(o,a,i,n),t=e.content.filter(e=>"text"===e.type),s=e.content.filter(e=>"tool_use"===e.type),d=t.map(e=>e.text).join("");if(d&&(u+=d),0===s.length)break;const m=[];for(const e of s){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);m.push(t)}i.push({role:"assistant",content:e.content}),i.push({role:"user",content:m})}return l>=I_&&process.stderr.write(`Warning: Reached maximum conversation turns (${I_}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),u}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery"),zt();var N_=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),R_=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),$_=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),e.plan&&(t.plan=!0),e.permissionMode&&(t.permissionMode=e.permissionMode),t},"buildRuntimeOptions"),L_=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),M_=__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=M_(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=N_(e);await R_();const r=$_(t),s=L_({options:t,runtimeOptions:r,initialPrompt:n});__(s)}__name(interactiveModeAction,"interactiveModeAction"),Nt(),$n(),Vr(),globalThis.COMMAND_CODE_CWD=process.cwd();var O_=__name(()=>process.cwd(),"getCwd"),D_=__name(()=>process.argv.slice(2),"getArgs"),q_=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),F_=__name(()=>{const e=O_(),t=D_(),n=q_(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){F_(),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"),Nt(),Ot(),$n(),yr(),ir();var j_=getPackageJson(),z_=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=j_.version,t=getInvokedCommandName(),n=Ak.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(Be.bold("Command Code")+Be.gray(` v${e}`)),console.log(Be.gray(Tk)),console.log(),console.log(Be.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(Be.bold("Options"));for(const e of Pk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(kk)+Be.gray(e.description))}console.log(),console.log(Be.bold("Commands"));for(const e of xk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(kk)+Be.gray(e.description))}console.log(),console.log(Be.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(kk)+Be.gray(e.description));console.log(),console.log(Be.bold("Keyboard Shortcuts"));for(const e of _k)console.log(" "+e.key.padEnd(kk)+Be.gray(e.description));console.log(),console.log(Be.bold("Examples"));for(const e of Nk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(kk)+Be.gray(e.description))}console.log(),console.log(Be.cyan("❯")+" "+Be.gray(Rk.replace(/cmd/,t))),console.log(),console.log(Be.bold("Links"));for(const e of Ik)console.log(" "+e.key.padEnd(kk)+Be.cyan(e.description));console.log()}function createProgram(){const e=new Ae;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(j_.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("--plan","Start in plan mode (read-only exploration and planning)").addOption(new xe("--permission-mode <mode>","Set permission mode").choices(["standard","plan","auto-accept"])).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",z_,[]).addOption(new xe(ft).hideHelp()).addOption(new xe(yt).hideHelp()).addOption(new xe("-d, --debug","Enable debug mode").hideHelp()).addOption(new xe("--local","Use local server").hideHelp()).addOption(new xe("--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 s=t.opts(),o=Object.entries(s).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");o&&dlog(`[cmd] options: ${o}`);const i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Nt(),Vr(),Jr(),AC();var B_=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=h.platform(),n=h.arch();let r,s,o,i;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,s=e.user?.id,o=e.org?.login,i=e.org?.id)}catch{}if(!s)try{const e=await loadCredentials();s=e?.userId}catch{}systemInfo({userName:r,userId:s,orgLogin:o,orgId:i,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(){B_||(B_=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Ie("Opening GitHub issues...").start();try{await ie(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"),Qs(),Nt(),__name(openGitHubIssue,"openGitHubIssue");var U_=new Ae("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Nt();var W_=new Ae("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const{waitUntilExit:t}=ee(B.createElement(Qv,{verbose:e.verbose,text:e.text}));await t()}Nt(),Nt(),__name(runInfo,"runInfo");var Q_=new Ae("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=>{await runInfo(e)});function runLearnTaste(){const{unmount:e}=ee(B.createElement(g_,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}Nt(),Ot(),Nt(),__name(runLearnTaste,"runLearnTaste"),$n(),Vr();var G_=new Ae(Tt.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:Br.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 addMcpCommand(){const e=new Ae("add");return e.description("Add an MCP server").argument("<name>","Server name (unique identifier)").argument("[url]","Server URL (required for http transport)").option("-t, --transport <type>","Transport type (stdio or http)","stdio").addOption(new xe("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("-e, --env <KEY=value>","Environment variable (repeatable)",collectKeyValue,{}).option("-H, --header <header>","HTTP header (repeatable, http only)",collectHeaders,{}).allowUnknownOption().allowExcessArguments().action(async(e,t,n,r)=>{const s=getInvokedCommandName();try{let o;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(Be.red(`Error: Invalid server name '${e}'`)),console.error(Be.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1)),"stdio"!==n.transport&&"http"!==n.transport&&(console.error(Be.red(`Error: Invalid transport type '${n.transport}'`)),console.error(Be.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(Be.red("Error: URL is required for http transport")),console.error(Be.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(Be.red(`Error: Invalid URL '${t}'`)),process.exit(1)}o={transport:"http",enabled:!0,url:t,...Object.keys(n.header).length>0&&{headers:n.header},...Object.keys(n.env).length>0&&{env:n.env}},console.log(Be.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(Be.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(Be.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(Be.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${no}/callback`]});e&&(n=e.clientId,t=e.clientSecret)}o.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},console.log(Be.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(Be.gray(` ${e}`))},"onStatus")});s.success?console.log(Be.green("✓ Successfully authenticated")):(i=!0,console.log(Be.yellow(`Warning: Authentication failed: ${s.error}`)),console.log(Be.gray("You can retry with: cmd mcp auth "+e)),console.log(Be.gray("Or authenticate via the /mcp menu in a session")))}}else{const s=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(Be.red("Error: Command is required for stdio transport")),console.error(Be.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),a=e[0],l=e.slice(1)}else if(t){a=t;const n=s.indexOf(e);-1!==n&&s.length>n+2&&(l=s.slice(n+2))}else console.error(Be.red("Error: Command is required for stdio transport")),console.error(Be.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(Be.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);o={transport:"stdio",enabled:!0,command:a,...l.length>0&&{args:l},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:o,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(Be.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(Be.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===o.transport)console.log(Be.gray(` URL: ${o.url}`));else{const e=[o.command,...o.args||[]].join(" ");console.log(Be.gray(` Command: ${e}`))}console.log(""),console.log(Be.cyan("Next steps:")),console.log(Be.gray(`Start ${s} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function collectKeyValue(e,t){const[n,...r]=e.split("=");return n&&0!==r.length||(console.error(Be.red(`Error: Invalid format '${e}', expected KEY=value`)),process.exit(1)),t[n]=r.join("="),t}function collectHeaders(e,t){const n=e.indexOf(":");-1===n&&(console.error(Be.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),s=e.substring(n+1).trim();return r||(console.error(Be.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=s,t}function listMcpCommand(){const e=new Ae("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(Be.yellow("\nNo MCP servers configured\n")),console.log(Be.gray("Add a server with:")),console.log(Be.gray(" cmd mcp add --transport http <name> <url>")),console.log(Be.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(Be.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(Be.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(Be.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const s of e){const e=s.config.enabled?Be.green("enabled"):Be.gray("disabled");let o;o=s.config.oauth?await hasTokens(s.name)?Be.green(be.tick):Be.red(be.cross):s.config.headers||s.config.env?Be.green(be.tick):Be.gray("-"),console.log(` ${Be.white(s.name.padEnd(t))} ${Be.cyan(s.config.transport.padEnd(n))} ${Be.gray(s.scope.padEnd(r))} ${o} ${e}`)}console.log(Be.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new Ae("get");return e.description("Show details for an MCP server").argument("<name>","Server name").action(async e=>{try{const t=await getMcpServer({name:e});t||(console.error(Be.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(Be.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${Be.dim("Scope:")} ${r}`),console.log(` ${Be.dim("Transport:")} ${n.transport}`),console.log(` ${Be.dim("Status:")} ${n.enabled?Be.green("enabled"):Be.gray("disabled")}`),"http"===n.transport){if(console.log(` ${Be.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${Be.dim("Headers:")}`);for(const[e,t]of Object.entries(n.headers)){const n=e.toLowerCase().includes("auth")||e.toLowerCase().includes("token")||e.toLowerCase().includes("key")?"***":t;console.log(` ${e}: ${n}`)}}}else console.log(` ${Be.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${Be.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${Be.dim("Environment:")}`);for(const[e,t]of Object.entries(n.env)){const n=e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token")||e.toLowerCase().includes("password")?"***":t;console.log(` ${e}=${n}`)}}console.log("")}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Ae("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new xe("-s, --scope <scope>","Scope to remove from (auto-detects if not specified)").choices(["local","project","user"])).action(async(e,t)=>{try{const n=await getMcpServer({name:e});n||(console.error(Be.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(Be.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(Be.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const s="user"===r?"global":"project"===r?"project":"local";console.log(Be.green(`✓ Removed MCP server '${e}' from ${s} config`))}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new Ae("add-json");return e.description("Add an MCP server from JSON configuration").argument("<name>","Server name (unique identifier)").argument("<json>","Server configuration as JSON string").addOption(new xe("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("--client-secret <secret>","OAuth client secret (injected into oauth config)").action(async(e,t,n)=>{const r=getInvokedCommandName();try{let s,o;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(Be.red(`Error: Invalid server name '${e}'`)),console.error(Be.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{s=JSON.parse(t)}catch{console.error(Be.red("Error: Invalid JSON")),console.error(Be.gray("Make sure to quote the JSON string properly")),console.error(Be.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}s&&"object"==typeof s&&"type"in s&&!("transport"in s)&&(s.transport=s.type,delete s.type),s?.oauth?.callbackPort&&(o=s.oauth.callbackPort,delete s.oauth.callbackPort),n.clientSecret&&s?.oauth&&(s.oauth.clientSecret=n.clientSecret);const i=js.safeParse(s);if(!i.success){console.error(Be.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(Be.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(Be.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(Be.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(Be.cyan("Starting OAuth authentication...")),console.log(Be.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:a.oauth.authorizationUrl,tokenUrl:a.oauth.tokenUrl,clientId:a.oauth.clientId,clientSecret:a.oauth.clientSecret,scopes:a.oauth.scopes},n=await performOAuthFlow(e,t,{...o&&{port:o},onStatus:__name(e=>{console.log(Be.gray(` ${e}`))},"onStatus")});n.success?console.log(Be.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(Be.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(Be.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(Be.gray("Or authenticate via the /mcp menu in a session")))}const u="user"===n.scope?"global":"project"===n.scope?"project":"local";if(l?console.log(Be.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(Be.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(Be.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(Be.gray(` Command: ${e}`))}console.log(""),console.log(Be.cyan("Next steps:")),console.log(Be.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new Ae("auth");return e.description("Manage OAuth authentication for MCP servers").argument("[server]","Server name to authenticate").option("--status","Check authentication status").option("--clear","Clear stored authentication").option("--list","List servers with stored authentication").action(async(e,t)=>{const n=getInvokedCommandName();try{if(t.list){const e=await listServersWithTokens();if(0===e.length)return void console.log(Be.yellow("No servers with stored authentication."));console.log(Be.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?Be.yellow("expired"):Be.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(Be.red("Error: Server name is required")),console.error(Be.gray(`Usage: ${n} mcp auth <server>`)),console.error(Be.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(Be.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(Be.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(Be.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(Be.gray(" A refresh token is available for re-authentication"));else{if(console.log(Be.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(Be.gray(` Expires in ${e} minutes`))}t.scope&&console.log(Be.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(Be.green(`✓ Cleared authentication for '${e}'`)):console.log(Be.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(Be.red(`Error: MCP server '${e}' not found`)),console.error(Be.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(Be.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(Be.gray(`Add OAuth config using "${n} mcp add-json" with oauth field`)),process.exit(1));const s={authorizationUrl:r.config.oauth.authorizationUrl,tokenUrl:r.config.oauth.tokenUrl,clientId:r.config.oauth.clientId,clientSecret:r.config.oauth.clientSecret,scopes:r.config.oauth.scopes};console.log(Be.cyan(`Authenticating with '${e}'...`)),console.log(Be.gray("A browser window will open for authentication.\n"));const o=await performOAuthFlow(e,s,{onStatus:__name(e=>{console.log(Be.gray(` ${e}`))},"onStatus")});if(o.success)return console.log(Be.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(Be.gray("Restart the session to connect with the authenticated server."));console.error(Be.red(`\nError: Authentication failed: ${o.error}`)),console.log(Be.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(Be.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Ae("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(h.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${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")}Nt(),Nt(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Nt(),__name(listMcpCommand,"listMcpCommand"),Nt(),__name(getMcpCommand,"getMcpCommand"),Nt(),__name(removeMcpCommand,"removeMcpCommand"),Nt(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Nt(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Nt(),Ot(),Nt(),Nt(),fC(),Nt(),Ot(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Nt(),Nt();var H_=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||H_.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const s=n[r].trim();return{endIdx:t+r,inclusive:H_.test(s)&&!s.startsWith("#")&&!s.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:s}=findLookaheadEnd(e,t),o=s?r+1:r;return{combined:[n,...e.slice(t,o).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:o}}function processRawLine(e,t){const n=e[t],r=t+1,s=n.trim();if(!s.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(H_.test(s))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:o,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:o,originalLineNum:r},nextIdx:i}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:s}=processRawLine(e,n);t.push(r),n=s}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],s=t.substring(1).trim();if(!H_.test(s))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 o=Array.from(s.matchAll(/confidence:\s*(\S+)/gi)),i=o.length>0?o[o.length-1]:null;if(!i)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 a=i[1],l=parseFloat(a);if(isNaN(l))return r.push({line:n,severity:"error",message:`Confidence value "${a}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==i.index?s.substring(0,i.index).trim():s.trim();return u&&0!==u.length?(u.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(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 hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=t.slice(n+1,n+4),s=r.findIndex(e=>e.trim().startsWith("# "));return(-1===s?r:r.slice(0,s)).some(e=>e.includes("See [")&&e.includes("taste.md"))}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),s=t.filter(e=>"warning"===e.severity),o=0===r.length;if(0===t.length)return{valid:o,issues:[...t],summary:`${be.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),s.length>0&&i.push(`${s.length} warning${s.length>1?"s":""}`);const a=r.length>0?be.cross:be.warning;return{valid:o,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?Be.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(Be.dim(` → ${e.suggestion}`)),n}function formatIssueGroup(e,t,n){return 0===e.length?[]:[n,...e.flatMap(e=>formatSingleIssue(e,t)),""]}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`${Be.green(e)} ${Be.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),s=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?Be.red(t.summary):Be.yellow(t.summary),"",...formatIssueGroup(r,Be.red,Be.bold(Be.red("Errors:"))),...formatIssueGroup(s,Be.yellow,Be.bold(Be.yellow("Warnings:")))].join("\n").trim()}__name(findLookaheadEnd,"findLookaheadEnd"),__name(joinMultiLineLearning,"joinMultiLineLearning"),__name(processRawLine,"processRawLine"),__name(preprocessLines,"preprocessLines"),__name(validateLearningLine,"validateLearningLine"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(buildResult,"buildResult"),Nt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var V_=new Set(["# Taste (Continuously Learned by [CommandCode][cmd])","# Taste (Continuously Learned by CommandCode.ai)","# Taste (Continuously Learned by CommandCode)"]);function warnIfEmptyCategory(e,t){!e.currentCategory||e.learningsInCurrentCategory>0||hasReferenceAfterCategory({lines:t,categoryLineIndex:e.categoryLineNumber-1})||e.issues.push({line:e.categoryLineNumber,severity:"warning",message:`Category '${e.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function processHeading(e){const{line:t,lineNum:n,state:r,rawLines:s}=e;V_.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,s),r.currentCategory=t.trim().substring(2).trim(),r.categoryLineNumber=n,r.learningsInCurrentCategory=0)}function processLearning(e){const{line:t,lineNum:n,state:r}=e;r.currentCategory?(r.learningsInCurrentCategory++,r.issues.push(...validateLearningLine({line:t.trim(),lineNum:n}))):r.issues.push({line:n,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'})}__name(warnIfEmptyCategory,"warnIfEmptyCategory"),__name(processHeading,"processHeading"),__name(processLearning,"processLearning");var K_=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,Y_=/^\[cmd\]: https:\/\/commandcode\.ai\/$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:s}=e,o=t.trim();o&&(o.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:s}):o.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):K_.test(o)||Y_.test(o)||r.issues.push({line:n,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"}))}function checkFinalCategory(e){const{state:t,rawLines:n}=e;!t.currentCategory||t.learningsInCurrentCategory>0||!t.categoryLineNumber||hasReferenceAfterCategory({lines:n,categoryLineIndex:t.categoryLineNumber-1})||t.issues.push({line:t.categoryLineNumber,severity:"warning",message:`Category '${t.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}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 s=t.split("\n"),o=preprocessLines(s),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of o)processLine({line:e,lineNum:t,state:i,rawLines:s});return checkFinalCategory({state:i,rawLines:s}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var J_=__name(e=>"local-global"===e?"global":"project","locationLabel"),X_=__name(({file:e,error:t})=>({success:!1,filesLinted:[],errors:[{file:e,error:t}],totalErrors:0,totalWarnings:0}),"failResult");function resolvePackageFile(e,t){const n=getCategoryTasteFile({target:t,category:e});return E(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${J_(t)}`}}}function collectSpecificFiles(e){const{packages:t,target:n}=e,r=t.map(e=>resolvePackageFile(e,n));return{files:r.filter(e=>"result"in e).map(e=>e.result),errors:r.filter(e=>"error"in e).map(e=>e.error)}}async function collectAllFiles(e){const{tastePath:t,target:n}=e,r=[],s=getRootTasteFile({target:n});E(s)&&r.push({path:s,displayName:"taste.md"});const o=(await $.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>E(e)).map(({entry:e,categoryFile:t})=>({path:t,displayName:`${e.name}/taste.md`}));return r.push(...o),r}async function lintFile(e){let t=await $.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await $.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),s=r.issues.filter(e=>"error"===e.severity).length,o=r.issues.filter(e=>"warning"===e.severity).length,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:s,warnings:o,formatted:i}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:s}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&s.length>0)return{success:!1,filesLinted:[],errors:s,totalErrors:0,totalWarnings:0};if(0===r.length)return X_({file:"all",error:`No taste files found in ${J_(n)}`});const o=await Promise.all(r.map(lintFile)),i=o.reduce((e,t)=>e+t.errors,0),a=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid)&&0===s.length,filesLinted:o,errors:s,totalErrors:i,totalWarnings:a}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return X_({file:"all",error:`No taste files found in ${J_(n)}`});const s=await Promise.all(r.map(lintFile)),o=s.reduce((e,t)=>e+t.errors,0),i=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid),filesLinted:s,errors:[],totalErrors:o,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return E(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):X_({file:"all",error:`No taste directory found in ${J_(n)}`})}function resolveConflictStrategy(e){const t=[e.skip&&"skip",e.merge&&"merge",e.overwrite&&"overwrite"].filter(Boolean);return t.length>1&&exitWithError(`Cannot combine --${t[0]} and --${t[1]}. Choose one conflict strategy.`),t[0]}__name(resolvePackageFile,"resolvePackageFile"),__name(collectSpecificFiles,"collectSpecificFiles"),__name(collectAllFiles,"collectAllFiles"),__name(lintFile,"lintFile"),__name(lintSpecificPackages,"lintSpecificPackages"),__name(lintAllFiles,"lintAllFiles"),__name(lint,"lint"),Nt(),Vr(),__name(resolveConflictStrategy,"resolveConflictStrategy");var Z_=Be.bgGreen.black.bold(" TASTE ");function shortenPath(e){const t=process.env.HOME??process.env.USERPROFILE??"";return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function exitWithError(e){console.error(`${Be.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`),process.exit(1)}function formatUsageLine(e){const t=e.match(/^(\s*(?:Usage:|or:)?\s*)(cmd)(\s+.+?)(\s+\(.*\))?$/);return t?`${Be.dim(t[1])}${Be.green(t[2])}${Be.white(t[3]??"")}${t[4]?Be.dim(t[4]):""}`:Be.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${Be.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`);for(const e of t)console.error(formatUsageLine(e));process.exit(1)}function resolveRemoteDefault(e){return e.global||e.remote?e:{...e,remote:!0}}__name(shortenPath,"shortenPath"),__name(exitWithError,"exitWithError"),__name(formatUsageLine,"formatUsageLine"),__name(exitWithUsage,"exitWithUsage"),__name(resolveRemoteDefault,"resolveRemoteDefault");var eP=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return ot(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:eP})}function getProfileLink(e){return ot(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:eP})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return st(e,n,{trim:!1})}function formatMergeParts(e){const t=[];return e.added>0&&t.push(`${e.added} ${1===e.added?"learning":"learnings"} added`),e.updated>0&&t.push(`${e.updated} ${1===e.updated?"learning":"learnings"} updated`),e.unchanged>0&&t.push(`${e.unchanged} ${1===e.unchanged?"learning":"learnings"} unchanged`),t}function hasMergeConflictRisk(e){return(e.added>0||e.updated>0)&&e.unchanged>0}function hasMergeConflictRiskInRecord(e){return Object.values(e).some(hasMergeConflictRisk)}function logMergeReviewTip(){console.log(Be.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function parseOwnerPackage(e){if(!e.includes("/"))return;const[t,n]=e.split("/");return t&&n?{owner:t,packageName:n}:void 0}function handleResultErrors(e){for(const t of e){const e=t.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${t.pkg}' `);console.error(`${Be.red("Error:")} ${e}`)}process.exit(1)}function getTimeAgo(e){const t=Date.now()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),s=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`:`${s} day${s>1?"s":""} ago`}async function flushAndExit(e){await Promise.race([shutdownTelemetry(),new Promise(e=>setTimeout(e,500))]).catch(()=>{}),process.exit(e)}function withErrorHandler(e){return async(...t)=>{try{await e(...t),await flushAndExit(0)}catch(e){const t=e instanceof Error?e.message:String(e);console.error(Be.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new Ae("lint").argument("[package]","Taste package name").option("-g, --global","Validate taste packages from global storage (~/.commandcode)").option("--all","Validate all taste packages").description(`Validate taste package format ${Be.dim("(structure, style, etc.)")}`).action(withErrorHandler(async(e,t)=>runLint({packageName:e,options:t})))}function validateLintOptions({packageName:e,options:t}){e||t.all||exitWithUsage({message:"Specify a taste package name or use --all to validate everything",usage:["cmd taste lint <package> validate a taste package","cmd taste lint --all validate all taste packages"]}),e&&t.all&&exitWithError("Use either a package name or --all, not both")}function logLintResults(e){for(const t of e.filesLinted)console.log(t.formatted);e.filesLinted.length>1&&logLintSummary(e),e.success||process.exit(1)}function logLintSummary({filesLinted:e,totalErrors:t,totalWarnings:n}){if(console.log(""),0===t&&0===n)return void console.log(`${Be.green(be.tick)} All ${Be.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(Be.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(Be.yellow(`${n} warning${n>1?"s":""}`)),console.log(`Summary: ${r.join(", ")} across ${e.length} files`)}async function runLint({packageName:e,options:t}){console.log(""),validateLintOptions({packageName:e,options:t});const n=await lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(Be.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),s=r[0].trim(),o=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===o.length?null:{category:normalizeCategory({category:s}),learnings:o,sourcePath:n}}function parsePackages(e){const{content:t,sourcePath:n}=e;return t.split(/^# /gm).filter(e=>e.trim()).filter(e=>!e.includes("See [")).map(e=>parseSection({section:e,sourcePath:n})).filter(e=>null!==e)}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 formatPackage(e){const{pkg: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}async function readAndMigrateFile(e){const{filePath:t}=e,n=await $.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await $.writeFile(t,r,"utf-8"),r)}function trimTrailingBlanks(e){const{lines:t,until:n}=e;let r=e.from;for(;r>n&&""===t[r].trim();)r--;return r}function findCategoryRange(e){const{lines:t,pattern:n}=e,r=t.findIndex(e=>n.test(e));if(-1===r)return null;const s=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===s)return{start:r,end:t.length-1};const o=trimTrailingBlanks({lines:t,from:s-1,until:r});return{start:r,end:o}}function ensureHeader(e){if(!e)return lC+"\n\n";const t=e.trim();return t.startsWith(iC)||t.startsWith(cC)||t.startsWith(uC)?e:lC+"\n\n"+e}function ensureTrailingNewlines(e){return e?e.endsWith("\n\n")?e:e.endsWith("\n")?e+"\n":e+"\n\n":e}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(formatMergeParts,"formatMergeParts"),__name(hasMergeConflictRisk,"hasMergeConflictRisk"),__name(hasMergeConflictRiskInRecord,"hasMergeConflictRiskInRecord"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(parseOwnerPackage,"parseOwnerPackage"),__name(handleResultErrors,"handleResultErrors"),__name(getTimeAgo,"getTimeAgo"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Nt(),Es(),Nt(),Nt(),Nt(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Nt(),__name(formatPackage,"formatPackage"),Nt(),fC(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var tP="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:tP,category:e.name});return E(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await $.stat(e.sourcePath);return{category:e.category,learningCount:e.learnings.length,lastUpdated:t.mtime,filePath:e.sourcePath}}catch{return{category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}}}async function getAllPackages(){const e=getTastePath({target:tP});if(!E(e))return[];const t=await $.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:tP,category:t});return E(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:tP});await $.mkdir(r,{recursive:!0});const s=getCategoryTasteFile({target:tP,category:n.category}),o=e.dirname(s);await $.mkdir(o,{recursive:!0});const i=formatPackage({pkg:n});await $.writeFile(s,i,"utf-8")}async function listPackages(){const e=await getAllPackages();return await Promise.all(e.map(getPackageInfo))}__name(loadCategoryPackages,"loadCategoryPackages"),__name(getPackageInfo,"getPackageInfo"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(writePackage,"writePackage"),__name(listPackages,"listPackages"),Nt(),Nt(),fC();var nP="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!E(n))return null;const r=migrateHeader({content:await $.readFile(n,"utf-8")}).split("\n"),s=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!s)return null;const o=r.slice(0,s.start),i=s.end<r.length-1?r.slice(s.end+1):[],a={before:o.join("\n").trim(),after:i.join("\n").trim()},l=[...o,...i].join("\n").trim();return""===l&&await $.rm(n,{force:!0}),""!==l&&await $.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:nP}),s=await removeCategoryFromRoot({category:n,rootFile:r}),o=getCategoryTasteFile({target:nP,category:n}),i=e.dirname(o);return E(i)&&await $.rm(i,{recursive:!0,force:!0}),s}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,s=formatPackage({pkg:t});if(r){let e=ensureHeader(migrateHeader({content:r.before}));e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=s.trim()+t,void await $.writeFile(n,e.trim()+"\n","utf-8")}let o="";E(n)&&(o=await $.readFile(n,"utf-8"),o=migrateHeader({content:o})),o=ensureHeader(o),o=ensureTrailingNewlines(o),o+=s,await $.writeFile(n,o.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:s}=t,o=getCategoryTasteFile({target:nP,category:n.category}),i=e.dirname(o);await $.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await $.writeFile(o,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(s){let e=ensureHeader(migrateHeader({content:s.before}));e=ensureTrailingNewlines(e);const t=s.after?"\n\n"+s.after:"";return e+=l.trim()+t,void await $.writeFile(r,e.trim()+"\n","utf-8")}let u="";E(r)&&(u=await $.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await $.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var rP="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:rP,category:e.name});return E(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:rP});if(!E(e))return[];const t=[],n=getRootTasteFile({target:rP});if(E(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await $.readdir(e,{withFileTypes:!0}),s=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...s),t}async function getPackage2(e){const{category:t}=e;return(await getAllPackages2()).find(e=>e.category===t)||null}async function writePackage2(e){const{pkg:t}=e,n=getTastePath({target:rP});await $.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:rP}),s=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:s}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:s})}function exists2(){const e=getTastePath({target:rP});return E(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!E(n))return;const r=await $.readFile(n,"utf-8"),s=new Blob([r],{type:"text/markdown"}),o=new File([s],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,o)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:s,type:o="category",isPublic:i=!1}=t,a=new FormData;a.append("name",n),s&&a.append("description",s),a.append("type",o),a.append("isPublic",String(i));const l=formatPackage({pkg:r}),u=new Blob([l],{type:"text/markdown"}),d=new File([u],"taste.md",{type:"text/markdown"});if(a.append("files[taste.md]",d),"category"===o)return a;const m=getTastePath({target:"local-project"}),p=e.join(m,r.category);if(!E(p))return a;const g=getCategoryTasteFile({target:"local-project",category:r.category});if(!E(g))return a;const h=await $.readFile(g,"utf-8"),f=new Blob([h],{type:"text/markdown"}),y=new File([f],"taste.md",{type:"text/markdown"});return a.append(`files[${r.category}/taste.md]`,y),a}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:s=!1}=e,o=new FormData;o.append("name",n),r&&o.append("description",r),o.append("type","project"),o.append("isPublic",String(s));const i=getRootTasteFile({target:"local-project"});if(E(i)){const e=await $.readFile(i,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});o.append("files[taste.md]",n)}const a=t.map(e=>appendCategoryFile(o,e));return await Promise.all(a),o}function parseLearningLine(e){const t=e.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(!t)return null;const n=t[1].trim(),r=parseFloat(t[2]);return!n||isNaN(r)?null:{text:n,confidence:r}}function parseTasteContent(e){return e.split("\n").filter(e=>{const t=e.trim();return t&&!t.startsWith("#")&&t.startsWith("-")}).map(e=>parseLearningLine(e.trim())).filter(e=>null!==e)}async function parseApiError(e){const{response:t,fallback:n}=e;try{const e=await t.json();return e.error?.message||e.message||n}catch{return n}}function throwTrackedError(e){const{message:t,label:n,heading:r,status:s,extra:o}=e,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:Br.TASTE_REMOTE_STORAGE,heading:r,"http.status":s,...o}}),i}async function requireAuthKey(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");return e}async function downloadPackage(e){const{owner:t,packageName:n}=e,r=getApiBaseUrl(),s=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(s)return s;const o=await getAuthKey();if(!o)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");return tryAuthenticatedDownload({baseUrl:r,owner:t,packageName:n,apiKey:o})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,s=`${t}${St.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let o;try{o=await fetch(s,{method:"GET"})}catch{return null}if(o.ok){const{data:e}=await o.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===o.status)return null;throwTrackedError({message:await parseApiError({response:o,fallback:`Failed to download taste package (${o.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:o.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:s}=e,o=`${t}${St.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${s}`}});if(i.ok){const{data:e}=await i.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===i.status)return null;throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:i.status})}async function fetchSinglePackage(e){try{return await getPackage3({category:e.name})}catch(t){const n=t instanceof Error?t:new Error(String(t));return trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_package_error"}),context:{component:Br.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${n.message}`),null}}async function getAllPackages3(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${St.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list taste packages",status:n.status});const{data:r}=await n.json(),s=r.packages||[];if(0===s.length)return[];const o=[];for(let e=0;e<s.length;e+=5){const t=s.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));o.push(...n.filter(e=>null!==e))}return o}async function getPackage3(e){const{category:t}=e;let n;await requireAuthKey();try{n=await getAuthenticatedEntity()}catch(e){const n=e instanceof Error?e:new Error(String(e));throw dlog(`[Auth] getPackage: entity endpoint unavailable — ${n.message}`),trackError({error:sanitizeErrorForTelemetry({error:n,label:"get_entity_error"}),context:{component:Br.TASTE_REMOTE_STORAGE,heading:"getAuthenticatedEntity failed in getPackage"}}),new Error(`Could not resolve your account to fetch '${t}'. Check your connection and try again.`)}if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");return downloadRemotePackage({owner:n.user.userName,packageName:t})}async function downloadRemotePackage(e){const{owner:t,packageName:n}=e,r=await downloadPackage({owner:t,packageName:n});if(!r)return null;const s=r.files||[];if(0===s.length)return null;const o=s.find(e=>"taste.md"===e.file);if(!o)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(o.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1}=e,s=await requireAuthKey(),o=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r}),i=`${getApiBaseUrl()}${St.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,a=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:o});a.ok||throwTrackedError({message:await parseApiError({response:a,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:a.status}),await a.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:s=!1}=e,o=await requireAuthKey(),i=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:s}),a=`${getApiBaseUrl()}${St.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:i});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:l.status,extra:{"package.count":t.length}}),await l.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${St.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list packages",status:n.status});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 function list(e){const{location:t}=e;if("local-global"===t)return listPackages();if("remote-project"===t||"remote-user"===t)return listPackages2();if("local-project"===t){const e=getRootTasteFile({target:"local-project"}),t=await getAllPackages2();return Promise.all(t.map(async t=>{let n;if(t.sourcePath!==e)try{n=(await $.stat(t.sourcePath)).mtime}catch{}return{category:t.category,learningCount:t.learnings.length,lastUpdated:n,filePath:t.sourcePath}}))}throw new Error(`Invalid location: ${t}`)}function createListCommand(){return new Ae("list").alias("ls").option("-g, --global","List global packages").addOption(new xe("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new xe("--staging","Use staging environment").hideHelp()).description(`List available packages ${Be.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}__name(loadCategoryPackages2,"loadCategoryPackages"),__name(getAllPackages2,"getAllPackages"),__name(getPackage2,"getPackage"),__name(writePackage2,"writePackage"),__name(exists2,"exists"),Nt(),ts(),Nt(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),Ot(),Nt(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),AC(),Vr(),Nt(),Qs(),Vr(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Nt(),ts(),Qs(),Ot(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),$n(),__name(fetchSinglePackage,"fetchSinglePackage"),__name(getAllPackages3,"getAllPackages"),__name(getPackage3,"getPackage"),__name(downloadRemotePackage,"downloadRemotePackage"),__name(writePackage3,"writePackage"),__name(writePackages,"writePackages"),__name(listPackages2,"listPackages"),__name(list,"list"),__name(createListCommand,"createListCommand");var sP={remote:{location:"remote-project",name:"remote",subtitle:"commandcode.ai account"},global:{location:"local-global",name:"global",subtitle:"~/.commandcode/taste"},project:{location:"local-project",name:"project",subtitle:".commandcode/taste"}};function resolveStorage(e){return e.remote?sP.remote:e.global?sP.global:sP.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${be.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${be.arrowDown}${e.downloadCount}`.length),t}function formatPackageLine({pkg:e,maxLen:t}){const n=" ".repeat(t-getPackageDisplayLength(e)+2),r=e.lastUpdated?getTimeAgo(e.lastUpdated):null,s=r?`, updated ${r}`:"";return` ${Be.white(e.category)}${e.isPublic?Be.green(" [public]"):""}${e.isPublic&&e.starCount?Be.yellow(` ${be.star}${e.starCount}`):""}${e.downloadCount?Be.gray(` ${be.arrowDown}${e.downloadCount}`):""}${n}${Be.dim.gray(`(${e.learningCount} learnings${s})`)}`}function validateListOptions(e){e.global&&e.remote&&exitWithError("Error: Cannot specify both --global and --remote flags")}async function fetchPackages({options:e}){const t=resolveStorage(e),n=e.remote?Ie(`Fetching ${t.name} packages`).start():null,r=await list({location:t.location});return n?.stop(),{packages:r,storage:t}}async function getStorageLabel({options:e,fallback:t}){if(!e.remote)return t;const n=await getUserName();return n?getProfileLink(n):t}function printPackageTable({packages:e,subtitle:t}){console.log(`\n${Z_} Packages`),console.log(`${Be.gray("⎿")} ${Be.dim(t)}\n`);const n=Math.max(...e.map(getPackageDisplayLength));let r=0;for(const t of e)r+=t.learningCount,console.log(formatPackageLine({pkg:t,maxLen:n}));console.log(Be.dim(`\nTotal: ${e.length} packages, ${r} learnings\n`))}async function runList({options:e}){console.log(""),validateListOptions(e);const{packages:t,storage:n}=await fetchPackages({options:e});0!==t.length?printPackageTable({packages:t,subtitle:await getStorageLabel({options:e,fallback:n.subtitle})}):console.log(Be.yellow(`No taste packages found in ${n.name}`))}async function fetchAllPackages(e){const{target:t}=e;return"local-project"===t?getAllPackages2():"local-global"===t?getAllPackages():getAllPackages3()}function handleOpenError(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 readCategoryLineNumber(t){const{filePath:n,category:r}=t,s=await $.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const o=s.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return o>=0?o+1:1}async function findCategoryLineNumber(e){try{return await readCategoryLineNumber(e)}catch{return 1}}async function openPackage(e){const{packageName:t,target:n}=e,r=(await fetchAllPackages({target:n})).find(e=>e.category===t);if(!r){let e="project";return"local-global"===n&&(e="global"),"remote-project"!==n&&"remote-user"!==n||(e="remote"),{success:!1,error:`Taste package '${t}' not found in ${e}`}}const s=r.sourcePath,o=await findCategoryLineNumber({filePath:s,category:t});return await et([{file:s,line:o}]),{success:!0,filePath:s,lineNumber:o}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Nt(),Nt(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var oP=new Set(["local-project","local-global","remote-project","remote-user"]);async function open7(e){const{package:t,target:n}=e;if(!oP.has(n))return{success:!1,error:`Invalid target: ${n}`};try{return await openPackage({packageName:t,target:n})}catch(e){return handleOpenError(e)}}function getEditorSetupInstructions(){const e=it.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}`}function createOpenCommand(){return new Ae("open").argument("[package]","Taste package name, or owner/package to open in browser").option("-g, --global","Open taste package from global storage (~/.commandcode)").description(`Open a taste package in your editor ${Be.dim("(use owner/package to open in browser)")}`).action(withErrorHandler(async(e,t)=>runOpen({packageName:e,options:t})))}function validateOpenOptions(e){e||exitWithUsage({message:"Specify a taste package name to open",usage:["cmd taste open <package> open taste package in editor","cmd taste open <package> -g open global taste package in editor","cmd taste open owner/package open package page in browser"]})}async function runOpen({packageName:e,options:t}){console.log(""),validateOpenOptions(e);const n=parseOwnerPackage(e);n?await openInBrowser(n):await openInEditor3({packageName:e,options:t})}async function openInBrowser(e){const t=`https://commandcode.ai/${e.owner}/${e.packageName}`;await ie(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${Be.green(be.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open7({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${Be.green(be.tick)} Opened ${Be.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open7,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Nt(),Nt(),Nt(),Nt();var iP=null,aP=!1;function setActiveSpinner(e){iP=e}function stopActiveSpinner(e){iP&&(iP.stop(e),iP=null)}function setPrompted(e){aP=e}function wasPrompted(){return aP}function beginPrompt(e,t){stopActiveSpinner(),Ee.intro(Be.dim(e)),t&&Ee.log.message(Be.dim(t)),setPrompted(!0)}function handleCancel(e){Ee.isCancel(e)&&(Ee.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Ee.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Ee.spinner();r.start(t),setActiveSpinner({stop:__name(e=>r.stop(e??n),"stop"),cancel:__name(e=>r.cancel(e),"cancel"),error:__name(e=>r.error(e),"error")})}async function promptMergeStrategy(e){const{packageName:t,owner:n,localPkg:r,remoteLearningsCount:s}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${Be.green(`'${t}'`)} from ${n}`,o),Ee.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${s} learnings ${Be.dim(`(from ${n})`)}`);const i=await Ee.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} → ${s} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});handleCancel(i);const a=i;return startStrategySpinner(a),a}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e,s="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${Be.green(`'${t}'`)} to global`,s),Ee.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const o=await Ee.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"});handleCancel(o);const i=o;return startStrategySpinner(i),i}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${Be.green(`'${t}'`)} from global`,s),Ee.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const o=await Ee.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"});handleCancel(o);const i=o;return startStrategySpinner(i),i}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:s}=e,o=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ot(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${Be.green(`'${t}'`)} to ${n}`,o),Ee.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${s} learnings) in ${n}`),Ee.log.info(`Current package: ${Be.cyan(i)} ${Be.dim("(review)")}`);const a=await Ee.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"});handleCancel(a);const l=a;return startStrategySpinner(l),l}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:s}=e,o=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ee.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ot(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${Be.green(`'${t}'`)} to ${n}`,o),Ee.log.message(`Local: ${r} learnings\nRemote: ${s} learnings`),Ee.log.info(`Current package: ${Be.cyan(i)} ${Be.dim("(review)")}`);const a=await Ee.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 (${s} → ${r} learnings)`}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}function mergeSingleLearning(e,t,n,r){const s=t.get(e.text);return s?e.confidence>s.confidence?(n.set(e.text,e),void r.updated++):void r.unchanged++:(n.set(e.text,e),void r.added++)}function mergePackages(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},s=new Map(n.map(e=>[e.text,e])),o=new Map(s);for(const e of t)mergeSingleLearning(e,s,o,r);const i=new Set(t.map(e=>e.text)),a=n.filter(e=>!i.has(e.text)).length;return r.unchanged+=a,{merged:Array.from(o.values()),details:r}}function validateSinglePackage(e,t){const n=validateTasteFile({content:formatPackage({pkg:e}),filePath:`${e.category}/taste.md`});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:e.category,error:`Validation failed for taste package in ${t}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${e.category}' in ${t} has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validateSingleRemoteFile(e,t){const n=validateTasteFile({content:e.content,filePath:e.file});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:t,error:`Validation failed for ${e.file}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validatePackages(e){const{packages:t,label:n}=e;return t.map(e=>validateSinglePackage(e,n)).filter(e=>null!==e)}function validateRemoteFiles(e){const{files:t,packageName:n}=e;return t.map(e=>validateSingleRemoteFile(e,n)).filter(e=>null!==e)}function mergeOrKeep(e){const{source:t,existing:n}=e;if(!n)return{pkg:t,details:{added:t.learnings.length,updated:0,unchanged:0}};const r=mergePackages({source:t.learnings,target:n.learnings});return{pkg:{...t,learnings:r.merged},details:r.details}}async function resolveRemotePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,tastePkg:s,owner:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:s.category,owner:o,localPkg:r,remoteLearningsCount:s.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:s,result:o}=e,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:s,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void o.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),o.packagesPulled.push(t.category),o.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),o.packagesPulled.push(t.category),o.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});o.filePaths[t.category]=l}async function processPackage(e){const{tastePkg:t,result:n}=e;try{await executePackageStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullProjectPackage(e){const{files:t,packageName:n,owner:r,overwrite:s,flagStrategy:o,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(a){const e=parsePackages({content:a.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:s,flagStrategy:o,result:i})}const l=t.filter(e=>"taste.md"!==e.file);for(const e of l){const t=e.file.replace("/taste.md",""),a={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:a,owner:r,overwrite:s,flagStrategy:o,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:s,flagStrategy:o,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(!a)return i.success=!1,void i.errors.push({pkg:n,error:"No taste.md file found in category package"});const l={category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,owner:r,overwrite:s,flagStrategy:o,result:i})}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),Nt(),Nt(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Nt(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var lP=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),cP=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),uP=__name(e=>"local-global"===e?"global":"remote-project"===e?"remote project":"remote-user"===e?"remote":"source","sourceName");async function resolvePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,source:s,tastePkg:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===s?promptGlobalPullStrategy({packageName:o.category,localPkg:r,globalLearningsCount:o.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:s,result:o}=e,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:s,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void o.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),o.packagesPulled.push(t.category),o.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),o.packagesPulled.push(t.category),o.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});o.filePaths[t.category]=l}async function pullSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePullStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pull(e){const{packages:t,source:n,overwrite:r=!1,strategy:s}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return lP({pkg:"all",error:`Invalid source: ${n}`});const o=uP(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return lP({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return lP({pkg:"all",error:`No taste packages found in ${o}`});const a=validatePackages({packages:i,label:o});if(a.length>0)return{success:!1,packagesPulled:[],errors:[...a],mergeDetails:{},overwritten:[],filePaths:{}};const l=t.length>0?i.filter(e=>t.includes(e.category)):i;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${o}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=cP();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:s,overwrite:r,result:u});return u}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o}=e,i=await downloadPackage({owner:t,packageName:n});if(!i)return lP({pkg:n,error:"Taste package not found in remote"});const{type:a,files:l}=i,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy:s,result:o};return"project"===a?(await pullProjectPackage(d),o):(await pullCategoryPackage(d),o)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:s}=e,o=cP();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o})}catch(e){return lP({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Ee.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:s,mergeDetails:o}=e,i=wasPrompted()?"":`${be.tick} `,a=r?Be.dim(`\n ${shortenPath(r)}`):"";if(s.overwrite)return`${Be.green(i)}Replaced ${Be.green(`'${t}'`)} taste package in project`+a;if(o){const e=formatMergeParts(o);return`${Be.green(i)}Pulled ${Be.green(`'${t}'`)} taste package from ${n} ${Be.gray(`(${e.join(", ")})`)}`+a}return`${Be.green(i)}Pulled ${Be.green(`'${t}'`)} taste package from ${n}`+a}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const s=t.packagesPulled[0],o=t.filePaths?.[s],i=t.mergeDetails?.[s];return logResult(buildPullMessage({pkgName:s,sourceName:n,filePath:o,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],s=t.skipped??[],o=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+s.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return o.length>0&&l.push(wrapLine(`${Be.green("Pulled")} (${o.length}) ${o.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${Be.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),s.length>0&&l.push(wrapLine(`${Be.dim("Skipped")} (${s.length}) ${Be.dim(s.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Ee.log.message(l.join("\n")),Ee.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${Be.green(be.tick)} ${a} from ${n}`),l.length>0&&console.log(l.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,s=t.skipped??[];t.packagesPulled.length+s.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():s.length>0?logResult(Be.yellow(`Skipped '${s[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new Ae("pull").argument("[package]","Taste package name, or owner/package to pull from remote").option("-g, --global","Pull taste package from global storage (~/.commandcode)").addOption(new xe("--local","Use local server").hideHelp()).option("--remote","Pull taste package from commandcode.ai remote").option("--all","Pull all taste packages from global").option("--overwrite","Replace local package without prompting").option("--skip","Keep local package, skip conflicting pull").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new xe("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${Be.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:s}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?s??"remote":"global",options:n})}))}function validatePullOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one source"),n.remote&&n.all&&exitWithUsage({message:"--all is not supported for remote pull — specify a package instead",usage:["cmd taste pull <owner>/<package> pull a taste package from remote"]}),n.remote&&!t&&exitWithUsage({message:"Specify a taste package to pull from remote",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),n.remote&&t&&!t.includes("/")&&exitWithUsage({message:`Remote pull requires owner/package format — got '${t}'`,usage:["cmd taste pull <owner>/<package> e.g. cmd taste pull ahmadawais/code-style"]}),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to pull everything",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}async function runPull(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePullOptions({packageName:t,options:r});const s=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:s}):pullGlobal({packageName:t,options:r,strategy:s})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,s=parseOwnerPackage(t);s||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner(Ie("Pulling taste package").start());const o=await pullRemote({owner:s.owner,packageName:s.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:o,owner:s.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner(Ie("Pulling taste package").start());const s=n.all||!t?[]:[t],o=await pull({packages:s,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:o}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new Vb({baseUrl:e}),n=await t.get({endpoint:St.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 logResult2(e){if(wasPrompted())return Ee.outro(e),void setPrompted(!1);console.log(e)}function logPushAllSuccess(t){const{result:n,options:r}=t;if(!r.all)return!1;if(0===n.packagesPushed.length){const e=n.skipped?.length??0;if(e>0){const t=wasPrompted()?"":`${be.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${Be.green(t)}Skipped ${n}`)}return!1}const s=n.packagesPushed.length,o=`${s} ${1===s?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${be.tick} `;if(!a)return logResult2(`${Be.green(l)}Pushed ${o} to remote`),!1;if(r.overwrite||Boolean(n.overwritten?.length)){let e=0;if(n.mergeDetails)for(const t of Object.values(n.mergeDetails))e+=t.updated??0;const t=e>0?` ${Be.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${Be.green(l)}Replaced ${o} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${Be.green(l)}Pushed ${o} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const p=formatMergeParts({added:u,updated:d,unchanged:m}),g=p.length>0?` ${Be.gray(`(${p.join(", ")})`)}`:"";return logResult2(`${Be.green(l)}Pushed ${o} to ${a}${g}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],s=t.filePaths?.[r],o=n.remote&&s,i=o?s:"global",a=wasPrompted()?"":`${be.tick} `,l=!o&&s?Be.dim(`\n ${shortenPath(s)}`):"";if(n.overwrite)return logResult2(`${Be.green(a)}Replaced ${Be.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${Be.green(a)}Pushed ${Be.green(`'${r}'`)} taste package to ${i} ${Be.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${Be.green(a)}Pushed ${Be.green(`'${r}'`)} taste package to ${i}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",s=wasPrompted()?"":`${be.tick} `;return logResult2(wrapLine(`${Be.green(s)}Pushed ${Be.green(t.packagesPushed.length)} taste packages ${Be.green(`(${t.packagesPushed.join(", ")})`)} to ${r}`)),!(n.overwrite||!t.mergeDetails)&&hasMergeConflictRiskInRecord(t.mergeDetails)}function logPushUrls(e){const{result:t,options:n}=e;if(!n.remote||!t.filePaths)return;const r=new Set;for(const e of t.packagesPushed){const n=t.filePaths[e];if(!n||!n.includes("/"))continue;const[s,o]=n.split("/");if(!s||!o)continue;const i=getPackageLink({owner:s,packageName:o});r.has(i)||(r.add(i),console.log(Be.gray(` ${i}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],s=t.packagesPushed.filter(e=>!n.includes(e)),o=t.packagesPushed.length+r.length,i=[];s.length>0&&i.push(wrapLine(`${Be.green("Merged")} (${s.length}) ${s.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${Be.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${Be.dim("Skipped")} (${r.length}) ${Be.dim(r.join(", "))}`,4)),i.length>0&&Ee.log.message(i.join("\n"));const a=`${o} ${1===o?"package":"packages"}`;Ee.outro(a)}function logPushBreakdown(e){const t=e.overwritten??[],n=e.skipped??[];if(0===n.length&&0===t.length)return;const r=e.packagesPushed.filter(e=>!t.includes(e)),s=[];r.length>0&&s.push(wrapLine(`${Be.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&s.push(wrapLine(`${Be.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&s.push(wrapLine(`${Be.dim("Skipped")} (${n.length}) ${Be.dim(n.join(", "))}`)),s.length>0&&console.log(s.join("\n"))}function logPushSuccess(e){const{result:t,options:n}=e;if(wasPrompted())return setPrompted(!1),logConflictSummary({result:t}),void logPushUrls({result:t,options:n});const r=logPushAllSuccess({result:t,options:n})||logPushSingleSuccess({result:t,options:n})||logPushMultiSuccess({result:t,options:n});n.all&&logPushBreakdown(t),logPushUrls({result:t,options:n}),r&&logMergeReviewTip()}__name(resolvePullStrategy,"resolvePullStrategy"),__name(executePullStrategy,"executePullStrategy"),__name(pullSinglePackage,"pullSinglePackage"),__name(pull,"pull"),__name(executePullRemote,"executePullRemote"),__name(pullRemote,"pullRemote"),Nt(),__name(logResult,"logResult"),__name(buildPullMessage,"buildPullMessage"),__name(logPullSingleSuccess,"logPullSingleSuccess"),__name(logPullSummary,"logPullSummary"),__name(logPullSuccess,"logPullSuccess"),__name(createPullCommand,"createPullCommand"),__name(validatePullOptions,"validatePullOptions"),__name(runPull,"runPull"),__name(pullRemoteSingle,"pullRemoteSingle"),__name(pullGlobal,"pullGlobal"),Nt(),$n(),Nt(),ts(),bE(),Ot(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Nt(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Nt(),AC(),Nt();var dP=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),mP=__name(e=>e.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0),"countRemoteLearnings");async function resolvePushAllStrategy(e){const{flagStrategy:t,overwrite:n,existingProject:r,packagesToPush:s,projectName:o,owner:i}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const a=r.type??"category",l=s.reduce((e,t)=>e+t.learnings.length,0),u=mP(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:o,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:o,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:s,isPublic:o,isPublicExplicitlySet:i,flagStrategy:a}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l});if("skip"===await resolvePushAllStrategy({flagStrategy:a,overwrite:s,existingProject:d,packagesToPush:n,projectName:l,owner:r}))return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:i?o:d?.isPublic??!1});for(const e of n)u.packagesPushed.push(e.category),u.filePaths[e.category]=`${r}/${l}`,u.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&u.overwritten.push(...n.map(e=>e.category)),u}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return dP({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var pP=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),gP=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:s}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:s})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var hP=__name(e=>{const{target:t,category:n,owner:r}=e;return"local-global"===t?getCategoryTasteFile({target:"local-global",category:n}):"remote-project"!==t&&"remote-user"!==t||!r?void 0:`${r}/${n}`},"getDestPath");async function getUserOwner(){try{const e=await getAuthenticatedEntity();if(e.success&&e.user?.userName)return e.user.userName}catch{}}async function resolveSinglePushStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,target:s,tastePkg:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===s?promptGlobalPushStrategy({packageName:o.category,localLearningsCount:o.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:s,userOwner:o,isPublic:i,result:a}=e,l="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),u=await resolveSinglePushStrategy({flagStrategy:r,overwrite:s,existingPkg:l,target:n,tastePkg:t});if("skip"===u)return void a.skipped.push(t.category);if("overwrite"===u&&(await writePkg({pkg:t,target:n,owner:o,isPublic:i}),a.packagesPushed.push(t.category),a.overwritten.push(t.category),a.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:o,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=hP({target:n,category:t.category,owner:o});d&&(a.filePaths[t.category]=d)}async function pushSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePushStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function push(e){const t=void 0!==e.isPublic,{packages:n,target:r,overwrite:s=!1,isPublic:o=!1,strategy:i}=e;if(!exists2())return pP({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return pP({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:a,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?a.filter(e=>n.includes(e.category)):a;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:s,isPublic:o,isPublicExplicitlySet:t,flagStrategy:i}):pP({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return pP({pkg:"all",error:`Invalid target: ${r}`});const m=gP();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,overwrite:s,userOwner:d,isPublic:o,result:m});return m}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:s=!1,isPublic:o=!1,strategy:i}=e,a=await getPackage2({category:r});if(!a)return pP({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:a}),filePath:`${a.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return pP({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:i,overwrite:s,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?o:u?.isPublic??!1,p=gP();if("skip"===d)return p.skipped.push(r),p;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m}),p.packagesPushed.push(r),p.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),p.packagesPushed.push(r),p.mergeDetails[r]=t}return p.filePaths[r]=`${n}/${r}`,p}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return pP({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return pP({pkg:t,error:e instanceof Error?e.message:String(e)})}}async function promptOwnerSelection(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"}))],s=await Ee.select({message:"Owner",options:r,initialValue:t});return Ee.isCancel(s)&&(Ee.cancel("Operation cancelled"),process.exit(0)),s}function createPushCommand(){return new Ae("push").description(`Push taste packages to remote ${Be.dim("(commandcode.ai)")} or global ${Be.dim("(~/.commandcode)")}`).argument("[package]","Taste package name to push (omit with --all)").option("--all","Push all taste packages to remote").option("--remote","Push to commandcode.ai remote (default)").option("-g, --global","Push to local global storage (~/.commandcode)").addOption(new xe("--local","Use local server").hideHelp()).option("--public","Make package publicly discoverable on commandcode.ai").option("--private","Make package private (not publicly discoverable)").option("--owner <owner>","Push under a specific owner or organization").option("--overwrite","Replace existing package without prompting").option("--skip","Keep existing package, skip conflicting push").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new xe("--staging","Push to staging environment").hideHelp()).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),r=await runPush({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPushSuccess({result:r,options:n})}))}function validatePushOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one destination"),n.public&&n.private&&exitWithError("--public and --private are mutually exclusive — pick one visibility"),n.owner&&n.global&&exitWithError("--owner only applies to remote pushes, not --global"),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to push everything",usage:["cmd taste push <package> push a taste package to remote (default)","cmd taste push --all push all taste packages to remote","cmd taste push <package> -g push a taste package to global (~/.commandcode)"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}__name(getUserOwner,"getUserOwner"),__name(resolveSinglePushStrategy,"resolveSinglePushStrategy"),__name(executePushStrategy,"executePushStrategy"),__name(pushSinglePackage,"pushSinglePackage"),__name(push,"push"),__name(executeRemotePush,"executeRemotePush"),__name(pushRemote,"pushRemote"),Nt(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var fP=__name(e=>!!e.public||!e.private&&void 0,"resolveVisibility");async function validateOwnerAccess(e){let t;try{t=await fetchUserNamespaces()}catch(e){return void dlog(`[Auth] validateOwnerAccess: namespace service unavailable, skipping — ${e instanceof Error?e.message:String(e)}`)}const n=[t.userName,...t.orgs.map(e=>e.login)];n.includes(e)||exitWithError(`No push access to '${e}'. Available: ${n.join(", ")}`)}async function resolveOwnerForPush(e){const{packageName:t,owner:n}=e,r=parseOwnerPackage(t);if(r)return await validateOwnerAccess(r.owner),r;if(n)return await validateOwnerAccess(n),{owner:n,packageName:t};Ee.intro(Be.dim(`pushing ${t}`)),setPrompted(!0);const s=Ee.spinner();s.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(s.error("Failed"),Ee.outro(Be.red(`Taste package '${t}' not found in project`)),process.exit(1));const o=await fetchUserNamespaces();return s.stop(o.orgs.length>0?"Select owner to push to":""),{owner:o.orgs.length>0?await promptOwnerSelection(o):o.userName,packageName:t}}async function runPush(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePushOptions({packageName:t,options:r});const s=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:s}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:s}):pushGlobal({packageName:t,options:r,strategy:s})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const s=(await getAllPackages2()).length,o=`${s} ${1===s?"package":"packages"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(Be.dim(` Pushing ${o} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(Ie("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:fP(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:s,packageName:o}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:s,pkgName:o});const i=await pushRemote({owner:s,packageName:o,overwrite:n.overwrite,isPublic:fP(n),strategy:r});return stopActiveSpinner(`Pushed to ${s}/${o}`),i}function resolveStrategyLabel(e){const{strategy:t,isRemote:n=!1}=e;return"overwrite"===t?" · overwrite":"skip"===t?" · skip conflicts":"merge"===t?" · auto-merge":n?"":" · will prompt on conflicts"}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=Ee.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Ie("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,s=n.all||!t?[]:[t],o=await getAllPackages2(),i=s.length>0?s.length:o.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(Be.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(Ie("Pushing taste packages").start());const d=await push({packages:s,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new Ae(Tt.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),e}function formatVersion(e,t,n=!1){const r=n?re.bold(re.green(t)):re.white(t);return`${re.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${re.bold(re.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(re.dim(`Run ${re.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(re.dim("Try updating manually:")),console.log(re.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(re.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Ie("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(`${re.green(be.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${re.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Ie("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} ${be.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:Br.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 ${re.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(resolveStrategyLabel,"resolveStrategyLabel"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),__name(createTasteCommand,"createTasteCommand"),Nt(),Ot(),Vr(),__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 yP=new Ae("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Nt(),Qs(),AC();var wP=__name((e,t)=>`${be.info} ${e}: ${re.cyan(t)}`,"formatInfoLine"),SP=__name(e=>re.bold(`${e}:`),"formatSectionHeader"),bP=__name(e=>re.red(e),"formatError"),EP=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),CP=__name(e=>["",SP("User Information"),wP("Name",e.name),wP("Email",e.email),wP("Username",e.userName)],"buildUserOutput"),vP=__name(e=>["",SP("Organization"),wP("Name",e.name),wP("Login",e.login)],"buildOrgOutput"),TP=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),kP=__name((e,t)=>{TP(CP(e)),t&&TP(vP(t)),console.log("")},"displayUserInfo"),_P=__name(e=>null!==e&&e.length>0,"validateApiKey"),PP=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Ie("Fetching user information...").start();try{const t=await getAuthKey();_P(t)||(e.fail(bP('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();PP(n)||(e.fail(bP("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),kP(n.user,n.org)}catch(t){e.fail(bP(`Error: ${EP(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var AP=new Ae("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var xP=createProgram();xP.action(interactiveModeAction),xP.addCommand(W_),xP.addCommand(Q_),xP.addCommand(AP),xP.addCommand(yP),xP.addCommand(U_),xP.addCommand(createTasteCommand()),xP.addCommand(createMcpCommand()),xP.addCommand(G_),xP.addCommand(ps),xP.addCommand(bs),xP.addCommand(As),setupCommanderHooks(xP),xP.parse();