command-code 0.11.6 → 0.11.8
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 +3 -3
- package/package.json +1 -1
- package/vsix/commandcode-vscode.vsix +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as e from"path";import t,{join as n,dirname as r,relative as o,isAbsolute as s,resolve as a,extname as i,basename as c}from"path";import{fileURLToPath as l,URL as d,pathToFileURL as u}from"url";import m,{z as g}from"zod";import*as p from"os";import h,{tmpdir as f}from"os";import*as y from"fs";import w,{existsSync as E,readFileSync as S,promises as k,constants as v,mkdirSync as b,writeFileSync as C,readdirSync as P,statSync as T,createReadStream as A}from"fs";import{spawn as x,execSync as I,exec as $,execFile as R}from"child_process";import*as D from"fs/promises";import M,{mkdir as N,writeFile as O,readFile as F,unlink as L}from"fs/promises";import*as _ from"crypto";import U,{randomUUID as j}from"crypto";import B,{useState as z,useRef as W,useEffect as H,useCallback as G,useMemo as q}from"react";import{Box as V,Text as K,Static as J,render as Y,useStdout as Q,useInput as Z,useApp as X}from"ink";import ee from"chalk";import te from"strip-ansi";import ne from"picocolors";import re from"sharp";import oe from"open";import se from"@opentelemetry/sdk-node";import ae from"@opentelemetry/exporter-trace-otlp-http";import ie from"@opentelemetry/resources";import ce from"@opentelemetry/semantic-conventions";import le from"@opentelemetry/sdk-trace-node";import{trace as de,SpanStatusCode as ue,context as me}from"@opentelemetry/api";import{v4 as ge}from"uuid";import*as pe from"http";import*as he from"net";import fe from"net";import{promisify as ye}from"util";import"dotenv/config";import we from"dedent";import Ee from"log-symbols";import Se,{mainSymbols as ke}from"figures";import ve from"readline/promises";import{Command as be,Option as Ce}from"commander";import*as Pe from"@clack/prompts";import{cancel as Te,select as Ae,isCancel as xe,note as Ie,confirm as $e,password as Re}from"@clack/prompts";import De from"ink-spinner";import Me from"ora";import Ne from"@crosscopy/clipboard";import Oe from"gray-matter";import{EventEmitter as Fe}from"events";import Le from"@sindresorhus/slugify";import{minimatch as _e}from"minimatch";import{glob as Ue}from"glob";import{quote as je}from"shell-quote";import{MessageStream as Be}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import ze from"strip-json-comments";import*as We from"readline";import He from"ink-select-input";import Ge from"semver";import qe from"ignore";import Ve from"ink-gradient";import{Marked as Ke}from"marked";import Je from"marked-terminal";import*as Ye from"diff";import Qe from"open-editor";import Ze from"ink-text-input";import{wrapAnsi as Xe}from"fast-wrap-ansi";import et from"terminal-link";import*as tt from"process";var nt,rt,ot,st,at,it,ct,lt,dt,ut,mt,gt,pt,ht,ft,yt,wt,Et,St,kt,vt,bt,Ct,Pt=Object.defineProperty,Tt=Object.getOwnPropertyNames,__name=(e,t)=>Pt(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[Tt(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)Pt(e,n,{get:t[n],enumerable:!0})},At=__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"(){}}),xt=__esm({"src/utils/telemetry/constants.ts"(){At(),nt="https://api.axiom.co/v1/traces",rt="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",ot="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",st="xaat-add69148-8f73-4833-921d-bc843285c95f",at="command-code-cli",it="command_code_cli_tracing",ct=["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"],lt=["content","body"],dt=200,ut=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 It,$t,Rt=__esm({"../shared/src/constants.ts"(){At(),gt="--xco",pt={INTERNAL_TEAM_FLAG_HEADER:`x-${(mt="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage"},ht={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"}}}},ft={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(ft.ALPHA.TASTE),Object.values(ft.BETA.TASTE_PACKAGES),ht.ALPHA.GENERATE,ht.ALPHA.AGENT.GENERATE,ht.ALPHA.WHOAMI,ht.ALPHA.NAMESPACES,ht.ALPHA.SHARE.CREATE,ht.ALPHA.SHARE.DELETE,ht.ALPHA.SHARE.APPEND,ht.ALPHA.DEVREL_THREAD.CREATE,ht.ALPHA.DEVREL_THREAD.DELETE,ht.ALPHA.DEVREL_THREAD.UPDATE,ht.ALPHA.TASTE.LEARN,ht.ALPHA.TASTE.DELETE,ht.ALPHA.TASTE.GET,ht.ALPHA.TASTE.UPDATE,Object.values(ht.BETA.TASTE.PACKAGES),ht.INTERNAL.ADMIN.USERS,ht.INTERNAL.ADMIN.ORGS,ht.INTERNAL.ADMIN.ENTITY_TYPE,ht.INTERNAL.USER.AVATAR,ht.INTERNAL.USER.SETTINGS,ht.INTERNAL.API_KEYS.LIST,ht.INTERNAL.API_KEYS.CREATE,ht.INTERNAL.API_KEYS.DELETE,ht.INTERNAL.USAGE.LIST,ht.INTERNAL.USAGE.SUMMARY,ht.INTERNAL.ADMIN.GRANT_CREDITS,ht.INTERNAL.ADMIN.GRANT_ORG_CREDITS,ht.INTERNAL.BILLING.CREDITS.GET,ht.INTERNAL.BILLING.CUSTOMERS.GET,ht.INTERNAL.BILLING.CUSTOMERS.UPSERT,ht.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,ht.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,ht.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,ht.INTERNAL.BILLING.CUSTOMERS.INVOICES,ht.INTERNAL.BILLING.SUBSCRIPTIONS.GET,ht.INTERNAL.ORGS.LIST,ht.INTERNAL.ORGS.GET,ht.INTERNAL.ORGS.CREATE,ht.INTERNAL.ORGS.UPDATE,ht.INTERNAL.ORGS.DELETE,ht.INTERNAL.ORGS.MEMBERS.LIST,ht.INTERNAL.ORGS.MEMBERS.ADD,ht.INTERNAL.ORGS.MEMBERS.UPDATE,ht.INTERNAL.ORGS.MEMBERS.REMOVE,ht.INTERNAL.ORGS.INVITATIONS.LIST,ht.INTERNAL.ORGS.INVITATIONS.SEND,ht.INTERNAL.ORGS.INVITATIONS.ACCEPT,ht.INTERNAL.ORGS.INVITATIONS.CANCEL,ht.INTERNAL.TASTE.PACKAGES.LIST,Object.values(ft.INTERNAL.ORGS),Object.values(ft.INTERNAL.USER),Object.values(ft.INTERNAL.TASTE.PACKAGES),yt={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(yt.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl"),wt={ANTHROPIC:"anthropic"},Et="anthropic:claude-haiku-4-5-20251001",m.enum(["owner","admin","member"]),St={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,vt=kt.SONNET_4_6.id,new Set([].map(e=>e.toLowerCase())),bt=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],Ct={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"(){At(),It=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),$t=__name(()=>{const e=It();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag")}});function getAuthDir(){return t.join(h.homedir(),".commandcode")}function getAuthFile(e){const n=e??It(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??It(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var Mt,Nt,Ot=__esm({"src/utils/auth/auth-paths.ts"(){At(),Rt(),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 w.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(;!w.existsSync(n);){const o=t.dirname(n);if(o===n)return t.normalize(e);r.unshift(t.basename(n)),n=o}return t.join(getCanonicalPath(n),...r)}catch{return t.normalize(e)}}function formatDirectoryForDisplay(e){const n=canonicalizeForLookup(t.normalize(e)),r=getCanonicalPath(process.cwd()),o=h.homedir();if(isPathInDirectory(n,r)){const e=t.relative(r,n);return e?`./${e}`:"."}if(o&&isPathInDirectory(n,o)){const e=t.relative(o,n);return e?`~/${e}`:"~"}return n}function isPathInDirectory(e,n){const r=normalizePathForComparison(e),o=normalizePathForComparison(n),s=o.endsWith(t.sep)?o:o+t.sep;return r===o||r.startsWith(s)}function findSensitiveDirectoryConflict(e){const n=[t.normalize(e),getCanonicalPath(e)];for(const e of Mt){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(h.homedir(),n.slice(1))),t.isAbsolute(n)||(n=t.resolve(process.cwd(),n)),t.normalize(n)}function createSkippedResult(e){const{inputPath:t,absolutePath:n,code:r}=e,o=formatDirectoryForDisplay(n);return{status:"skipped",inputPath:t,absolutePath:n,displayPath:o,code:r,message:"ALREADY_IN_WORKSPACE"===r?`${o} is already accessible from the current workspace`:`${o} is already added`}}function createErrorResult(e){const{inputPath:t,code:n,message:r}=e;return{status:"error",inputPath:t,code:n,message:r}}function addDirectory(e){const t=e.trim();if(!t)return createErrorResult({inputPath:e,code:"EMPTY_PATH",message:"Directory path cannot be empty"});const n=resolveDirectoryPath(e);let r,o;try{r=w.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{w.accessSync(n,w.constants.R_OK),o=getCanonicalPath(n)}catch{return createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}const s=findSensitiveDirectoryConflict(o);if(s)return createErrorResult({inputPath:e,code:"SENSITIVE_DIRECTORY",message:`Cannot add ${formatDirectoryForDisplay(o)} because it overlaps sensitive path ${formatDirectoryForDisplay(s)}`});const a=getCanonicalPath(process.cwd());return isPathInDirectory(o,a)?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_IN_WORKSPACE"}):Nt.some(e=>isPathInDirectory(o,e)||isPathInDirectory(e,o))?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_ADDED"}):(Nt.push(o),{status:"added",inputPath:e,absolutePath:o,displayPath:formatDirectoryForDisplay(o)})}function getAdditionalDirectories(){return[...Nt]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Nt.findIndex(e=>areSamePath(t,e));return-1!==n&&(Nt.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Nt.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t)}var Ft=__esm({"src/utils/additional-dirs.ts"(){At(),Mt=new Set(["/etc","/root","/proc","/sys","/dev",t.join(h.homedir(),".ssh"),t.join(h.homedir(),".gnupg"),t.join(h.homedir(),".aws")]),Nt=[],__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`${h.platform()}-${h.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 w.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,o=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,a=[];return n>0&&a.push(`M ${n}`),r>0&&a.push(`A ${r}`),o>0&&a.push(`D ${o}`),s>0&&a.push(`?? ${s}`),a.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=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 Lt,_t,Ut,jt,Bt,zt,Wt=__esm({"src/utils/environment.ts"(){At(),Ft(),__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")}}),Ht=__esm({"src/auth/index.ts"(){At(),Rt(),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(h.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=It(),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 M.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await M.mkdir(o,{recursive:!0});let a={};try{const e=await M.readFile(s,"utf-8");a=JSON.parse(e)}catch{}a[e]=t,await M.writeFile(s,JSON.stringify(a,null,2)),await M.chmod(s,384)}async function remove(e){const t=r();try{const n=await M.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await M.unlink(t):(await M.writeFile(t,JSON.stringify(r,null,2)),await M.chmod(t,384))}catch{}}async function list2(){try{const e=await M.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")})(Lt||(Lt={}))}}),Gt=__esm({"src/utils/constants.ts"(){At(),Rt(),_t="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing",Ut='OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.',jt=">"}}),qt=__esm({"src/auth/anthropic.ts"(){At(),Ht(),Gt(),nr(),(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 U.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return U.createHash("sha256").update(e).digest("base64url")}function generateState(){return U.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),o=generateState();return{url:`https://claude.ai/oauth/authorize?${new URLSearchParams({code:"true",client_id:t,response_type:"code",redirect_uri:r,scope:"org:create_api_key user:profile user:inference",code_challenge:n,code_challenge_method:"S256",state:o}).toString()}`,verifier:e,state:o}}async function exchangeCodeForTokens2(e,o,s){const a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:s})});if(!a.ok){const e=await a.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:Yn.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const i=await a.json();await Lt.set("anthropic",{type:"oauth",refresh:i.refresh_token,access:i.access_token,expires:Date.now()+1e3*i.expires_in})}async function refreshAccessToken2(){const e=await Lt.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:Yn.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await Lt.remove("anthropic");const o=await r.json();return await Lt.set("anthropic",{type:"oauth",refresh:o.refresh_token,access:o.access_token,expires:Date.now()+1e3*o.expires_in}),o.access_token}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:Yn.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await Lt.remove("anthropic")}}}async function getValidAccessToken2(){const e=await Lt.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")})(Bt||(Bt={}))}});function isWordBoundary(e){return!e||0===e.length||zt.test(e)}function findPreviousWordBoundary(e,t){if(!e||t<=0)return 0;let n=Math.min(t,e.length);for(;n>0&&isWordBoundary(e[n-1]||"");)n--;for(;n>0&&!isWordBoundary(e[n-1]||"");)n--;return n}function findNextWordBoundary(e,t){if(!e)return 0;if(t>=e.length)return e.length;let n=Math.max(0,t);for(;n<e.length&&isWordBoundary(e[n]||"");)n++;for(;n<e.length&&!isWordBoundary(e[n]||"");)n++;return n}function deleteWordBackwards(e,t){if(!e||t<=0)return{text:e||"",cursor:0};const n=findPreviousWordBoundary(e,t);return{text:e.slice(0,n)+e.slice(t),cursor:n}}function clampCursor(e,t){return Math.max(0,Math.min(e,t))}function findLineStart(e,t){if(!e||t<=0)return 0;for(let n=Math.min(t,e.length)-1;n>=0;n--)if("\n"===e[n])return n+1;return 0}function findLineEnd(e,t){if(!e)return 0;if(t>=e.length)return e.length;for(let n=Math.max(0,t);n<e.length;n++)if("\n"===e[n])return n;return e.length}function moveCursorUp(e,t){if(!e)return 0;const n=findLineStart(e,t);if(0===n)return t;const r=t-n,o=n-1,s=findLineStart(e,o),a=o-s;return s+Math.min(r,a)}function moveCursorDown(e,t){if(!e)return 0;const n=findLineStart(e,t),r=findLineEnd(e,t);if(r===e.length)return t;const o=t-n,s=r+1,a=findLineEnd(e,s)-s;return s+Math.min(o,a)}function insertTextAt(e,t,n){const r=e||"",o=clampCursor(t,r.length);return{text:r.slice(0,o)+n+r.slice(o),cursor:o+n.length}}function deleteCharBefore(e,t){return!e||t<=0?{text:e||"",cursor:0}:{text:e.slice(0,t-1)+e.slice(t),cursor:t-1}}function deleteCharAt(e,t){return!e||t>=e.length?{text:e||"",cursor:t}:{text:e.slice(0,t)+e.slice(t+1),cursor:t}}var Vt,Kt,Jt,Yt,Qt,Zt,Xt,en,tn,nn,rn,on=__esm({"src/utils/text-navigation.ts"(){At(),zt=/\s|[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/,__name(isWordBoundary,"isWordBoundary"),__name(findPreviousWordBoundary,"findPreviousWordBoundary"),__name(findNextWordBoundary,"findNextWordBoundary"),__name(deleteWordBackwards,"deleteWordBackwards"),__name(clampCursor,"clampCursor"),__name(findLineStart,"findLineStart"),__name(findLineEnd,"findLineEnd"),__name(moveCursorUp,"moveCursorUp"),__name(moveCursorDown,"moveCursorDown"),__name(insertTextAt,"insertTextAt"),__name(deleteCharBefore,"deleteCharBefore"),__name(deleteCharAt,"deleteCharAt")}});function isWordLeftSequence(e){return!!Vt.has(e)||!!nn.test(e)}function isWordRightSequence(e){return!!Kt.has(e)||!!rn.test(e)}function isHomeSequence(e){return Jt.has(e)}function isEndSequence(e){return Yt.has(e)}function isForwardDeleteSequence(e){return Qt.has(e)}function isDeleteWordSequence(e){return Zt.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===Xt.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===Xt.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===Xt.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===Xt.CTRL_U}function isAltP(e){return tn.has(e)}function isCtrlKey({inputChar:e,key:t,letter:n,ctrlCode:r}){return!(!t.ctrl||e.toLowerCase()!==n.toLowerCase())||void 0!==r&&e.charCodeAt(0)===r}var sn=__esm({"src/utils/keyboard-sequences.ts"(){At(),Vt=new Set(["[1;3D","b","[1;5D","[1;9D","[5D"]),Kt=new Set(["[1;3C","f","[1;5C","[1;9C","[5C"]),Jt=new Set(["[H","[1~","[7~","OH"]),Yt=new Set(["[F","[4~","[8~","OF"]),Qt=new Set(["[3~"]),Zt=new Set(["",""]),Xt={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},en={ALT_P:112,ALT_P_NO_META:960},tn=new Set([String.fromCharCode(27,en.ALT_P),String.fromCharCode(en.ALT_P_NO_META),"[112;3u"]),nn=/^\x1b\[1;[359]D$/,rn=/^\x1b\[1;[359]C$/,__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(isAltP,"isAltP"),__name(isCtrlKey,"isCtrlKey")}});function processWordLeft(e,t){return{value:e,cursor:findPreviousWordBoundary(e,t),handled:!0}}function processWordRight(e,t){return{value:e,cursor:findNextWordBoundary(e,t),handled:!0}}function processLineStart(e,t){return{value:e,cursor:findLineStart(e,t),handled:!0}}function processLineEnd(e,t){return{value:e,cursor:findLineEnd(e,t),handled:!0}}function processDeleteWord(e,t){const n=deleteWordBackwards(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processDeleteToEnd(e,t){const n=findLineEnd(e,t);return{value:e.slice(0,t)+e.slice(n),cursor:t,handled:!0}}function processDeleteToStart(e,t){const n=findLineStart(e,t);return{value:e.slice(0,n)+e.slice(t),cursor:n,handled:!0}}function processForwardDelete(e,t){const n=deleteCharAt(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processBackspace(e,t){const n=deleteCharBefore(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processCursorLeft(e,t,n){return n?t<=0?{value:e,cursor:t,handled:!0}:{value:e,cursor:t-1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorRight(e,t,n){return n?t>=e.length?{value:e,cursor:t,handled:!0}:{value:e,cursor:t+1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorUp(e,t,n){return n?{value:e,cursor:moveCursorUp(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorDown(e,t,n){return n?{value:e,cursor:moveCursorDown(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCharacterInput(e,t,n){const r=n.replace(/[\x00-\x1F\x7F]|\x1b.*/g,"");if(0===r.length)return{value:e,cursor:t,handled:!1};const o=insertTextAt(e,t,r);return{value:o.text,cursor:o.cursor,handled:!0}}function processRawInput(e,t,n){return isWordLeftSequence(e)?processWordLeft(t,n):isWordRightSequence(e)?processWordRight(t,n):isHomeSequence(e)?processLineStart(t,n):isEndSequence(e)?processLineEnd(t,n):isCtrlA(e)?processLineStart(t,n):isCtrlE(e)?processLineEnd(t,n):isDeleteWordSequence(e)?processDeleteWord(t,n):isCtrlK(e)?processDeleteToEnd(t,n):isCtrlU(e)?processDeleteToStart(t,n):isForwardDeleteSequence(e)?processForwardDelete(t,n):{value:t,cursor:n,handled:!1}}function isIgnoredKey(e,t){return!(!t.ctrl||"c"!==e)||!!t.tab||!(!t.shift||!t.tab)}function processInkInput(e,t,n,r,o){const s=t;return s.meta&&t.leftArrow?processLineStart(n,r):s.meta&&t.rightArrow?processLineEnd(n,r):s.meta&&"b"===e?processWordLeft(n,r):s.meta&&"f"===e?processWordRight(n,r):t.ctrl&&"a"===e?processLineStart(n,r):t.ctrl&&"e"===e?processLineEnd(n,r):t.ctrl&&"w"===e?processDeleteWord(n,r):t.ctrl&&"k"===e?processDeleteToEnd(n,r):t.ctrl&&"u"===e?processDeleteToStart(n,r):t.leftArrow?processCursorLeft(n,r,o):t.rightArrow?processCursorRight(n,r,o):t.upArrow?processCursorUp(n,r,o):t.downArrow?processCursorDown(n,r,o):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!s.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}var an,cn,ln,dn=__esm({"src/components/text/input-handlers.ts"(){At(),on(),sn(),__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(){an||(an=!0,cn=[],ln=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&cn.push(t)},"earlyInputHandler"),process.stdin.on("data",ln))}function stopEarlyInputCapture(){an&&ln&&(process.stdin.off("data",ln),ln=null,an=!1)}function consumeBufferedInput(){const e=cn.join("");return cn=[],e}function hasBufferedInput(){return cn.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("[I")||e.startsWith("[O"))}var un=__esm({"src/utils/early-input-buffer.ts"(){At(),an=!1,cn=[],ln=null,__name(startEarlyInputCapture,"startEarlyInputCapture"),__name(stopEarlyInputCapture,"stopEarlyInputCapture"),__name(consumeBufferedInput,"consumeBufferedInput"),__name(hasBufferedInput,"hasBufferedInput"),__name(isControlSequenceToSkip,"isControlSequenceToSkip")}});function useCursorState({value:e,focus:t,showCursor:n}){const[r,o]=z((e||"").length),s=W(r),a=W(e);H(()=>{s.current=r},[r]),H(()=>{const i=a.current;if(a.current=e,e===i)return;if(!t)return;if(!n)return;const c=(e||"").length,l=(i||"").length;(Math.abs(c-l)>1||r>c)&&(o(c),s.current=c)},[e,t,n,r]);const i=G(e=>{o(e),s.current=e},[]);return{cursor:r,setCursor:i,cursorRef:s}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o}){const s=W(!1);H(()=>{if(!e)return;const a=process.stdin,i=__name(e=>{const s=processRawInput(e.toString(),t.current,n.current);if(!s.handled)return;o(!0);const a=clampCursor(s.cursor,s.value.length);r(s.value,a),setTimeout(()=>o(!1),0)},"handleRawInput");if(a.on("data",i),!s.current&&hasBufferedInput()){s.current=!0;const e=consumeBufferedInput();e&&i(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",i)}},[e,t,n,r,o])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){Z((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void a?.(n.current);const c=processInkInput(e,i,n.current,r.current,t);if(!c.handled)return;const l=clampCursor(c.cursor,c.value.length);s(c.value,l)},{isActive:e})}function useSyncedRef(e){const t=W(e);return H(()=>{t.current=e},[e]),t}var mn=__esm({"src/components/text/hooks.ts"(){At(),on(),dn(),un(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef")}});function renderPlaceholder(e,t){return t?0===e.length?ee.inverse(" "):ee.inverse(e[0])+ee.grey(e.slice(1)):ee.grey(e)}function renderValue(e,t,n){if(!n)return e;if(0===e.length)return ee.inverse(" ");let r="";for(let n=0;n<e.length;n++)n===t?"\n"===e[n]?r+=ee.inverse(" ")+"\n":r+=ee.inverse(e[n]):r+=e[n];return t===e.length&&(r+=ee.inverse(" ")),r}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(te(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",c=0,l=!0;for(const e of a){const t=te(e).length;if(c+t>(l?s:o)&&c>0&&(i+="\n"+r,c=n,l=!1),i+=e,c+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);c=te(t).length,l=!0}}return i}function getDisplayValue(e,t,n,r,o){const s=r&&o;return t&&0===e.length?renderPlaceholder(t,s):renderValue(e,n,s)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}var gn=__esm({"src/components/text/render-utils.ts"(){At(),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue")}});function createStdinUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n.current(r),t.current=r)}}function createInkUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n(r),t.current=r)}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:a,onCursorChange:i,prefix:c="",prefixColor:l}){const d=W(!1),u=useSyncedRef(e),m=useSyncedRef(s),{cursor:g,setCursor:p,cursorRef:h}=useCursorState({value:e,focus:n,showCursor:o});B.useEffect(()=>{i?.(g)},[g,i]);const f=G(createStdinUpdateHandler(p,u,m),[p,u,m]),y=G(()=>createInkUpdateHandler(p,u,s),[p,u,s])(),w=G(e=>{d.current=e},[]),E=G(()=>d.current,[]);useRawStdinHandler({focus:n,valueRef:u,cursorRef:h,onUpdate:f,setHandled:w}),useInkInputHandler({focus:n,showCursor:o,valueRef:u,cursorRef:h,isHandledByStdin:E,onUpdate:y,onSubmit:a});const{stdout:S}=Q(),k=S?.columns??80,v=getMaskedValue(e,r),b=wrapWithIndent(__name(()=>{if(!c)return"";if(!l)return c;const e={white:ne.white,green:ne.green,red:ne.red,blue:ne.blue,yellow:ne.yellow,cyan:ne.cyan,magenta:ne.magenta,gray:ne.gray,grey:ne.gray}[l];return e?e(c):c},"getColoredPrefix")()+getDisplayValue(v,t,g,o,n),k,c?.length??0);return B.createElement(K,{wrap:"wrap"},b)}var pn=__esm({"src/components/text/text-input.tsx"(){At(),mn(),gn(),on(),__name(createStdinUpdateHandler,"createStdinUpdateHandler"),__name(createInkUpdateHandler,"createInkUpdateHandler"),__name(TextInput,"TextInput")}});async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=re(n),s=await o.metadata();if(!s.width||!s.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const a=1200;let i,c,{width:l,height:d}=s;(l>a||d>a)&&(l>d?(d=Math.round(d*a/l),l=a):(l=Math.round(l*a/d),d=a)),t.includes("png")&&s.hasAlpha?(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=i.length;return{compressedBase64:i.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:u,compressionRatio:r/u}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}var hn,fn=__esm({"src/utils/image-compression.ts"(){At(),__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=hn[n];if(!r)return null;const o=a(t);if(!E(o))return null;const s=S(o).toString("base64");if(!s||0===s.length)return null;if(s.length>32e6)return null;const c=await compressImageForSharing(s,r);return c?{data:c.compressedBase64,mediaType:c.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 yn=__esm({"src/utils/clipboard-image.ts"(){At(),fn(),hn={".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 processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};let r,o,s=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");if(s=s.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){r=e.slice(0,t.index);const s=e.slice(t.index+t[0].length);if(n){const e=s.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(o=s.slice(0,e.index))}else o=s}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:s,textBeforePaste:r,pastedContent:o}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}var wn,En,Sn,kn,vn=__esm({"src/utils/bracketed-paste.ts"(){At(),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode")}});function getIcon(e){if(Sn[e])return Sn[e];const t=e.split(":")[0];return Sn[t]?Sn[t]:Sn.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(!kn){kn=!0;try{y.mkdirSync(wn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${En}\n════════════════════════════════════════════════════════════════\n\n`;y.appendFileSync(En,t,"utf-8")}catch{}}}function dlog(e,t){if("true"===process.env.DEBUG){showStartup();try{const n=formatTime(new Date),{category:r,text:o}=parseMessage(e);let s;if(r){s=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${o}`}else s=`${n} ${Sn.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",y.appendFileSync(En,s,"utf-8")}catch{}}}function dlogSection(e){if("true"===process.env.DEBUG){showStartup();try{const t=`\n──── ${e} ${"─".repeat(Math.max(0,50-e.length))}\n`;y.appendFileSync(En,t,"utf-8")}catch{}}}var bn,Cn=__esm({"src/utils/dlog.ts"(){At(),wn=e.join(p.homedir(),".commandcode","logs"),En=e.join(wn,"command.log"),Sn={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"),kn=!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 D.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();y.writeFileSync(t,JSON.stringify(e,null,2)),y.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!==bn)return bn;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),bn=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),bn=!0,!0;const e=await loadUserConfig();return(bn=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),bn}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error(Ut)}function getConfiguredModel(){try{const e=getConfigFile();return(parseJSON(y.readFileSync(e,"utf-8"))||{}).model??vt}catch{return vt}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}var Pn,Tn,An=__esm({"src/utils/user-config.ts"(){At(),Rt(),Ot(),Gt(),Cn(),In(),$n(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),bn=null,__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel")}}),xn=__esm({"src/components/anthropic-auth.tsx"(){At(),pn(),qt(),Gt(),yn(),vn(),An(),Pn=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=z(""),[s,a]=z(null),[i,c]=z(!1),[l,d]=z(null),[u,m]=z(!0),[g,p]=z(!1),[h,f]=z(!1);H(()=>{const{url:e,verifier:t,state:n}=Bt.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=G(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||h){if(!h||t.isPasteEnd){if(h&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}o(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}},[h]);Z((e,n)=>{if(n.escape&&t(),u&&!g)if("y"!==e&&"Y"!==e)"n"!==e&&"N"!==e||t();else{if(!s)return;oe(s.url).then(()=>{p(!0),m(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),p(!0),m(!1)})}});const w=__name(async()=>{if(r.trim()&&s&&!i){c(!0),d(null);try{const t=r.split("#")[0].trim();await Bt.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),c(!1),n&&n(t)}}},"handleSubmit");return u&&!g?B.createElement(V,{flexDirection:"column"},B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,color:"cyan"},"Anthropic Authentication")),B.createElement(V,{marginBottom:1},B.createElement(K,null,"Open the Anthropic auth page?",B.createElement(K,{dimColor:!0}," (Y/n)")))):B.createElement(V,{flexDirection:"column"},B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,color:"cyan"},"Anthropic Authentication")),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"After authorizing, copy the code and paste it below:")),l&&B.createElement(V,{marginBottom:1},B.createElement(K,{color:"red"},"Error: ",l)),B.createElement(V,null,B.createElement(K,null,"Authorization code: "),B.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:y,onSubmit:w,placeholder:"Paste code here..."})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function getProviderDisplayName(e){if(!e)return"None";const t=Tn[e];return t?.displayName||e}function getProviderConfig(e){return Tn[e]}function isInternalTeamFlagPresent(){return process.argv.includes(mt)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(gt)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(y.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(Tn).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var In=__esm({"src/utils/provider-config.ts"(){At(),Rt(),qt(),xn(),Ot(),$n(),Tn={"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:Pn,checkAuth:__name(async()=>!!await Bt.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(gt)}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 M.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,s=isInternalTeamFlagPresent();return isInternalTeamDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):s||o?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),"anthropic"):r}catch{return null}}function getIsExpandToolShortcut(e,t){const n=getIsTerminalIterm2();return!(!n||!e.shift||"O"!==t)||!(n||!e.ctrl||"o"!==t)}function formatTime2(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function formatTokens(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}var $n=__esm({"src/utils/utils.ts"(){At(),Ot(),Wt(),In(),An(),Rt(),__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=w.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var Rn=__esm({"src/utils/is-local-dev.ts"(){At(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":It()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return ot;case"local":return st;default:return rt}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(y.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var Dn=__esm({"src/utils/telemetry/config.ts"(){At(),Ot(),$n(),Dt(),Rn(),xt(),xt(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}}),Mn={};function getPackageJson(){const e=import.meta.url,t=l(e),o=r(t);return JSON.parse(S(n(o,"./../package.json"),"utf8"))}__export(Mn,{getPackageJson:()=>getPackageJson});var Nn,On,Fn,Ln,_n,Un,jn=__esm({"src/utils/package.ts"(){At(),__name(getPackageJson,"getPackageJson")}});function createAxiomExporter(){return new On({url:nt,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":it}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return Fn({[Ln]:at,[_n]: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 Nn({resource:t,spanProcessors:[new Un(e)],autoDetectResources:!1})}var Bn,zn,Wn,Hn,Gn,qn=__esm({"src/utils/telemetry/sdk-factory.ts"(){At(),xt(),Dn(),jn(),({NodeSDK:Nn}=se),({OTLPTraceExporter:On}=ae),({resourceFromAttributes:Fn}=ie),({ATTR_SERVICE_NAME:Ln,ATTR_SERVICE_VERSION:_n}=ce),({SimpleSpanProcessor:Un}=le),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function generateSessionId(){return`sess_${ge().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return _.createHash("sha256").update(e).digest("hex").substring(0,12)}function getCliVersion(){try{const e=getPackageJson();if("string"==typeof e.version&&""!==e.version.trim())return e.version}catch{}return"unknown"}function buildSessionAttributes(e){const{sessionId:t,projectPath:n,gitBranch:r,cliVersion:o}=e;return{"session.id":t,"session.start_time":(new Date).toISOString(),"session.project_hash":hashPath(n),"session.branch_hash":r?hashPath(r):"unknown","session.cli_version":o,"session.platform":`${p.platform()}-${p.arch()}`,"session.node_version":process.version}}function startSession(){Gn={},zn=null,Wn=null,Bn=generateSessionId(),Hn=Date.now();try{const e=de.getTracer(at),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:Bn,projectPath:n,gitBranch:r,cliVersion:t});zn=e.startSpan("session:cli",{attributes:o}),Wn=zn.spanContext(),zn.end()}catch{zn=null,Wn=null}return Bn}function getTraceId(){return Wn?Wn.traceId:null}function getSessionContext(){return Wn?de.setSpanContext(me.active(),Wn):me.active()}function endSession(e={}){const{status:t="success"}=e;if(Wn&&Hn){const e=de.getTracer(at),n=Date.now()-Hn,r=de.setSpanContext(me.active(),Wn),o=e.startSpan("session:end",{attributes:{"session.id":Bn||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Gn}},r);"error"===t?o.setStatus({code:ue.ERROR}):o.setStatus({code:ue.OK}),o.end()}zn=null,Wn=null,Bn=null,Hn=null,Gn={}}var Vn=__esm({"src/utils/telemetry/session.ts"(){At(),xt(),jn(),Wt(),Bn=null,zn=null,Wn=null,Hn=null,Gn={},__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:ue.ERROR}):e.setStatus({code:ue.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=de.getTracer(at),o=getSessionContext();return r.startSpan(t,{attributes:n},o)}function endSpan(e){const{span:t,status:n="success"}=e;setSpanStatus(t,n),t.end()}function recordError(e){const{span:t,error:n,additionalAttributes:r}=e;if(t.recordException(n),t.setStatus({code:ue.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 Kn=__esm({"src/utils/telemetry/spans.ts"(){At(),xt(),Vn(),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});function isSecretKey(e){const t=e.toLowerCase();return ct.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return lt.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString(e){return e.length<=dt?e:`${e.substring(0,dt-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>dt?truncateString(t):t;if("number"==typeof t||"boolean"==typeof t)return t;if("object"==typeof t){if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map((e,t)=>sanitizeValue({value:e,key:String(t),visited:r}));const e={};for(const[n,o]of Object.entries(t))e[n]=sanitizeValue({value:o,key:n,visited:r});return e}return"[Unsupported]"}function sanitizeParams(e){const t=new WeakSet;t.add(e);const n={};for(const[r,o]of Object.entries(e))n[r]=sanitizeValue({value:o,key:r,visited:t});return n}function sanitizeEndpoint(e){return e.split("?")[0]}var Jn=__esm({"src/utils/telemetry/sanitization.ts"(){At(),xt(),__name(isSecretKey,"isSecretKey"),__name(isContentKey,"isContentKey"),__name(safeStringify,"safeStringify"),__name(truncateString,"truncateString"),__name(normalizeError,"normalizeError"),__name(sanitizeErrorForTelemetry,"sanitizeErrorForTelemetry"),__name(sanitizeValue,"sanitizeValue"),__name(sanitizeParams,"sanitizeParams"),__name(sanitizeEndpoint,"sanitizeEndpoint")}});function createTrackingHandle(e){const{span:t,startTime:n,durationAttr:r,statusAttr:o}=e;return{span:t,end:__name(e=>{const s=Date.now()-n;if(t.setAttribute(r,s),"status"in e)t.setAttribute(o,e.status),e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r,errorBody:o}=e;if(t.setAttribute("http.status_code",n),o){const e="string"==typeof o?o:safeStringify(o);t.setAttribute("http.response_body",e.substring(0,ut))}r?(recordError({span:t,error:r}),endSpan({span:t,status:"error"})):endSpan({span:t,status:n>=400?"error":"success"})}},"end")}}function trackToolStart(e){const{toolName:t,params:n}=e;return createTrackingHandle({span:createSpan({name:`tool:${t}`,attributes:{"tool.name":t,"tool.params":safeStringify(n?sanitizeParams(n):{})}}),startTime:Date.now(),durationAttr:"tool.duration_ms",statusAttr:"tool.status"})}function trackError(e){const{error:t,context:n}=e,r=normalizeError(t),{component:o,heading:s,code:a,...i}=n,c={"error.type":r.name,"error.message":r.message,"error.component":o,"error.heading":s};void 0!==a&&(c["error.code"]=String(a));for(const[e,t]of Object.entries(i))null!=t&&(c[e]="object"==typeof t?safeStringify(t):String(t));const l=createSpan({name:`error:${r.name}`,attributes:c});recordError({span:l,error:r}),l.end()}function trackAPICallStart(e){const{method:t,endpoint:n}=e,r=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${r}`,attributes:{"http.method":t,"http.url":r}}),startTime:Date.now(),durationAttr:"http.duration_ms",statusAttr:"http.status"})}function getSupportId(){const e=getTraceId();return e?`req_${e}`:"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,nodeVersion:s,platform:a,arch:i}=e,c={"whoami.node_version":s,"whoami.platform":a,"whoami.arch":i,"whoami.os":`${a}-${i}`};t&&(c["whoami.user_name"]=t),n&&(c["whoami.user_id"]=n),r&&(c["whoami.org_login"]=r),o&&(c["whoami.org_id"]=o),endSpan({span:createSpan({name:"whoami",attributes:c}),status:"success"})}var Yn,Qn,Zn,Xn=__esm({"src/utils/telemetry/events.ts"(){At(),Kn(),Vn(),xt(),Jn(),Jn(),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(trackError,"trackError"),__name(trackAPICallStart,"trackAPICallStart"),__name(getSupportId,"getSupportId"),__name(systemInfo,"systemInfo")}}),er=__esm({"src/utils/telemetry/components.ts"(){At(),Yn={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(Zn)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(Qn=createTelemetrySDK()).start(),Zn=!0,!0}catch{return Qn=null,Zn=!1,!1}}async function shutdownTelemetry(){if(Qn&&Zn)try{endSession(),await Qn.shutdown()}catch{}finally{Qn=null,Zn=!1}}function shutdownTelemetrySync(){if(Zn)try{endSession()}catch{}}function isTelemetryInitialized(){return Zn}var tr,nr=__esm({"src/utils/telemetry/telemetry.ts"(){At(),qn(),Dn(),Vn(),Kn(),Xn(),er(),Qn=null,Zn=!1,__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized")}});function getTokenFilePath(){return e.join(h.homedir(),".commandcode",tr)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await D.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 D.mkdir(r,{recursive:!0}),await D.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await D.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 rr,or=__esm({"src/mcp/auth/token-storage.ts"(){At(),Rt(),Cn(),tr="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")}});function fetchWithTimeout(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),rr);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var sr,ar,ir=__esm({"src/mcp/fetch.ts"(){At(),rr=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),cr={};function generateRandomString(e){return _.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:_.createHash("sha256").update(e).digest("base64url")}}function escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function startCallbackServer(e,t){return new Promise((n,r)=>{let o=null,s=null;const a=new Promise((e,t)=>{o=e,s=t}),i=pe.createServer((n,r)=>{const a=new d(n.url||"/",`http://${ar}:${e}`);if("/callback"===a.pathname){const e=a.searchParams.get("code"),n=a.searchParams.get("error"),i=a.searchParams.get("error_description");if(a.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'),s?.(new Error("OAuth state parameter mismatch"));else if(n){const e=escapeHtml(i||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`),s?.(new Error(i||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'),o?.(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'),s?.(new Error("No authorization code received")))}else r.writeHead(404),r.end("Not Found")});i.on("error",r),i.listen(e,ar,()=>{n({server:i,getCode:__name(()=>a,"getCode")})})})}async function exchangeCodeForTokens(e,t,n,r){const o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r,client_id:e.clientId,code_verifier:n});e.clientSecret&&o.set("client_secret",e.clientSecret);const s=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!s.ok){const e=await s.text();throw new Error(`Token exchange failed: ${s.status} ${e}`)}const a=await s.json();return{accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:a.expires_in?Date.now()+1e3*a.expires_in:void 0,tokenType:a.token_type,scope:a.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 o=await r.json();return{accessToken:o.access_token,refreshToken:o.refresh_token||t,expiresAt:o.expires_in?Date.now()+1e3*o.expires_in:void 0,tokenType:o.token_type,scope:o.scope}}async function performOAuthFlow(e,t,n){const r=n?.port||sr,o=n?.timeout||12e4,s=n?.onStatus||(()=>{});let a=null;try{const n=generatePKCE(),i=generateRandomString(32),c=`http://${ar}:${r}/callback`;s("Starting authentication server...");const{server:l,getCode:u}=await startCallbackServer(r,i);a=l;const m=new d(t.authorizationUrl);if(m.searchParams.set("response_type","code"),m.searchParams.set("client_id",t.clientId),m.searchParams.set("redirect_uri",c),m.searchParams.set("state",i),m.searchParams.set("code_challenge",n.challenge),m.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&m.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))m.searchParams.set(e,n);s("Opening browser for authentication..."),await oe(m.toString()),s("Waiting for authorization...");const g=u();let p;const h=new Promise((e,t)=>{p=setTimeout(()=>t(new Error("Authentication timed out")),o)}),f=await Promise.race([g,h]);clearTimeout(p),s("Exchanging authorization code for tokens...");const y=await exchangeCodeForTokens(t,f,n.verifier,c);return await storeTokens(e,y),s("Authentication successful!"),{success:!0,tokens:y}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{a&&a.close()}}function createRefreshCallback(e){return t=>refreshAccessToken({config:e,refreshToken:t})}__export(cr,{DEFAULT_OAUTH_CALLBACK_PORT:()=>sr,LOCALHOST_IP:()=>ar,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var lr,dr,ur,mr,gr,pr,hr,fr,yr,wr,Er,Sr,kr,vr,br,Cr=__esm({"src/mcp/auth/oauth-flow.ts"(){At(),or(),ir(),sr=8085,ar="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")}}),Pr=__esm({"src/components/vscode-context/ipc-client.ts"(){At(),Cn(),lr=t.join(h.homedir(),".commandcode","ide"),dr=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),ur=__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"),mr=__name((e,t,n=ur)=>{const r=new Map;for(const t of e)r.set(t.session.pid,t);let o=t;for(let e=0;e<10&&null!==o;e++){const e=r.get(o);if(e)return e;o=n(o)}return null},"findAncestorSession"),gr=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),pr=__name((e,n)=>{try{w.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{w.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),hr=__name((e,n={})=>{const{sessionDir:r=lr,parentPidFn:o=ur,startPid:s=process.ppid}=n;try{if(!w.existsSync(r))return null;const n=`${e}-`,a=w.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),i=[];for(const e of a)try{const n=t.join(r,e),o=JSON.parse(w.readFileSync(n,"utf-8"));if(!dr(o.pid)){pr(n,r);continue}i.push({session:o,file:e})}catch{continue}if(0===i.length)return null;const c=mr(i,s,o);if(c)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:c.session.socketPath,ideName:c.session.ideName}),c.session.socketPath;const l=process.cwd();let d=null,u=0;for(const{session:e}of i)for(const n of e.workspaceFolders)(l===n||l.startsWith(n+t.sep))&&n.length>u&&(d=e,u=n.length);return d&&dlog("[VSCode:IPC] Discovered session via workspace match",{socketPath:d.socketPath,ideName:d.ideName}),d?.socketPath??null}catch{return null}},"discoverSocketPath"),fr=__name(()=>{const e=gr();return e?hr(e):null},"resolveSocketPath"),yr=__name(()=>({type:"request",id:j(),payload:{action:"getContext"}}),"createContextRequest"),wr=__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"),Er=__name((e,t)=>{try{const n=JSON.parse(e.toString());return wr(n)?"response"!==n.type||n.id!==t?null:n.payload:(dlog("[VSCode:IPC] Invalid message structure"),null)}catch{return null}},"parseResponse"),Sr=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??fr()}get isConnected(){return this.connected}async connect(e=2e3){if(!this.socketPath)return dlog("[VSCode:IPC] No socket path resolved"),!1;const t=this.socketPath;return dlog("[VSCode:IPC] Connecting to socket",{path:t,timeout:e}),new Promise(n=>{const r=__name(()=>{this.socket?.off("error",o)},"cleanup"),o=__name(e=>{clearTimeout(s),r(),this.connected=!1,dlog("[VSCode:IPC] Connection error",{error:e.message}),n(!1)},"handleError"),s=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),r(),this.socket?.destroy(),n(!1)},e);try{this.socket=fe.connect(t),this.socket.on("connect",()=>{clearTimeout(s),r(),this.connected=!0,dlog("[VSCode:IPC] Connected successfully"),this.socket.on("close",()=>{this.connected=!1}),this.socket.on("error",()=>{this.connected=!1}),n(!0)}),this.socket.on("error",o)}catch(e){clearTimeout(s),r(),dlog("[VSCode:IPC] Connection exception",{error:e}),n(!1)}})}async getContext(e=5e3){const t=this.socket;if(!t||!this.connected)return dlog("[VSCode:IPC] Cannot get context - not connected"),null;const n=yr();return new Promise(r=>{const o=__name(()=>{t.off("data",a),t.off("error",i)},"cleanup"),s=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),o(),r(null)},e),a=__name(e=>{clearTimeout(s),o();const t=Er(e,n.id);t||dlog("[VSCode:IPC] Invalid response received"),r(t)},"handleData"),i=__name(e=>{clearTimeout(s),o(),dlog("[VSCode:IPC] Socket error during request",{error:e.message}),r(null)},"handleError");t.on("data",a),t.on("error",i);try{t.write(JSON.stringify(n)+"\n")}catch(e){clearTimeout(s),o(),dlog("[VSCode:IPC] Failed to send request",{error:e}),r(null)}})}disconnect(){this.socket&&(dlog("[VSCode:IPC] Disconnecting"),this.socket.end(),this.socket=null,this.connected=!1)}static async isAvailable(e=1e3){const t=new _VSCodeIPCClient;if(!t.socketPath)return dlog("[VSCode:IPC] Availability check",{available:!1,reason:"no socket path"}),!1;const n=await t.connect(e);return t.disconnect(),dlog("[VSCode:IPC] Availability check",{available:n}),n}}}}),Tr={};function getVsixPath(){try{const e=t.dirname(l(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return w.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),Sr.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await kr(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp(`${vr}@([\\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 kr(`${e} --install-extension "${t}" --force`,{timeout:3e4}),dlog(`[IDE] Extension installed for ${e}`),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function installExtensionAsync(e){e&&installExtension(e).catch(()=>{})}async function isAutoInstallEnabled(){try{return!1!==(await loadUserConfig()).autoInstallExtension}catch{return!0}}async function ensureExtensionInstalled(){if(process.env.CI)return;const e=gr();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:ee.green("✔"),installed:ee.green("✔"),needs_reload:ee.yellow("◌"),failed:ee.red("✖"),not_in_ide:ee.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=>ee.dim(` ${e}`)),""]}async function runIDESetup(){const e=gr(),t=e?br[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new Sr,r=await n.connect(500);if(n.disconnect(),r)return{status:"connected",ide:t};const{installed:o}=await checkInstalled(e);return o?{status:"needs_reload",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:(await installExtension(e)).success?{status:"installed",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:{status:"failed",ide:t,details:[`Make sure "${e}" is available in your PATH.`,"Then run /ide to retry installation."]}}__export(Tr,{detectIDE:()=>gr,ensureExtensionInstalled:()=>ensureExtensionInstalled,formatSetupResult:()=>formatSetupResult,getExtensionStatus:()=>getExtensionStatus,installExtension:()=>installExtension,installExtensionAsync:()=>installExtensionAsync,isAutoInstallEnabled:()=>isAutoInstallEnabled,runIDESetup:()=>runIDESetup});var Ar=__esm({"src/utils/ide-installer.ts"(){At(),Pr(),Cn(),An(),kr=ye($),vr="commandcode.commandcode-vscode",__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled"),br={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"},__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup")}});At(),At();var xr=process.argv.includes("-d")||process.argv.includes("--debug");xr&&(process.env.DEBUG="true"),xr||(process.removeAllListeners("warning"),process.on("warning",()=>{})),At(),At(),nr();var{red:Ir,yellow:$r,dim:Rr}=ee,Dr=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:o=!0,skipTelemetry:s=!1}=e;if(n){if(s||trackError({error:sanitizeErrorForTelemetry({error:n,label:"cli_error"}),context:{component:Yn.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Ee.error} ${Ir(t)}`),console.log(`${Ee.error} ${Ir("ERROR →")} ${n.name}`),console.log(`${Ee.info} ${Ir("REASON →")} ${n.message}`),console.log(`${Ee.info} ${Ir("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Ee.info} ${Rr(`Request ID: ${e}`)}`),console.log(`${Rr(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Ee.warning} ${$r(t)}\n`);if(!o)return!1;process.exit(0)}},"handleError");function handleUnhandledErrors(){process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:Yn.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),Dr({heading:we`CRITICAL: Unhandled Promise Rejection!
|
|
3
|
-
This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:t,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})}),process.on("uncaughtException",e=>{trackError({error:sanitizeErrorForTelemetry({error:e,label:"uncaught_exception"}),context:{component:
|
|
4
|
-
This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}async function findAvailablePort(e=5959,t=10){for(let n=0;n<t;n++){const t=e+n;if(await checkPortAvailable(t))return t}throw new Error(`No available port found after ${t} attempts starting from port ${e}`)}async function checkPortAvailable(e){return new Promise(t=>{const n=he.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}nr(),__name(handleUnhandledErrors,"handleUnhandledErrors"),At(),At(),Rt(),At(),At(),Rt(),At(),At(),At(),At(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable");var Mr=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}};function createAuthServer(e,t){let n,r;const o=new Promise((e,t)=>{n=e,r=t}),s=pe.createServer((e,o)=>{const a=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],i=e.headers.origin||"",c=a.includes(i)?i:a[0];if(o.setHeader("Access-Control-Allow-Origin",c),o.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type"),o.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return o.writeHead(204),void o.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return o.writeHead(404),void o.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return o.writeHead(405),void o.end(JSON.stringify(e))}let l="";e.on("data",t=>{l+=t.toString(),l.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(l);if(e.error){const t=e,n={success:!0};return o.writeHead(200),o.end(JSON.stringify(n)),"access_denied"===t.error?r(new Mr(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void s.close()}const a=e;if(!(a.apiKey&&a.state&&a.userId&&a.userName&&a.keyName)){const e={success:!1,error:"Missing required fields"};return o.writeHead(400),void o.end(JSON.stringify(e))}if(a.state!==t){const e={success:!1,error:"Invalid state token"};return o.writeHead(403),void o.end(JSON.stringify(e))}const i={success:!0};o.writeHead(200),o.end(JSON.stringify(i)),n(a),s.close()}catch{const e={success:!1,error:"Invalid JSON"};o.writeHead(400),o.end(JSON.stringify(e))}}),e.on("error",()=>{o.writeHead(500),o.end(JSON.stringify({success:!1,error:"Request error"}))})});return s.on("error",e=>{r(e)}),s.listen(e,"127.0.0.1"),{server:s,waitForCallback:o}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}function generateStateToken(){return _.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await oe(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:Yn.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(It()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer"),Dt(),Ot(),nr(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl");var Nr=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}};async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await D.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 D.writeFile(n,r,{mode:384}),await D.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await D.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}function getApiBaseUrl(){const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials"),At(),__name(getApiBaseUrl,"getApiBaseUrl"),Rt(),nr();var Or=12e4;async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${ht.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:Yn.AUTH_FLOW,heading:"API key validation network error"}}),process.env.DEBUG&&console.error("API key validation network error:",e),{valid:!1,error:"network_error"}}}function sanitizeApiKey(e){const t=String.fromCharCode(27),n=e.replaceAll(t+"[200~","").replaceAll(t+"[201~","").replaceAll("[200~","").replaceAll("[201~","");return Array.from(n).filter(e=>{const t=e.charCodeAt(0);return t>31&&127!==t}).join("").trim()}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:o=Or}=e,[s,a]=z("initializing"),[i,c]=z("Starting authentication..."),[l,d]=z(""),[u,m]=z(null),g=W(null),p=W(!1),h=W(!1),f=W(null),y=W(t),w=W(n),E=W(r);H(()=>{y.current=t,w.current=n,E.current=r});const S=G(()=>{f.current&&(clearTimeout(f.current),f.current=null),g.current&&(stopServer(g.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),g.current=null)},[]),k=G(()=>{h.current||(h.current=!0,p.current=!0,S(),E.current())},[S]),v=G((e,t)=>{h.current||(h.current=!0,S(),y.current(e,t))},[S]),b=G((e,t)=>{h.current||(h.current=!0,S(),w.current(e,t))},[S]),C=G(async e=>{const t=sanitizeApiKey(e);if(!t)return;a("validating"),c("Validating API key...");const n=await validateApiKey(t);if(p.current)return;if(h.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return a("invalid_key"),c(e),void(f.current=setTimeout(()=>{p.current||h.current||(a("manual_entry"),c("Paste a valid API key below.")),f.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(h.current)return;await storeCredentials(e),a("success"),v(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:Yn.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),c("Failed to save API key. Please try again."),a("manual_entry")}},[v]);return H(()=>{let e=!0;return __name(async()=>{if(!p.current)try{const t=await findAvailablePort(5959,10);if(!e||p.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);m(r);const{server:s,waitForCallback:i}=createAuthServer(t,n);if(g.current=s,!e||p.current)return void await stopServer(s);a("waiting_browser"),c("Opening browser for authentication...");const l=await openBrowser(r);if(!e||p.current)return;if(!l)return S(),c("Could not open browser. Paste your API key below."),void a("manual_entry");c("Complete login in your browser...");const d=new Promise((e,t)=>{setTimeout(()=>{t(new Nr("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([i,d]);if(!e||p.current)return;if(h.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(h.current)return;if(await storeCredentials(n),!e||p.current||h.current)return;a("browser_success"),v(n,"browser")}catch(t){if(h.current)return;if(!e||p.current)return;if(t instanceof Mr)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:Yn.AUTH_FLOW,heading:"Authorization denied by user"}}),a("denied"),void b("denied","Authorization denied by user.");S(),t instanceof Nr&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:Yn.AUTH_FLOW,heading:"Browser auth timed out"}}),c("Browser auth timed out. Paste your API key below.")):(trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_failed"}),context:{component:Yn.AUTH_FLOW,heading:"Browser auth failed"}}),c("Browser auth failed. Paste your API key below.")),a("manual_entry")}}catch(t){if(h.current)return;if(!e||p.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:Yn.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),S(),a("manual_entry"),c("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,S()}},[o,v,b,S]),{authState:s,statusMessage:i,browserUrl:u,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:C,cancel:k,hasCompleted:h.current}}function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){switch(e){case"waiting_browser":return"Authorize in browser, or paste API key here";case"invalid_key":return"That key was invalid. Try again.";default:return"Paste your API key and press Enter"}}function getAuthUrlLabel(e){return"waiting_browser"===e?"Authenticating via:":"Get your API key from:"}__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow"),At(),pn(),Rt(),Dt(),At(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel");var Fr=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const a=__name(()=>{switch(e){case"initializing":case"waiting_browser":case"validating":default:return B.createElement(De,{type:"dots"});case"browser_success":case"success":return B.createElement(K,{color:"green"},Se.tick);case"denied":case"invalid_key":return B.createElement(K,{color:"red"},Se.cross);case"manual_entry":return B.createElement(K,{color:"yellow"},Se.arrowDown);case"error":return B.createElement(K,{color:"red"},Se.warning)}},"getStatusIcon"),i=__name(()=>getAuthStatusColor(e),"getStatusColor");if("browser_success"===e||"success"===e||"denied"===e)return null;const c="initializing"===e||"waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,l=n&&("waiting_browser"===e||"manual_entry"===e);return B.createElement(V,{flexDirection:"column",paddingY:1},B.createElement(V,{marginBottom:1},B.createElement(V,{marginRight:1},a()),B.createElement(K,{color:i()},t)),c&&B.createElement(V,{flexDirection:"column"},B.createElement(V,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?"yellow":"gray",paddingX:1},B.createElement(K,{dimColor:!0},"API Key: "),B.createElement(V,{flexGrow:1},B.createElement(TextInput,{value:r,onChange:o,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},getAuthHelpText(e))),l&&B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,{dimColor:!0},getAuthUrlLabel(e)),B.createElement(K,{color:"cyan",dimColor:!0},n||getStudioAuthUrl(It())))),"validating"===e&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"initializing"===e||"invalid_key"===e)&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Ctrl+C to cancel")))},"AuthFlowUI"),Lr=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a,cancel:i}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return Z((e,t)=>{t.ctrl&&"c"===e&&i()}),B.createElement(Fr,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey");function heading({text:e,sub:t,dim:n,green:r}){const o=t?` ${t}`:"";return r?`${ne.bgGreen(ne.black(` ${e} `))}${o}`:n?`${ne.bgBlack(ne.white(` ${e} `))}${o}`:`${ne.bold(ne.bgCyan(ne.black(` ${e} `)))}${o}`}async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=Bt.createAuthorizationUrl(),r=await $e({message:"Open the Anthropic auth page?"});if(xe(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await oe(e),console.log(),console.log(ne.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(ne.dim(" Open this URL in your browser:")),console.log(),console.log(ne.cyan(` ${e}`)),console.log(),console.log(ne.yellow(" Copy your authorization code and paste it below.")),console.log());const o=await Re({message:"Paste your authorization code:",mask:"*"});if(xe(o))return{success:!1,error:"No API key provided"};if(!o.trim())return{success:!1,error:"No authorization code provided"};const s=o.split("#")[0].trim();return await Bt.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}Gt(),Dt(),At(),__name(heading,"heading"),In(),An(),At(),qt(),__name(performAnthropicAuth,"performAnthropicAuth"),At();var _r=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},Ur=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 M.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=Me("Checking authentication status...").start();try{const t=It(),n=await checkAuthStatus(t);n.error&&(e.fail(ne.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(ne.red("Not authenticated")),console.log(""),console.log(`${ne.dim("Run")} ${ne.cyan("cmd auth login")} ${ne.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${ne.green(Se.tick)} ${ne.bold("Authenticated")} with ${ne.cyan("Command Code")}`),n.userName&&console.log(`${ne.dim("Logged in as")} ${ne.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(ne.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}At(),Rt(),Ot(),Dt(),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(getUserName,"getUserName"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction");var jr=new be("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction),Br=__name(({message:e})=>B.createElement(B.Fragment,null,B.createElement(K,{color:"cyan"},B.createElement(De,{type:"dots"})),B.createElement(K,null," ",e)),"LoadingIndicator"),zr=__name(({message:e})=>B.createElement(B.Fragment,null,B.createElement(K,{color:"green"},Se.tick),B.createElement(K,null," ",e)),"SuccessIndicator"),Wr=__name(({children:e})=>B.createElement(V,{flexDirection:"column"},B.createElement(K,null," "),B.createElement(V,null,e)),"StatusContainer");function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,a]=z("loading"),[i,c]=z(null);return H(()=>{n().then(e=>{c(e),a(o?"success":"done")})},[n,o]),H(()=>{if("done"===s&&null!==i&&r(i),"success"===s&&null!==i){const e=setTimeout(()=>r(i),100);return()=>clearTimeout(e)}},[s,i,r]),"done"===s?null:B.createElement(Wr,null,"loading"===s?B.createElement(Br,{message:e}):B.createElement(zr,{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 ${ne.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${ne.green(Se.tick)} ${ne.bold("Already logged in")}${t}`,"",`${ne.dim("Run")} ${ne.cyan("cmd")} ${ne.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${ne.green(Se.tick)} ${ne.bold("Logged in")}${n}`,"",`${ne.dim("API key stored in")} ${ne.cyan(`~/.commandcode/${t}`)}`,`${ne.dim("Run")} ${ne.cyan("cmd")} ${ne.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 Ur(e.message):isLoginCancelled(e)?new _r(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 _r||e instanceof Ur}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),Pe.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await Ae({message:"Select provider",options:e});if(xe(t))throw Te(`${Se.cross} No provider selected.`),new _r("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){Te(`${Se.cross} ${e}`)}function showAnthropicAuthNote(){Ie("Command Code authentication complete. Now authenticating with Anthropic...")}function printMessage(e){console.log(""),console.log(e),console.log("")}function renderTaskWithSpinner(e,t,n,r=!0){return new Promise(o=>{const s=__name(e=>{a(),o(e)},"handleComplete"),{unmount:a}=Y(B.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:s,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=Y(B.createElement(Lr,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__name(isGenericUserName,"isGenericUserName"),__name(isGenericUserNameForOutro,"isGenericUserNameForOutro"),__name(formatUserDisplay,"formatUserDisplay"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(isLoginSuccess,"isLoginSuccess"),__name(isLoginDenied,"isLoginDenied"),__name(isLoginCancelled,"isLoginCancelled"),__name(createLoginError,"createLoginError"),__name(processLoginResult,"processLoginResult"),__name(needsProviderSelection,"needsProviderSelection"),__name(getDefaultProvider,"getDefaultProvider"),__name(isAnthropicProvider,"isAnthropicProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage,"getErrorMessage"),__name(showAuthIntro,"showAuthIntro"),__name(promptProviderSelection,"promptProviderSelection"),__name(selectProvider,"selectProvider"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(showAnthropicAuthNote,"showAnthropicAuthNote"),__name(printMessage,"printMessage"),__name(renderTaskWithSpinner,"renderTaskWithSpinner"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow");var Hr=__name(({env:e,onComplete:t})=>{const[n,r]=z("checking"),[o,s]=z(null);return H(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),H(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),B.createElement(Wr,null,"checking"===n&&B.createElement(Br,{message:"Checking authentication status..."}),"logged_in"===n&&B.createElement(zr,{message:"Authenticated"}),"not_logged_in"===n&&B.createElement(zr,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=Y(B.createElement(Hr,{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=It(),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(`${Se.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleAnthropicAuth,"handleAnthropicAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var Gr=new be("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction);async function safeRemoveFile(e,t){try{return await M.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"}}}At(),At(),Ot(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout");var qr=__name(()=>B.createElement(B.Fragment,null,B.createElement(K,{color:"cyan"},B.createElement(De,{type:"dots"})),B.createElement(K,null," Logging out...")),"LoadingIndicator"),Vr=__name(()=>B.createElement(B.Fragment,null,B.createElement(K,{color:"green"},Se.tick),B.createElement(K,null," Logged out")),"SuccessIndicator"),Kr=__name(({errorMessage:e})=>B.createElement(B.Fragment,null,B.createElement(K,{color:"red"},Se.cross),B.createElement(K,{color:"red"}," Logout failed: ",e)),"ErrorIndicator"),Jr=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return B.createElement(qr,null);case"success":return B.createElement(Vr,null);case"error":return B.createElement(Kr,{errorMessage:t})}},"StatusDisplay"),Yr=__name(({onComplete:e})=>{const[t,n]=z("loading"),[r,o]=z(""),[s,a]=z(null);return H(()=>{performLogout().then(e=>{a(e),e.success?n("success"):(o(e.error||"Unknown error"),n("error"))})},[]),H(()=>{if(("success"===t||"error"===t)&&s){const t=setTimeout(()=>e(s),100);return()=>clearTimeout(t)}},[t,s,e]),B.createElement(V,{flexDirection:"column"},B.createElement(K,null," "),B.createElement(V,null,B.createElement(Jr,{status:t,errorMessage:r})))},"LogoutSpinner");function printWarnings(e){e.length>0&&(console.warn(ne.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(ne.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=Y(B.createElement(Yr,{onComplete:n=>{t(),e(n)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction");var Qr=new be("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction);Dt(),Ot(),new be("auth").description("Manage authentication with Command Code").addCommand(Gr).addCommand(Qr).addCommand(jr),At(),Rt();var Zr="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",Xr="\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 eo=getMaxLineWidth(Zr),to=getMaxLineWidth(Xr),no=eo+1,ro=to+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var oo=__name(e=>{const t=e??getTerminalWidth();return t>=no?Zr:t>=ro?Xr:so},"getResponsiveCommandLogo"),so="⌘ CMD\n",ao=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),io=__name(e=>{console.log(ee.white(oo())),console.log(""),console.log(`${Se.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),co=__name(async e=>{const t=ve.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"),lo=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.log(""),console.log(`${Se.cross} Authentication failed. Please try again with: cmd login`),!1)}catch{return!1}},"attemptLogin"),uo=__name(()=>{console.log(""),console.log(`${Se.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),mo=__name(()=>{console.log(""),console.log(`${Se.info} Authentication cancelled. You can authenticate later with: cmd login`)},"showCancelledMessage");async function checkAuthAndPromptLogin(){try{if(await getAuthKey())return!0;io($t());const{answer:e,cancelled:t}=await co(`Would you like to sign in now? ${ee.dim("(y/n)")}: `);return t?(mo(),!1):ao(e)?(console.log(""),lo()):(uo(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin"),At(),At(),Rt(),At();var go=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))}};At(),At();var po=class _APIError extends Error{static{__name(this,"APIError")}status;headers;error;code;param;type;request_id;constructor(e,t,n,r){super(_APIError.makeMessage(e,t,n)),this.status=e,this.headers=r,this.request_id=r?.["lb-request-id"];const o=t;this.error=o,this.code=o?.code,this.status=o?.status}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e)return new ho({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new fo(e,o,n,r);case 401:return new yo(e,o,n,r);case 403:return new wo(e,o,n,r);case 404:return new Eo(e,o,n,r);case 409:return new So(e,o,n,r);case 422:return new ko(e,o,n,r);case 429:return new vo(e,o,n,r);default:return e>=500?new bo(e,o,n,r):new _APIError(e,o,n,r)}}},ho=class extends po{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)}},fo=class extends po{static{__name(this,"BadRequestError")}status=400},yo=class extends po{static{__name(this,"AuthenticationError")}status=401},wo=class extends po{static{__name(this,"PermissionDeniedError")}status=403},Eo=class extends po{static{__name(this,"NotFoundError")}status=404},So=class extends po{static{__name(this,"ConflictError")}status=409},ko=class extends po{static{__name(this,"UnprocessableEntityError")}status=422},vo=class extends po{static{__name(this,"RateLimitError")}status=429},bo=class extends po{static{__name(this,"InternalServerError")}};nr();var Co=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=await this.buildHeaders({headers:e.headers}),o=trackAPICallStart({method:e.method,endpoint:t});let s;try{s=await this.makeRequest({url:n,options:e,headers:r})}catch(e){const t=new ho({cause:e instanceof Error?e:void 0});throw o.end({statusCode:0,error:t}),t}if(!s.ok){const{error:e}=await this.handleErrorResponse({response:s});throw o.end({statusCode:s.status,error:e}),e}return o.end({statusCode:s.status}),e.stream?s.body:s.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const s=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return o&&clearTimeout(o),s}catch(e){throw o&&clearTimeout(o),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};return e.headers.forEach((e,t)=>{n[t]=e}),{error:po.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"})}};qt(),At(),qt(),At(),At(),At(),At();var Po=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.array(g.string()).optional(),metadata:g.record(g.string(),g.any()).optional(),"allowed-tools":g.array(g.string()).optional()});function getPersonalSkillsDir(){return t.join(h.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return t.join(process.cwd(),".commandcode","skills")}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await M.access(n);const e=(await M.readdir(n,{withFileTypes:!0})).filter(e=>e.isDirectory());return(await Promise.all(e.map(async e=>{try{const r=t.join(n,e.name,"SKILL.md");await M.access(r);const o=await M.readFile(r,"utf-8"),{data:s}=Oe(o),a=Po.parse(s);return{name:a.name,description:a.description,filePath:r}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}async function loadAllSkillSummaries(){const[e,t]=await Promise.all([loadSkillSummariesFromDirectory({dir:getPersonalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir()})]);return{personal:e,project:t}}function escapeXML(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function generateSkillsXML(e){const{personal:n,project:r}=e,o=[...n,...r];return 0===o.length?"":`<available_skills>\n${o.map(e=>{const n=t.normalize(e.filePath);return`<skill>\n<name>\n${escapeXML(e.name)}\n</name>\n<description>\n${escapeXML(e.description)}\n</description>\n<location>\n${escapeXML(n)}\n</location>\n</skill>`}).join("\n")}\n</available_skills>`}function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}g.object({name:g.string(),description:g.string(),license:g.string().optional(),compatibility:g.array(g.string()).optional(),metadata:g.record(g.string(),g.any()).optional(),"allowed-tools":g.array(g.string()).optional(),content:g.string(),filePath:g.string()}),g.object({name:g.string(),description:g.string(),filePath:g.string()}),Rt(),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),At(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),At(),At(),At(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath"),At();var To=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()});var Ao=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};async function readFileContent(t){const{absolutePath:n,offset:r,limit:o}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new Ao("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=e.normalize(n);try{await D.access(s,y.constants.F_OK|y.constants.R_OK)}catch{throw new Ao(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await D.stat(s)).isFile())throw new Ao("Path does not point to a file","NOT_A_FILE");const a=getFileType(s),i=isBinaryFile(a);if(void 0!==r&&void 0===o||void 0===r&&void 0!==o)throw new Ao("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new Ao("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new Ao("Limit must be > 0","INVALID_LIMIT");try{if(i){const e=await D.readFile(s);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==r&&void 0!==o){const e=await readTextFileLines(s,r,o);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await D.readFile(s,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof Ao)throw e;throw new Ao(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var xo={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".pdf":"application/pdf",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf"};function getFileType(t){const n=e.extname(t).toLowerCase();return{".txt":"text",".md":"markdown",".csv":"csv",".log":"log",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".env":"env",".js":"javascript",".ts":"typescript",".jsx":"jsx",".tsx":"tsx",".py":"python",".java":"java",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c-header",".hpp":"cpp-header",".cs":"csharp",".go":"go",".rb":"ruby",".php":"php",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".clj":"clojure",".elm":"elm",".erl":"erlang",".ex":"elixir",".exs":"elixir",".hs":"haskell",".lua":"lua",".pl":"perl",".r":"r",".dart":"dart",".f":"fortran",".f90":"fortran",".groovy":"groovy",".jl":"julia",".m":"matlab",".sh":"shell",".bash":"bash",".zsh":"zsh",".ps1":"powershell",".sql":"sql",".vue":"vue",".svelte":"svelte",".astro":"astro",".component.ts":"angular",".module.ts":"angular",".service.ts":"angular",".razor":"razor",".cshtml":"razor",".erb":"ruby-template",".mustache":"mustache",".handlebars":"handlebars",".hbs":"handlebars",".ejs":"ejs",".pug":"pug",".liquid":"liquid",".twig":"twig",...xo}[n]||"unknown"}function isBinaryFile(e){return Object.values(xo).includes(e)}async function readTextFileLines(e,t,n){const r=(await D.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),a=r.slice(o,s);return{content:a.join("\n"),linesRead:a.length}}async function processFileReferences(t){const n=[];let r=t;const o=[...t.matchAll(/@([^\s@]+)/g)];for(const t of o){const o=t[0],s=t[1];try{const t=e.isAbsolute(s)?s:e.resolve(process.cwd(),s),a=await readFileContent({absolutePath:t});if("binary"===a.contentType)continue;const i=String(a.content),c=e.relative(process.cwd(),t),l=1e5;if(i.length>l){n.push({token:o,resolvedPath:t,content:"",tooLarge:!0});const e=`${c}`;r=r.replace(o,e);continue}n.push({token:o,resolvedPath:t,content:i});const d=`{${c}: ${i}}`;r=r.replace(o,d)}catch(e){continue}}return{displayContent:t,processedContent:r,fileReferences:n}}function reconstructContent(t,n){let r=t;for(const t of n){const n=`{${e.relative(process.cwd(),t.resolvedPath)}: ${t.content}}`;r=r.replace(t.token,n)}return r}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),At(),At();var Io="read_file",$o="edit_file",Ro="write_file",Do="read_directory",Mo="read_multiple_files",No="grep",Oo="shell_command",Fo="think",Lo="todo_write",_o="ask_user_question",Uo="kill_shell",jo="web_search",Bo="web_fetch",zo=__name(e=>e===jo,"isWebSearchTool"),Wo=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],Ho=__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 Wo.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:zo(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),Go=["create_file","delete_file",$o,Ro,Oo],qo=[Oo];function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",o=e.relative(n,t);return o.startsWith("..")?r&&t.startsWith(r)?t.replace(r,"~"):t:""===o?e.basename(t):o}function replacePathsInText(t){if(!t||"string"!=typeof t)return t;let n=t;return n=n.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,t=>e.isAbsolute(t)?toRelativePath(t):t),n=n.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),n}At(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText"),At(),At(),At();var Vo="2025-03-26",Ko={name:"command-code",version:"1.0.0"};Promise.resolve().then(()=>(jn(),Mn)).then(({getPackageJson:e})=>{Ko.version=e().version??"1.0.0"}).catch(()=>{}),At(),At();var Jo=g.object({authorizationUrl:g.string(),tokenUrl:g.string(),clientId:g.string(),clientSecret:g.string().optional(),scopes:g.array(g.string()).optional()}),Yo=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:Jo.optional(),env:g.record(g.string(),g.string()).optional()}),Qo=g.object({mcpServers:g.record(g.string(),Yo)});At(),Rt();var Zo="mcp.json";function getUserMcpConfigPath(){return e.join(h.homedir(),".commandcode",Zo)}function getLocalMcpConfigPath(t=process.cwd()){const n=Le(t);return e.join(h.homedir(),".commandcode","projects",n,Zo)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,".mcp.json")}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)}]}async function loadMcpConfig({scope:e,projectPath:t=process.cwd()}){try{const n=getMcpConfigPath({scope:e,projectPath:t}),r=await D.readFile(n,"utf-8"),o=JSON.parse(r),s=Qo.safeParse(o);return s.success?s.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 o=getMcpConfigPath({scope:n,projectPath:r}),s=e.dirname(o);await D.mkdir(s,{recursive:!0}),await D.writeFile(o,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:o}of t){const t=await loadMcpConfig({scope:o,projectPath:e});if(t?.mcpServers)for(const[e,s]of Object.entries(t.mcpServers))n[e]=s,r.set(e,o)}return{config:{mcpServers:n},serverScopes:r}}async function addMcpServer({name:e,serverConfig:t,scope:n,projectPath:r=process.cwd()}){let o=await loadMcpConfig({scope:n,projectPath:r});o||(o={mcpServers:{}});let s=t;if("project"===n&&t.oauth?.clientSecret){await storeClientSecret(e,t.oauth.clientSecret);const{clientSecret:n,...r}=t.oauth;s={...t,oauth:r}}o.mcpServers[e]=s,await saveMcpConfig({config:o,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),o=n.mcpServers[e],s=r.get(e);return o&&s?{config:o,scope:s}: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)}))}__name(getUserMcpConfigPath,"getUserMcpConfigPath"),__name(getLocalMcpConfigPath,"getLocalMcpConfigPath"),__name(getProjectMcpConfigPath,"getProjectMcpConfigPath"),__name(getMcpConfigPath,"getMcpConfigPath"),__name(getAllMcpConfigPaths,"getAllMcpConfigPaths"),Cn(),or(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers"),At();var Xo=class _StdioTransport extends Fe{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=x(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 o=setTimeout(()=>{this.pendingRequests.delete(n),t(new Error("Request timed out"))},_StdioTransport.REQUEST_TIMEOUT_MS);this.pendingRequests.set(n,{resolve:__name(t=>{clearTimeout(o),e(t)},"resolve"),reject:__name(e=>{clearTimeout(o),t(e)},"reject")});const s=JSON.stringify(r)+"\n";this.process.stdin.write(s,e=>{e&&(clearTimeout(o),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)}};At(),or(),ir();var es=class _HttpTransport extends Fe{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":`${Ko.name}/${Ko.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(()=>(Cr(),cr));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,o=setTimeout(()=>r.abort(),rr);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 o=t.headers.get("mcp-session-id");o&&(this.sessionId=o);const s=t.headers.get("content-type")||"",a=await t.text();if(s.includes("text/event-stream")||a.startsWith("event:")||a.startsWith("data:")){const e=this.parseSSEResponse(a);if(e)return e;throw new Error("Failed to parse SSE response")}return JSON.parse(a)}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw new Error("Request timed out");throw e}finally{clearTimeout(o)}}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,o=setTimeout(()=>r.abort(),rr);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(o)}}async close(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.isConnected=!1,this.emit("close")}get connected(){return this.isConnected}},ts=class extends Fe{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,o]of Object.entries(t.mcpServers)){if(!o.enabled)continue;const t=n.get(e);r.push(this.connectServer(e,o,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 Xo?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?Xo.fromConfig(e):es.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:Vo,capabilities:{roots:{}},clientInfo:Ko});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 o=await r.transport.request("tools/call",{name:t,arguments:n});if(o.error)throw new Error(`Tool call failed: ${o.error.message}`);return o.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}},ns=null;function getMcpConnectionManager(){return ns||(ns=new ts),ns}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),o=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:o,...r.isError&&{error:o}}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}__name(getMcpConnectionManager,"getMcpConnectionManager"),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool");var rs=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()})}),os=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(rs).optional().default([])}),ss=os.extend({role:g.literal("user")}),as=os.extend({role:g.literal("assistant")}),is=os.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'"}),cs=os.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'"}),ls=os.extend({role:g.literal("system")}),ds=os.extend({role:g.literal("error")}),us=os.extend({role:g.literal("info")}),ms=os.extend({role:g.literal("taste-onboarding")}),gs=os.extend({role:g.literal("command-result"),hasError:g.boolean().optional(),details:g.string().optional()}),ps=os.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()}),hs=g.discriminatedUnion("role",[ss,as,is,cs,ls,ds,us,ms,gs,ps]),fs=__name((e,t)=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),ys=__name((e,t)=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),ws=__name(e=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),Es=__name((e,t,n)=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Ss=__name(e=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),ks=__name(e=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),vs=__name(e=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),bs=__name(()=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Cs=__name((e,t=!1,n)=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),Ps=__name((e,t,n)=>hs.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),Ts=__name(({name:e,input:t})=>{const n=Date.now();return hs.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"),As=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return hs.parse(n)},"updateEntryWithOutput"),xs=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),Is=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),$s=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),Rs=["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…"],Ds=__name(()=>Rs[Math.floor(Math.random()*Rs.length)],"getRandomLLMStatus"),Ms=__name(e=>{switch(e){case Io:return"Read";case $o:return"Edit";case Ro:return"Write";case Do:return"List";case Mo:return"Read Multiple";case No:return"Search";case Oo:return"Shell";case Lo:return"Todos";case Fo:return"Thinking…";case jo:return"Web Search";case Bo:return"Web Fetch";case _o:return"Question";case"explore":return"Explore";case Uo:return"Kill Shell";default:if(isMcpTool(e)){const t=parseMcpToolName(e);if(t){const e=t.toolName.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase());return`${t.serverName}: ${e} (MCP)`}}return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),Ns=__name(e=>{const t=Object.entries(e);if(0===t.length)return"";const[n,r]=t[0],o="string"==typeof r?r:JSON.stringify(r)??"";return`${n}: ${o.length>60?o.slice(0,57)+"...":o}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),Os=__name(e=>{let t=e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~").replace(/C:\\Users\\[^\\]+/g,"~");if(t.includes(" && ")){const e=t.split(" && "),n=e[0].trim();if(n.length<=100)return e.length>1?`${n} && …`:n;t=n}return t.length>100?t.substring(0,100)+"…":t},"truncateShellCommand"),Fs=__name((e,t)=>{try{switch(e){case Io:case Ro:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case $o:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Do:return toRelativePath(t.path||"directory");case No:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Oo:if(t.command){const e=Array.isArray(t.args)&&t.args.length>0?` ${t.args.join(" ")}`:"string"==typeof t.args&&t.args?` ${t.args}`:"",n=`${t.command}${e}`;return Os(n)}return t.command||"";case Lo:let o;try{o="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=Ls(o);return`${e?e.length:0} items`}catch{return"items"}case Fo:return t.content||"planning";case Mo:const s=t.include||[];return Array.isArray(s)?s.join(", "):"multiple files";case jo:return t.query||"search";case Bo:return t.url||"fetch";case _o:return"User answered questions";case Uo:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case"enter_plan_mode":case"exit_plan_mode":return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return Ns(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("."),r=n>0?t.slice(0,n):t;return r.length>80?r.slice(0,80)+"...":r}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),Ls=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput");function formatOutput(e){const t=[];if(void 0!==e.linesRead)t.push(`Read ${e.linesRead} lines`);else if("binary"===e.contentType)t.push(`Binary file: ${e.size} bytes`);else{const n=e.content?String(e.content).split("\n").length:0;t.push(`Read ${n} lines`)}return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}At(),At(),At(),__name(formatOutput,"formatOutput");var _s={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=To.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while reading file`}},"execute")};At(),At();var Us=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()}),At(),At(),At();var js=g.object({backupFileName:g.string().nullable(),version:g.number().int().positive(),backupTime:g.string().datetime()}),Bs=g.object({messageId:g.string().uuid(),trackedFileBackups:g.record(g.string(),js),timestamp:g.string().datetime()});g.object({type:g.literal("file-history-snapshot"),messageId:g.string().uuid(),snapshot:Bs,isSnapshotUpdate:g.boolean()}),g.object({maxFileSize:g.number().int().positive().default(10485760),retentionDays:g.number().int().positive().default(30)});var zs=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`${U.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(h.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 M.statfs(t);return e.bavail*e.bsize}catch{return-1}}async function hasEnoughDiskSpace(e){const{fileSizeBytes:t,targetPath:n}=e,r=2*t,o=await getAvailableDiskSpace({targetPath:n});return-1===o||o>=r}async function ensureDirectoryExists(e){const{dirPath:t}=e;await M.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await M.writeFile(r,n);const e=await M.stat(r),o="string"==typeof n?Buffer.byteLength(n,"utf-8"):n.length;if(e.size!==o)throw new Error(`Write verification failed: expected ${o} bytes, got ${e.size}`);await M.rename(r,t)}catch(e){try{await M.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await M.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await M.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function truncateString2(e){const{text:t,maxLength:n}=e;return t.length<=n?t:n<=3?t.slice(0,n):t.slice(0,n-3)+"..."}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60),a=Math.floor(s/24);return a>0?`${a}d ago`:s>0?`${s}h ago`:o>0?`${o}m ago`:"just now"}function getFileName(e){const{filePath:n}=e;return t.basename(n)}function isWithinRetentionPeriod(e){const{timestamp:t,retentionDays:n}=e,r=new Date(t).getTime();return Date.now()-r<=24*n*60*60*1e3}At(),At(),Rt(),__name(getPathHash,"getPathHash"),__name(getBackupFileName,"getBackupFileName"),__name(getCommandCodeBasePath,"getCommandCodeBasePath"),__name(getFileHistoryPath,"getFileHistoryPath"),__name(getBackupFilePath,"getBackupFilePath"),__name(getAvailableDiskSpace,"getAvailableDiskSpace"),__name(hasEnoughDiskSpace,"hasEnoughDiskSpace"),__name(ensureDirectoryExists,"ensureDirectoryExists"),__name(atomicWriteFile,"atomicWriteFile"),__name(getFileSizeBytes,"getFileSizeBytes"),__name(fileExists,"fileExists"),__name(getCurrentTimestamp,"getCurrentTimestamp"),__name(truncateString2,"truncateString"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod"),nr();var Ws={maxFileSize:10485760,retentionDays:30},Hs=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Ws,...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 M.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,o=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const s=getBackupFilePath({sessionId:this.sessionId,backupFileName:o});await atomicWriteFile({filePath:s,content:e});const a={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,a),this.trackedState.versions.set(t,n),{success:!0,backup:a,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:Yn.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 M.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new zs(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:Yn.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await M.readFile(r);await atomicWriteFile({filePath:t,content:o})}async verifyRestoreOperation(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName){if(!await fileExists({filePath:t}))return{canRestore:!0};try{return await M.access(t,M.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 M.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await M.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await M.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}};At(),nr();var Gs=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new Hs({sessionId:t,config:r}),this.sessionStore=n||null,this.snapshots=[],this.config={maxFileSize:r?.maxFileSize||10485760,retentionDays:r?.retentionDays||30}}getFileHistoryManager(){return this.fileHistoryManager}setSessionStore(e){const{sessionStore:t}=e;this.sessionStore=t}async backupFile(e){const{filePath:t}=e,n=await this.fileHistoryManager.backupFile({filePath:t,sessionId:this.fileHistoryManager.getSessionId()});if(n.success&&this.snapshots.length>0){const e=this.snapshots[this.snapshots.length-1];e.trackedFileBackups=this.fileHistoryManager.getTrackedFileBackups(),this.sessionStore&&this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0}).catch(()=>{})}return{success:n.success,backup:n.backup}}async createSnapshot(e){const{messageId:t}=e,n={messageId:t,trackedFileBackups:{},timestamp:getCurrentTimestamp()};return this.snapshots.push(n),this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:n,isUpdate:!1}),n}async updateCurrentSnapshot(){if(0===this.snapshots.length)return;const e=this.snapshots[this.snapshots.length-1],t=this.fileHistoryManager.getTrackedFileBackups(),n=this.snapshots.length>1?this.snapshots[this.snapshots.length-2]:null,r=n?.trackedFileBackups||{},o={};for(const[e,n]of Object.entries(t)){const t=r[e];(!t||t.version!==n.version||t.backupFileName!==n.backupFileName)&&(o[e]=n)}e.trackedFileBackups=o,this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0})}listCheckpoints(){const e=[];for(let t=0;t<this.snapshots.length;t++){const n=this.snapshots[t];t>0&&this.snapshots[t-1];let r="";if(this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:n.messageId}),t=this.sessionStore.getMessageAtIndex({index:e});t&&(r=truncateString2({text:t.content,maxLength:100}))}const o=Object.keys(n.trackedFileBackups);let s=null;if(o.length>0){const e=o[0];n.trackedFileBackups[e]&&(s={additions:0,deletions:0,fileName:getFileName({filePath:e})})}e.push({messageId:n.messageId,timestamp:n.timestamp,userPrompt:r,fileCount:Object.keys(n.trackedFileBackups).length,filesModified:o,codeChanges:s})}return e.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime())}getSnapshot(e){const{messageId:t}=e;return this.snapshots.find(e=>e.messageId===t)||null}async restore(e){const{messageId:t,mode:n}=e;if(!this.getSnapshot({messageId:t}))return{success:!1,error:"Snapshot not found",filesRestored:0,filesDeleted:0,messagesRemoved:0};const r=this.snapshots.findIndex(e=>e.messageId===t);let o=0,s=0,a=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return trackError({error:sanitizeErrorForTelemetry({error:new Error(`Restore verification failed:\n${t.join("\n")}`),label:"restore_verification_failed"}),context:{component:Yn.CHECKPOINT_MANAGER,heading:"Checkpoint restore verification failed","checkpoint.failures":t.length}}),{success:!1,error:`Restore verification failed:\n${t.join("\n")}`,filesRestored:0,filesDeleted:0,messagesRemoved:0};for(const t of e)await this.fileHistoryManager.restoreFile({filePath:t.filePath,backup:t.backup}),null===t.backup.backupFileName?s++:o++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(a=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const i=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&i.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&i.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:i}),{success:!0,filesRestored:o,filesDeleted:s,messagesRemoved:a}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}};At();var qs=null;function initializeCheckpointService(e){const{sessionId:t}=e;return qs=new Gs({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return qs?qs.backupFile({filePath:t}):{success:!0,backup:null}}function createFileEditError(e,t){const n=new Error(e);return n.name="FileEditError",n.code=t,n}async function editFile(t){const{filePath:n,oldValue:r,newValue:o,replaceAll:s=!1,replacementCount:a=1}=t;if(!n)throw createFileEditError("filePath is required","INVALID_PATH");if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!r)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==o)throw createFileEditError("newValue is required","INVALID_INPUT");if(!s&&a<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await k.access(n,v.F_OK|v.R_OK|v.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${n}`,"FILE_ACCESS_ERROR")}let i;try{const e=await readFileContent({absolutePath:n});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");i=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const c=(i.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===c)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let l,d;if(s)l=c;else if(l=a,l>c)throw createFileEditError(`Expected ${l} replacements, but only found ${c} occurrences`,"INSUFFICIENT_MATCHES");let u=0;if(s||l===c)d=i.split(r).join(o),u=c;else{d=i;for(let e=0;e<l;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+o+d.substring(e+r.length),u++)}}if(0===u)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await k.writeFile(n,d,"utf-8"),{path:n,replacementsCount:u,oldContent:i,newContent:d}}catch(e){throw createFileEditError(`Failed to write file: ${e instanceof Error?e.message:"Unknown error"}`,"WRITE_ERROR")}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function formatOutput2(e){const t=1!==e.replacementsCount?"s":"",n=`Edited ${e.path} (${e.replacementsCount} replacement${t})`;return e.newContent.length<500?`${n}\n\n${e.newContent}`:n}__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit"),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),At(),__name(formatOutput2,"formatOutput");var Vs={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=Us.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while editing file`}},"execute")};At(),At();var Ks=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())});var Js=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}};async function readDirectory(t){const{path:n,exclude:r=[],respectGitIgnore:o=!1}=t;if(!e.isAbsolute(n))throw new Js("Path must be absolute, not relative","INVALID_PATH");try{if(!(await D.stat(n)).isDirectory())throw new Js("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Js)throw e;throw new Js(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await D.readdir(n);let s=[];o&&(s=await loadGitIgnorePatterns(n));const a=[...r,...s],i=[],c=[];for(const r of t){if(shouldIgnoreEntry(r,a))continue;const t=e.join(n,r);try{const e=await D.stat(t);e.isDirectory()?c.push(r):e.isFile()&&i.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:i.sort(),directories:c.sort()}}catch(e){if(e instanceof Js)throw e;throw new Js(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(t){const n=[];try{if(!await isInGitRepository(t))return n;let r=e.resolve(t);const o=await findGitRoot(t);for(;r&&isWithinGitRoot(r,o);){const t=e.join(r,".gitignore");try{const e=(await D.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch(e){}const o=e.dirname(r);if(o===r)break;r=o}}catch(e){}return n}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await D.stat(t)).isDirectory())return n}catch{}const t=e.dirname(n);if(t===n)throw new Error("Not in a git repository");n=t}}function isWithinGitRoot(t,n){const r=e.resolve(t),o=e.resolve(n);return"win32"===process.platform?r.toLowerCase().startsWith(o.toLowerCase()):r.startsWith(o)}function shouldIgnoreEntry(e,t){for(const n of t)if(_e(e,n))return!0;return!1}function formatOutput3(e){const t=e.directories.length+e.files.length,n=[];return n.push(`Found ${t} items (${e.directories.length} dirs, ${e.files.length} files)`),e.directories.length>0&&(n.push("Directories:"),e.directories.forEach(e=>n.push(` ${e}/`))),e.files.length>0&&(n.push("Files:"),e.files.forEach(e=>n.push(` ${e}`))),0===t&&n.push("(empty directory)"),n.join("\n")}At(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),At(),__name(formatOutput3,"formatOutput");var Ys={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=Ks.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while reading directory`}},"execute")};At(),At();var Qs=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")});async function writeFile4({filePath:e,content:n}){const o=e.startsWith("~/")?t.join(h.homedir(),e.slice(2)):e;if(!s(o))throw new Error(`Invalid file path: '${o}'. Only absolute paths are supported.`);try{const e=r(o);return E(e)||await N(e,{recursive:!0}),await backupFileBeforeEdit({filePath:o}),await O(o,n,"utf-8"),{path:o,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 '${o}': ${t}`)}}function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}g.object({success:g.boolean(),message:g.string(),path:g.string().optional()}),At(),__name(writeFile4,"writeFile"),At(),__name(formatOutput4,"formatOutput");var Zs={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=Qs.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")};At(),At();var Xs=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")}),ea=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(ea)});var ta=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}};At();var na=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const o=new Set;for(const s of e)try{(await Ue(s,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>o.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${s}": ${e}`)}return Array.from(o).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:n,exclude:r=[],gitIgnore:o=!0,defaultExclude:s=!0,targetDirectory:a=process.cwd()}=e;if(!n||0===n.length)throw new ta("At least one include pattern must be provided","NO_PATTERNS");const i=t.resolve(a),c={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];s&&e.push(...na);const a=await findMatchingFiles({include:n,exclude:e,gitIgnore:o,targetDirectory:i});for(const e of a)try{const n=t.resolve(i,e),r=await readFileContent({absolutePath:n}),o=processFileResult({content:r,filePath:e});c.fileDetails.push(o),c.content+=`\n// File: ${e} (${r.fileType})\n`,c.content+=o.content,c.content+="\n",c.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);c.errors.push({file:e,error:n}),c.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return c}catch(e){if(e instanceof ta)throw e;throw new ta(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getReadSummary(e){return{totalFiles:e.fileDetails.length,successfulReads:e.filesRead.length,failedReads:e.errors.length,totalSize:e.fileDetails.reduce((e,t)=>e+t.size,0),fileTypesCounts:e.fileDetails.reduce((e,t)=>(e[t.fileType]=(e[t.fileType]||0)+1,e),{}),contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];return n.push(`Read ${t.successfulReads}/${t.totalFiles} files (${t.totalSize} bytes)`),e.errors.length>0&&(n.push("\nErrors:"),e.errors.forEach(e=>n.push(` - ${e.file}: ${e.error}`))),n.push("\n--- File Contents ---"),n.push(e.content),n.join("\n")}__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles"),At(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var ra={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=Xs.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while reading multiple files`}},"execute")};At(),At();var oa=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()});At(),At();var sa=1e5,aa=5e4;function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=x(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",a="";o.stdout?.on("data",e=>{try{const t=e.toString();if(s.length+t.length>sa)return a="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",void o.kill("SIGTERM");s+=t}catch(e){a+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,o.kill("SIGTERM")}}),o.stderr?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>aa)return void(a+="\n[Error output truncated: too large]");a+=t}catch(e){a+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),o.on("close",e=>{0===e?n(s):1!==e||a?r(new Error(a||`Command failed with exit code ${e}`)):n("")}),o.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,o]=t;return{file:n,line:parseInt(r,10),column:1,content:o.trim(),match:o.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",o=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)o.splice(-1,0,"--glob",e);o.splice(-1,0,"--glob","!node_modules/**"),o.splice(-1,0,"--glob","!.git/**"),o.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:o,command:"rg"})}catch(s){if(!(s instanceof Error&&s.message.includes("ENOENT")))throw s;if(r="grep",o=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)o.splice(-1,0,"--include",e);o.splice(-1,0,"--exclude-dir=node_modules"),o.splice(-1,0,"--exclude-dir=.git"),o.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:o,command:"grep"})}if(!e.trim())return[];const s=e.trim().split("\n"),a=[];for(const e of s){const t=parseGrepLine(e);t&&a.push(t)}return a}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),At(),__name(formatGrepResults,"formatGrepResults");var ia={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=oa.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while searching files`}},"execute")};At(),At();var ca=g.object({pattern:g.string().min(1,"Pattern is required"),path:g.string().optional()}),la=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 la("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new la("Search path must be within the current working directory or an added directory","INVALID_PATH");const o=await Ue(n,{cwd:e,ignore:bt,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),s=await Promise.all(o.map(async n=>{const r=t.join(e,n);try{return{file:n,mtime:(await M.stat(r)).mtimeMs}}catch{return{file:n,mtime:0}}}));return s.sort((e,t)=>t.mtime-e.mtime),{files:s.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof la)throw e;if(e instanceof Error)throw new la(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new la("Unknown error occurred during file search","UNKNOWN_ERROR")}}function formatGlobResults(e){if(0===e.files.length)return"No files found matching pattern";const t=[],n=e.files.length;t.push(`Found ${n} file${1!==n?"s":""}`);for(const n of e.files)t.push(` ${n}`);return t.join("\n")}At(),Rt(),Ft(),__name(globSearch,"globSearch"),At(),__name(formatGlobResults,"formatGlobResults");var da={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=ca.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while finding files`}},"execute")};At(),At();var ua=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())}),ma=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,a){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=a}};async function executeShellCommand(t){const{command:n,args:r=[],directory:o,timeout:s=3e4}=t,a=Date.now();if(!n.trim())throw new ma("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(e.isAbsolute(o))throw new ma("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=e.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await M.stat(i)).isDirectory())throw new ma(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof ma)throw e;throw new ma(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:i,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((t,o)=>{let i="",c="",l=!1;const d=r.length>0?je([n,...r]):n,u=setTimeout(()=>{if(!l){m.kill("SIGTERM");const e=Date.now()-a;o(new ma(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",i,c,e))}},s),m=x(d,[],e);m.stdout?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>sa)return c="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void m.kill("SIGTERM");i+=t}catch(e){c+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,m.kill("SIGTERM")}}),m.stderr?.on("data",e=>{try{const t=e.toString();if(c.length+t.length>aa)return void(c+="\n[Error output truncated: too large]");c+=t}catch(e){c+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),m.on("close",(e,n)=>{l=!0,clearTimeout(u);const r=Date.now()-a;0===e?t({stdout:i.trim(),stderr:c.trim(),exitCode:e,signal:n,duration:r}):o(new ma(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,i.trim(),c.trim(),r))}),m.on("error",e=>{l=!0,clearTimeout(u);const t=Date.now()-a;o(new ma(`Failed to start command: ${e.message}`,"START_FAILED",null,null,i.trim(),c.trim(),t))})})}catch(e){if(e instanceof ma)throw e;throw new ma(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}function formatShellCommandResult(e){const t=[];return 0===e.exitCode||null===e.exitCode||t.push(`Exit code: ${e.exitCode}`),e.signal&&t.push(`Signal: ${e.signal}`),e.stdout&&t.push(e.stdout),e.stderr&&t.push(e.stderr),t.join("\n")}At(),__name(executeShellCommand,"executeShellCommand"),At(),__name(formatShellCommandResult,"formatShellCommandResult");var ga={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=ua.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${Se.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${Se.cross} Error: ${e.message}`}return`${Se.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}At(),At(),__name(think,"think");var pa={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)}At(),At(),__name(todoWrite,"todoWrite");var ha={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`});if(n.header.length>12)return JSON.stringify({error:`Question ${t+1} header exceeds maximum length of 12 characters`})}if(!t?.onQuestionRequest)return JSON.stringify({error:"Question request callback not available"});if(t.abortSignal?.aborted)return JSON.stringify({error:"Interrupted by user"});try{const n=await t.onQuestionRequest(e);return t.abortSignal?.aborted?JSON.stringify({error:"Interrupted by user"}):JSON.stringify(n)}catch(e){return e instanceof Error?JSON.stringify({error:e.message}):JSON.stringify({error:"Failed to get user response"})}}function isErrorResponse(e){return"error"in e&&"string"==typeof e.error}function formatOutput6(e){const{result:t,params:n}=e;if(isErrorResponse(t))return`Error: ${t.error}`;if(!t.answers||0===t.answers.length)return"User declined to answer questions";const r=t.answers.filter(e=>e.selectedOptions&&Array.isArray(e.selectedOptions)&&e.selectedOptions.length>0);if(0===r.length)return"User declined to answer questions";const o=[];return r.forEach(e=>{let t=`Question ${e.questionIndex+1}`;n?.questions?.[e.questionIndex]&&(t=n.questions[e.questionIndex].question||t);const r=e.selectedOptions.join(", ");o.push(`${t} → ${r}`)}),o.join("\n")}At(),At(),__name(askUserQuestion,"askUserQuestion"),At(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var fa={name:"ask_user_question",description:'Use this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- Users will always be able to select "Type something" to provide custom text input\n- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label\n- Use multiSelect: true to allow multiple answers to be selected for a question',acceptsCallbacks:!0,input_schema:{type:"object",properties:{questions:{type:"array",description:"Questions to ask the user",items:{type:"object",properties:{question:{type:"string",description:"The complete question to ask the user. Should be clear, specific, and end with a question mark."},header:{type:"string",description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'},options:{type:"array",description:'The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Type something" option, that will be provided automatically.',items:{type:"object",properties:{label:{type:"string",description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."},description:{type:"string",description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}},required:["label","description"]}},multiSelect:{type:"boolean",description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."}},required:["question","header","options"]}}},required:["questions"]},execute:__name(async(e,t)=>{const n=await askUserQuestion(e,{onQuestionRequest:t?.onQuestionRequest,abortSignal:t?.abortSignal});try{return formatOutput6({result:JSON.parse(n),params:e})}catch{return n}},"execute")};At(),At();var ya=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"}),wa=class extends Error{static{__name(this,"KillshellError")}code;pid;port;constructor(e,t,n,r){super(e),this.name="KillshellError",this.code=t,this.pid=n,this.port=r}};function isUnixLike(){const e=process.platform;return"darwin"===e||"linux"===e}function isWindows(){return"win32"===process.platform}async function executeCommand(e,t){return new Promise((n,r)=>{const o=x(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let s="",a="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{a+=e.toString()}),o.on("close",e=>{0===e?n(s.trim()):r(new Error(a.trim()||s.trim()))}),o.on("error",e=>{r(e)})})}async function findPidByPort(e){try{if(isUnixLike()){const t=(await executeCommand("lsof",["-ti",`:${e}`,"-sTCP:LISTEN"])).trim().split("\n")[0];if(!t||!/^\d+$/.test(t))return null;const n=parseInt(t,10);return isNaN(n)?null:n}if(isWindows()){const t=(await executeCommand("netstat",["-ano"])).split("\n");for(const n of t){const t=n.trim();if(!t)continue;const r=t.split(/\s+/);if(r.length<5)continue;if("LISTENING"!==r[3])continue;const o=r[1].match(/:(\d+)$/);if(!o)continue;const s=parseInt(o[1],10);if(isNaN(s)||s!==e)continue;const a=parseInt(r[r.length-1],10);if(!isNaN(a))return a}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new wa(`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 wa("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 wa(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}function formatKillshellResult(e){const t=[];return t.push(`${Se.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}At(),__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"),At(),__name(formatKillshellResult,"formatKillshellResult");var Ea={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=ya.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?`${Se.cross} Permission denied: Process termination was not approved`:formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while killing process`}},"execute")};At();var Sa={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")};At();var 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")};At(),At(),At(),At(),At(),Rt(),At(),At();var va=["explore","plan","review","general"],ba=[{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&&va.includes(e.toLowerCase())}function getRootAgentDir(){return t.join(h.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await M.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await M.readFile(o,"utf-8"),{data:a,content:i}=Oe(s),c=a.name||r.replace(".md","");if(isReservedAgentName(c))return null;let l=a.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:c,description:a.description||"",tools:l,systemPrompt:i.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}}async function loadAllAgents(){const[e,t]=await Promise.all([loadAgentsFromDirectory(getRootAgentDir(),"personal"),loadAgentsFromDirectory(getLocalAgentDir(),"project")]);return{personal:e,project:t}}__name(isReservedAgentName,"isReservedAgentName"),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents"),At(),Rt(),qt(),$n(),Wt(),At(),Rt(),qt(),At(),Rt(),nr(),Cn(),At();var Ca=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext"),Pa=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(h.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Le(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const n=_SessionManager.getCurrentProjectDirName();this.projectPath=t.join(_SessionManager.getProjectsBasePath(),n),this.sessionFilePath=t.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=I("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await M.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:Yn.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await M.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{if(0===e.length)return;const n=JSON.stringify(e);if(n===this.lastSavedMessagesHash)return;await this.initializeProject();const r=[];for(const n of e){const e=crypto.randomUUID(),o={id:e,timestamp:n.meta.timestamp,sessionId:this.sessionId,parentId:this.lastMessageId,role:n.message.role,content:n.message.content,gitBranch:this.gitBranch,metadata:{...n.meta,...t?.metadata||{}}};r.push(JSON.stringify(o)),this.lastMessageId=e}await M.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 M.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let n=0;for(const r of e)try{const e=JSON.parse(r);"user"!==e.role&&"assistant"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}})}catch(e){n++,console.error("Error parsing session line:",e)}return{messages:t,corruptedLines:n,totalLines:e.length}}catch(e){return console.error("Error loading messages:",e),{messages:[],corruptedLines:0,totalLines:0}}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),o=crypto.randomUUID();if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n=Ca(n),n&&t.push({id:o,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)t.push({id:o,timestamp:r,role:"assistant",input:e.content,images:[]});else if(Array.isArray(e.content)){for(const r of e.content)if("text"===r.type)n+=r.text;else if("tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=Fs(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=Fs(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 M.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 M.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await M.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 M.access(n)}catch{return[]}const e=(await M.readdir(n)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),r=[];for(const o of e){const e=o.replace(".jsonl",""),s=t.join(n,o);try{const t=await M.stat(s),o=(await M.readFile(s,"utf-8")).trim().split("\n").filter(e=>e.trim());if(o.length>0){let s="",a="";const i=JSON.parse(o[0]);i.gitBranch&&(a=i.gitBranch);for(const e of o){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)s=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){s=e.text;break}}else t.content?.input&&(s=t.content.input);if(s)break}}s=Ca(s);const c=await _SessionManager.loadSessionMetaForId(e,n),l=c?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:s||"No messages",title:l||void 0,messageCount:o.length,projectPath:n,gitBranch:a||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return r.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const n=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await M.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 M.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 M.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await M.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 M.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 M.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 M.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const o=n.findIndex(e=>e.messageId===t.messageId);-1!==o?n[o]=e:n.push(e);const s=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await M.writeFile(r,s)}else await M.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 M.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 M.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),o=e.findIndex(e=>e.messageId===t);if(-1===o)return;const s=(n?e.slice(0,o):e.slice(0,o+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await M.writeFile(r,s)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let o="";if("string"==typeof r.message.content)o=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(o+=e.text);return o=Ca(o),{messageId:r.meta.messageId||crypto.randomUUID(),content:o}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return r.length>0&&await this.saveMessages(r),r}};Wt(),An(),$n(),Cn();var Ta=new Map,Aa=null;function getRequest(){return Aa||(Aa=new Co({baseUrl:getApiBaseUrl()})),Aa}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:Et,max_tokens:50,temperature:.3,stream:!0},threadId:crypto.randomUUID()}}async function getAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced();let n;e===wt.ANTHROPIC&&(n=await Bt.getValidAccessToken(),validateOAuthToken({token:n,provider:e}));const r={[pt.PROJECT_SLUG]:Pa.getCurrentProjectDirName(),[pt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(r[pt.OAUTH_TOKEN]=`Bearer ${n}`),r}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=Ta.get(n);if(r)return Ta.delete(n),Ta.set(n,r),dlog(`[ToolDescription] cache hit for ${e}: "${r}"`),r;dlog(`[ToolDescription] generating for ${e}`);try{const e=getRequest(),r=await getAuthHeaders(),o=buildRequestBody(createPrompt(0,t));dlog(`[ToolDescription] calling ${ht.ALPHA.GENERATE} with model: ${Et}`);const s=e.post({endpoint:ht.ALPHA.GENERATE,body:o,headers:r,stream:!0}),a=await Promise.race([s,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),5e3))]);if(!a)return dlog("[ToolDescription] no response stream"),null;dlog("[ToolDescription] got response stream");const i=Be.fromReadableStream(a);let c="",l=null;if(i.on("text",e=>{c+=e}),i.on("error",e=>{l=e}),await i.finalMessage(),l)throw l;dlog(`[ToolDescription] raw response: "${c}"`);const d=cleanDescription(c);if(d){if(Ta.size>=100){const e=Ta.keys().next().value;void 0!==e&&Ta.delete(e)}Ta.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,200)}function createPrompt(e,t){return`Describe this shell command in 3-6 words as an imperative action. Start with a capital letter, no period at the end. Be specific about what's happening.\n\nCommand: ${`${sanitize(t.command||"")} ${sanitize(Array.isArray(t.args)?t.args.join(" "):t.args||"")}`.trim()}\n\nExamples:\n- npm test → "Run npm test suite"\n- git status → "Check git repository status"\n- rm -rf node_modules → "Delete node_modules directory"\n- docker build -t app . → "Build Docker image"\n\nDescription:`}function cleanDescription(e){let t=e.trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim();t.length>0&&(t=t.charAt(0).toUpperCase()+t.slice(1));const n=t.split(/\s+/).length;return n<3||n>6||t.length>60?null:t}function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=h.homedir(),o=n.startsWith("~/")?t.join(r,n.slice(2)):n,s=t.resolve(o),a=t.join(r,".commandcode","plans");return s.startsWith(a+t.sep)||s===a}__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"),At(),At(),Rt(),__name(isPlanPath,"isPlanPath");var xa=["edit_file","delete_file","shell_command","todo_write","kill_shell"],Ia=["exit_plan_mode"],$a=["enter_plan_mode"];function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!Ia.includes(e.name)):"plan"===n?t.filter(e=>!xa.includes(e.name)&&!$a.includes(e.name)):t.filter(e=>!Ia.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 xa.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.`}}__name(getToolsForMode,"getToolsForMode"),__name(isToolAllowedInMode,"isToolAllowedInMode"),At();var Ra=2e5;function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(1.1*t));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=1.1*estimateTextTokens(JSON.stringify(n.input)));else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/3.5;const n=.1*e.split(/\s+/).length;return Math.max(0,Math.ceil(t-n))}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>25e3}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?(estimateTokens(e),"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."):e}function calculateUsageFromResponse(e){return(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.output_tokens||0)}function sleep(e){const{delay:t,signal:n}=e;return new Promise((e,r)=>{if(n?.aborted)return r(new Error("Interrupted by user"));const o=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(o),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(function getOversizedOutputError(e,t){return"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."},"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),At(),__name(sleep,"sleep"),At(),Cn();var Da=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${Se.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${Se.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${Se.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${Se.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}};function getEnterpriseMemoryPath(){switch(p.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=p.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 o=getUserMemoryPath();return t.push({type:"user",path:o,exists:E(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return E(e)&&T(e).isFile()?await D.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}async function processImports(t,n,r=0,o=5){if(r>=o)return t;const s=[],a=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(s.push(e),`__CODE_BLOCK_${s.length-1}__`)),i=Array.from(a.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let c=a;for(const t of i){const s=t[1];let a=s;s.startsWith("~/")?a=e.join(p.homedir(),s.slice(2)):e.isAbsolute(s)||(a=e.resolve(e.dirname(n),s));const i=await loadMemoryFile(a);if(i){const e=await processImports(i,a,r+1,o);c=c.replace(t[0],`\n# Imported from ${s}\n${e}\n`)}}return c=c.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>s[parseInt(t)]),c}async function loadAllMemories(t,n){const r=new Map,o=getEnterpriseMemoryPath();if(E(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const s=getUserMemoryPath();if(E(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const a=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of a)if(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 o of n){const n=e.isAbsolute(o)?e.dirname(o):e.dirname(e.resolve(t,o));if(n.startsWith(t)&&n!==t){const o=[];let s=n;for(;s.startsWith(t)&&s!==t;)o.push(s),s=e.dirname(s);for(const t of o.reverse()){const n=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of n)if(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 D.mkdir(r,{recursive:!0}),E(t)||await D.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const o=x(n,[t],{stdio:"inherit",shell:!0});o.on("exit",t=>{0===t?e():r(new Error(`Editor exited with code ${t}`))}),o.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),r(e)})})}async function initProjectMemory(t){const n=e.join(t,"AGENTS.md");return E(n)||await D.writeFile(n,"# Memory\n\n## Project Overview\nSee @README.md for project overview and @package.json for available npm/pnpm commands for this project.\n\n## Code Style Guidelines\n- Use descriptive variable names\n- Follow existing patterns in the codebase\n- Extract complex conditions into meaningful boolean variables\n\n## Architecture Notes\nAdd important architectural decisions and patterns here.\n\n## Common Workflows\nDocument frequently used workflows and commands here.\n","utf-8"),n}async function getMemoryContent(t){try{const n=process.cwd(),r=await loadAllMemories(n,t);if(0===r.size)return null;const o=[],s=getEnterpriseMemoryPath(),a=getUserMemoryPath(),i=[e.join(n,"AGENTS.md"),e.join(n,".commandcode","AGENTS.md")];r.has(s)&&o.push(`# Memory from: ${s}\n\n${r.get(s)}`),r.has(a)&&o.push(`# Memory from: ${a}\n\n${r.get(a)}`);for(const e of i)if(r.has(e)){o.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===s||e===a||i.includes(e)||o.push(`# Memory from: ${e}\n\n${t}`);return o.join("\n\n---\n\n")}catch(e){return null}}At(),Rt(),__name(getEnterpriseMemoryPath,"getEnterpriseMemoryPath"),__name(getUserMemoryPath,"getUserMemoryPath"),__name(getProjectMemoryPaths,"getProjectMemoryPaths"),__name(discoverMemoryFiles,"discoverMemoryFiles"),__name(loadMemoryFile,"loadMemoryFile"),__name(function getCodeBlockRegex(){return/```[\s\S]*?```|`[^`]+`/g},"getCodeBlockRegex"),__name(function getImportRegex(){return/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm},"getImportRegex"),__name(processImports,"processImports"),__name(loadAllMemories,"loadAllMemories"),__name(openInEditor,"openInEditor"),__name(initProjectMemory,"initProjectMemory"),__name(getMemoryContent,"getMemoryContent"),An();var Ma=new Da("AgentExecutor");function agentToTool(t,n){const{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}=n;return{name:t.name,description:t.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object"}}},required:["messages"]},execute:__name(async(n,i)=>{let c=null;const l=Date.now();let d=null;try{const u=i?.permissionMode||"standard",m=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}),clientTools:r,serverTools:o,mode:u});let g=Date.now();const p=10,h=[];if(i?.onFeedUpdate){const e=Fs(t.name,n);c=Ts({name:t.name,input:e}),i.onFeedUpdate(c)}d=setInterval(()=>{if(i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{...c.metadata,elapsedSeconds:t}},i.onFeedUpdate(c)}},1e3);const f=await getConfiguredProvider(),y=await isOAuthEnforced();let w;f===wt.ANTHROPIC&&(w=await Bt.getValidAccessToken(),validateOAuthToken({token:w,provider:f}));const E=getApiBaseUrl(),S=new Co({baseUrl:E});let k=0;const v=[];let b=n?.messages;if("string"==typeof b)try{b=JSON.parse(b)}catch(e){b=[]}if(Array.isArray(b)&&b.length>0)for(const e of b)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&v.push({role:"user",content:t})}const C={stream:!0,messages:v,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:m,model:`anthropic:${getConfiguredModel()}`},P=await isTasteLearningEnabled(),T={[pt.PROJECT_SLUG]:Pa.getCurrentProjectDirName(),[pt.TASTE_LEARNING]:P.toString(),[pt.INTERNAL_TEAM_FLAG_HEADER]:y.toString()};w&&(T[pt.OAUTH_TOKEN]=`Bearer ${w}`);const A=getEnvironmentContext(),x=await getMemoryContent([]),I=crypto.randomUUID();let $="",R=!0;const D=__name(()=>{Ma.debug("[Agent] Abort signal triggered, stopping immediately"),R=!1,d&&(clearInterval(d),d=null)},"abortHandler");i?.abortSignal&&i.abortSignal.addEventListener("abort",D);try{for(;R;){if(i?.abortSignal?.aborted)throw Ma.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:S,body:{mode:"custom-agent",config:A,memory:x,threadId:I,params:{...C,messages:v}},headers:T,abortSignal:i?.abortSignal,onTextDelta:__name(e=>{k+=estimateTokens(e);const t=Date.now();if(i?.onFeedUpdate&&c&&t-g>=p){const e=Math.floor((t-l)/1e3);c={...c,metadata:{...c.metadata,tokensUsed:k,elapsedSeconds:e}},i.onFeedUpdate(c),g=t}},"onTextDelta")});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(k=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if($=t.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(t,i):t.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===n.length){const e=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);e.length>0&&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 o=[],s=new Set;let a=!1;for(const t of n){if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{const r=Go.includes(t.name),m=qo.includes(t.name)?generateToolDescription(t.name,n).catch(()=>null):Promise.resolve(null);if(r&&i?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await m;if(!await i.onPermissionRequest(t.name,n,e)){Ma.debug(`Permission denied for tool: ${t.name}`),a=!0;break}d=setInterval(()=>{if(i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{...c.metadata,elapsedSeconds:t}},i.onFeedUpdate(c)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let o=!1;const s=["path","file_path","absolutePath","filePath","directory","folder"];for(const t of s)if(t in r&&"string"==typeof r[t]){const n=r[t];if(!e.isAbsolute(n)){const s=e.resolve(process.cwd(),n);r[t]=s,o=!0,Ma.debug(`Converted '${t}': '${n}' -> '${s}'`)}}"paths"in r&&Array.isArray(r.paths)&&(r.paths=r.paths.map(t=>"string"!=typeof t||e.isAbsolute(t)?t:(o=!0,e.resolve(process.cwd(),t)))),o?(n=r,Ma.debug(`Resolved input for ${t.name}: ${Fs(t.name,n)}`)):Ma.debug(`No path resolution needed for ${t.name}: ${Fs(t.name,n)}`)}if(i?.onFeedUpdate&&c){const e=Fs(t.name,n);h.push({name:t.name,input:e}),h.length>3&&h.shift();const r=Date.now(),o=Math.floor((r-l)/1e3);c={...c,metadata:{isAgent:!0,status:"running",startTime:l,tokensUsed:k,elapsedSeconds:o,recentTools:[...h]}},Ma.debug(`Updating agent with recentTools (${h.length} tools): ${JSON.stringify(h)}`),i.onFeedUpdate(c)}const g=await executeTool(t.name,n,{abortSignal:i?.abortSignal,permissionMode:u});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");const p=checkToolOutputTokensLimit(g,t.name);if(o.push({type:"tool_result",tool_use_id:t.id,content:p}),s.add(t.id),i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{isAgent:!0,status:"running",startTime:l,tokensUsed:k,elapsedSeconds:t,recentTools:[...h]}},i.onFeedUpdate(c)}Ma.debug(`Tool executed successfully: ${t.name}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";o.push({type:"tool_result",tool_use_id:t.id,content:`Error: ${n}`,is_error:!0}),s.add(t.id),Ma.error(`Tool execution failed: ${t.name} - ${n}`)}}if(a){const e=v[v.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?s.has(e.id):"text"===e.type);t.length>0?e.content=t:v.pop()}R=!1;break}const m=[...o];v.push({role:"user",content:m})}}finally{i?.abortSignal&&i.abortSignal.removeEventListener("abort",D)}if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&c){const e=Date.now(),t=(e-l)/1e3;c={...c,output:$||"DONE",metadata:{isAgent:!0,status:"done",startTime:l,endTime:e,tokensUsed:k,elapsedSeconds:t}},i.onFeedUpdate(c)}return $||"DONE"}catch(e){if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&c){const t=Date.now(),n=(t-l)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||i?.abortSignal?.aborted;c={...c,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:l,endTime:t,tokensUsed:c?.metadata?.tokensUsed||0,elapsedSeconds:n}},i.onFeedUpdate(c)}throw e}},"execute")}}function filterToolsForMode(e){const{tools:t,clientTools:n,serverTools:r,mode:o}=e;if("standard"===o||"auto-accept"===o)return t;const s=t.filter(e=>n.includes(e)),a=t.filter(e=>r.includes(e));return[...getToolsForMode({allTools:s,mode:o}),...a]}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=t;let a=[];if("*"===e.tools)a=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=s[e];if(!t&&o.has(e)&&(t=e),t){const e=o.get(t);if(e)a.push(e);else{const e=r.find(e=>e.name===t);e&&a.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=s[t];if(!e&&o.has(t)&&(e=t),e){const t=o.get(e);if(t)a.push(t);else{const t=r.find(t=>t.name===e);t&&a.push(t)}}}return a}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:s}=e;let a=null;for(let e=0;e<5;e++){if(o?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:ht.ALPHA.GENERATE,signal:o,headers:r}),a=Be.fromReadableStream(e);s&&a.on("text",s);let i=null;a.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await a.finalMessage();if(i)throw i;return c}catch(t){if(a=t,o?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Ma.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:o})}}throw a||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof fo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof wo||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 fo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof wo||403===e?.status)return e;if(e?.message?.startsWith("Error:"))return e;let n="Error: ";return e.message?n+="Something went wrong. Please try again or contact support if the issue persists.":e.toString?n+=e.toString():n+="Unknown error occurred",new Error(n)}function processServerToolBlocks(e,t){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let n="";const r=e.content;for(const e of r)if("text"===e.type)n+=e.text;else if("server_tool_use"===e.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const{message:n,isError:o}=Ho({serverToolBlock:e,contentBlocks:r}),s=Fs(e.name,e.input),a={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:s,output:o?xs(n):n};t.onFeedUpdate(a)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}__name(agentToTool,"agentToTool"),__name(filterToolsForMode,"filterToolsForMode"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks");var Na=new Map,Oa=null;function initializeAgentManager(e){Oa=e}async function loadAgentTools(){if(!Oa)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Na.clear();for(const e of ba){const t=agentToTool(e,Oa);Na.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Oa);Na.set(t.name,t)}}async function getAgentTools(){return 0===Na.size&&await loadAgentTools(),Array.from(Na.values())}async function getAgentTool(e){return 0===Na.size&&await loadAgentTools(),Na.get(e)}function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,o=e.join(r,".commandcode","taste"),s=e.normalize(e.resolve(r,n)),a=e.normalize(o);return s.startsWith(a)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),o=e.normalize(e.join(p.homedir(),".commandcode","taste"));let s=null;if(n.startsWith(r)?s=r:n.startsWith(o)&&(s=o),!s)return{isTaste:!1};if(!n.endsWith("taste.md"))return{isTaste:!1};const a=e.relative(s,n).split(e.sep);return 1===a.length?{isTaste:!0}:2===a.length?{isTaste:!0,category:a[0]}:{isTaste:!1}}__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool"),At(),Rt(),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(function getTasteAccessError(){return"Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system."},"getTasteAccessError"),nr();var Fa=[_s,Vs,Ys,Zs,ra,ia,da,ga,pa,ha,fa,Ea,Sa,ka],La=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],_a=new Map(Fa.map(e=>[e.name,e])),Ua=new Set([...Fa.map(e=>e.name),...La.map(e=>e.name)]);function isAgentTool(e){return!Ua.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",o=isToolAllowedInMode({toolName:e,mode:r,toolParams:t});if(!o.allowed)throw new Error(o.reason||`Tool "${e}" not allowed in ${r} mode`);let s=_a.get(e);if(s||(s=await getAgentTool(e)),!s){const t=await getAgentTools(),n=[...Array.from(_a.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 a=trackToolStart({toolName:e});try{let r;return r=(!_a.has(e)||!0===s.acceptsCallbacks)&&n?await s.execute(t,n):await s.execute(t),a.end({status:"success"}),r}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message){const t=sanitizeErrorForTelemetry({error:e,label:"tool_interrupted"});throw a.end({status:"error",error:t}),e}if(e instanceof Error){const t=sanitizeErrorForTelemetry({error:e,label:"tool_error"});return a.end({status:"error",error:t}),`Error: ${e.message}`}return a.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(e){const t=e?.mode||"standard",n=[...Fa],r=await getAgentTools(),o=getToolsForMode({allTools:n,mode:t}).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),s=r.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}));let a=[];return"plan"!==t&&getMcpConnectionManager().isInitialized&&(a=getAllMcpToolSchemas()),[...o,...s,...a,...La]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var ja={};Fa.forEach(e=>{ja[e.name]=toPascalCase(e.name)}),La.forEach(e=>{ja[e.name]=toPascalCase(e.name)});var Ba={};function parseEmbeddedErrorJSON(e){const t=e.indexOf("{");if(-1===t)return null;try{const n=JSON.parse(e.slice(t));if(n?.error?.message){const r=e.slice(0,t).trim();return{status:/^\d+$/.test(r)?Number(r):null,type:n.error.type||null,message:n.error.message}}}catch{}return null}function parseErrorLine(e){try{const t=JSON.parse(e);if("error"===t?.type&&t?.error?.type&&t?.error?.message)return{type:t.error.type,message:t.error.message}}catch{}return null}function interceptStreamErrors(e){const{responseStream:t}=e;let n=null,r="";const o=new TextDecoder,s=new TransformStream({transform(e,t){const s=o.decode(e,{stream:!0});r+=s;const a=r.split("\n");r=a.pop()??"";for(const e of a){const r=e.trim();if(!r){t.enqueue((new TextEncoder).encode(e+"\n"));continue}const o=parseErrorLine(r);if(o)return n=o,void t.error(new Error(`Error: Stream error: ${o.type} - ${o.message}`));t.enqueue((new TextEncoder).encode(e+"\n"))}},flush(e){const t=r.trim();if(t){const o=parseErrorLine(t);if(o)return n=o,void e.error(new Error(`Error: Stream error: ${o.type} - ${o.message}`));e.enqueue((new TextEncoder).encode(r))}}});return{stream:t.pipeThrough(s),getStreamError:__name(()=>n,"getStreamError")}}Object.entries(ja).forEach(([e,t])=>{Ba[t]=e}),initializeAgentManager({clientTools:Fa,serverTools:La,toolsMap:_a,displayNameToToolName:Ba}),At(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors"),nr(),Rt(),Wt(),An(),$n(),At(),Rt(),qt(),Cn(),At();var za=new class extends Fe{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;get observerHasRun(){return this._observerHasRun}markObserverRun(){this._observerHasRun=!0}get importHasStarted(){return this._importHasStarted}markImportStarted(){this._importHasStarted=!0}get learningComplete(){return this._learningComplete}markLearningComplete(){this._learningComplete=!0,this.emit("learning-complete")}addEvent(e){const{type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d}=e,u={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d};this.events.unshift(u),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",u)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}};function extractLearningWithConfidence(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)\.\s+Confidence:\s*(\d+\.?\d*)/);return n?{text:n[1].trim(),confidence:parseFloat(n[2])}:null}function extractLearnings(e){const{text:t}=e;return t.split("\n").filter(e=>e.trim().startsWith("-")).map(e=>extractLearningWithConfidence({line:e})).filter(Boolean)}function compareLearnings(e){const{oldText:t,newText:n}=e,r=extractLearnings({text:t}),o=extractLearnings({text:n}),s=new Map(r.map(e=>[e.text,e.confidence])),a=[],i=[],c=[];return o.forEach(e=>{const t=s.get(e.text);void 0===t?a.push(e):e.confidence>t?i.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&c.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:a,upgraded:i,downgraded:c}}At(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings"),An(),$n(),nr();var Wa=new Da("LearningAgent"),Ha=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:Yn.LEARNING_AGENT,heading:"Learning pass failed"}}),za.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)];za.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),s=t.length-this.lastProcessedMessageIndex-1,a=Math.max(20,s),i=Math.max(0,t.length-a),c=t.slice(i);let l=0,d=!1;dlog(`[LearningAgent] analyzing ${s} new messages for patterns`);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){const e=await this.callLearningAPI({conversation:u}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.name).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&Wa.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||za.addEvent({type:"no_learnings",message:"no changes to taste"}),za.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",s="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(s=String(e.filePath||e.file_path||""),s)try{o=await y.promises.readFile(s,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const a=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&s)try{i=await y.promises.readFile(s,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=s.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:o,newText:i});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{za.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{za.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{za.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:a})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:t instanceof Error?t.message:String(t)})}return{results:n,learningsFound:r}}validateTastePath(t){const{toolName:n,input:r}=t,o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(!o||!r[o])return;const s=String(r[o]);if(e.isAbsolute(s))throw new Error(`Security: ${n} received absolute path. Only taste-relative paths are allowed (e.g., ".commandcode/taste/cli/taste.md" or ".commandcode/taste/taste.md"). Attempted: ${s}`);const a=e.normalize(s);if(a.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${s}`);const i=e.join(this.tasteDir,a);if(!e.normalize(i).startsWith(this.tasteDir))throw new Error(`Security: ${n} can only access files within .commandcode/taste/. Attempted: ${s}`)}adjustPathsForTaste(t){const{toolName:n,input:r}=t,o={...r},s={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(s&&o[s]){const t=String(o[s]);let r;const a="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)&&t.startsWith(this.tasteDir))if(a){if(!this.isValidTasteFilePath(t))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${t}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);r=t}else r=t;else{if(e.isAbsolute(t))throw new Error(`Invalid path: Absolute path outside taste directory: ${t}`);const n=e.normalize(t);if(n.startsWith(".."))throw new Error(`Security: Path traversal attempt detected: ${t}`);if(r=n.startsWith(".commandcode/taste")||n.startsWith(".commandcode"+e.sep+"taste")?n.replace(/^\.commandcode[/\\]taste/,this.tasteDir):e.join(this.tasteDir,n),r=e.normalize(r),!r.startsWith(this.tasteDir))throw new Error(`Security: Resolved path escapes taste directory: ${t} -> ${r}`);if(a&&!this.isValidTasteFilePath(r))throw new Error(`Invalid adjusted path: ${r}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}o[s]=r}return o}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isValidTasteFilePath(e))throw new Error(`Security: Invalid taste file path. Only allowed:\n - {project}/.commandcode/taste/taste.md\n - {project}/.commandcode/taste/{category}/taste.md\nAttempted: ${e}`)}async initializeTasteDirectory(){if(!y.existsSync(this.tasteDir)){y.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");y.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!y.existsSync(t))return!1;const n=y.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let o=n;for(const t of r){const n=t.name.toLowerCase().replace(/\s+/g,"-"),r=e.join(this.tasteDir,n),s=e.join(r,"taste.md");y.mkdirSync(r,{recursive:!0}),za.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const a=`# ${t.name}\n${t.learnings.join("\n")}\n`;y.writeFileSync(s,a,"utf-8");const i=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;o=o.replace(t.fullSection,i)}return y.writeFileSync(t,o,"utf-8"),!0}parseCategories(e){const{content:t}=e,n=[],r=t.split(/^# /gm).filter(e=>e.trim());for(const e of r){const t=e.split("\n"),r=t[0].trim();if(e.includes("See ["))continue;const o=t.filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:"));o.length>0&&n.push({name:r,learningCount:o.length,learnings:o,fullSection:`# ${e}`})}return n}async getTasteStructure(){return y.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(t){const{dir:n,prefix:r}=t,o=y.readdirSync(n,{withFileTypes:!0});let s="";for(let t=0;t<o.length;t++){const a=o[t],i=t===o.length-1,c=i?"└── ":"├── ";if(a.isDirectory()){s+=`${r}${c}${a.name}/\n`;const t=r+(i?" ":"│ ");s+=await this.buildTree({dir:e.join(n,a.name),prefix:t})}else if("taste.md"===a.name){const t=(y.readFileSync(e.join(n,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;s+=`${r}${c}${a.name} (${t} learnings)\n`}else s+=`${r}${c}${a.name}\n`}return s}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===wt.ANTHROPIC&&(o=await Bt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[pt.PROJECT_SLUG]:Pa.getCurrentProjectDirName(),[pt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[pt.OAUTH_TOKEN]=`Bearer ${o}`);const a=await this.getTasteTools(),i=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${i})`);const c={conversation:t,tools:a,model:i,threadId:this.sessionId};let l=0,d=null;for(;l<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:ht.ALPHA.TASTE.LEARN,body:c,headers:s,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),l++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${d.message}`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_client_error"}),context:{component:Yn.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(l>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:Yn.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":l}}),d;const n=1e3*Math.pow(2,l);dlog(`[LearningAgent] retrying API call (${l}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw d||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return y.existsSync(r)}};At(),Rt(),qt(),Wt(),An(),$n(),Cn();var Ga="claude-haiku-4-5-20251001",qa=class{static{__name(this,"CompactAgent")}request;sessionId;maxApiRetries=3;constructor(e){this.request=e.request,this.sessionId=e.sessionId}updateRequest(e){this.request=e}async compactMessages(e){const{messages:t}=e;dlog(`[CompactAgent] compacting ${t.length} messages`);try{const e=await this.callCompactAPI({messages:t});return dlog(`[CompactAgent] compaction complete: ${e.summary.length} chars`),e}catch(e){throw dlog(`[CompactAgent] ERROR: ${e instanceof Error?e.message:String(e)}`),e}}async callCompactAPI(e){const{messages:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===wt.ANTHROPIC&&(o=await Bt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[pt.PROJECT_SLUG]:Pa.getCurrentProjectDirName(),[pt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[pt.OAUTH_TOKEN]=`Bearer ${o}`);const a=t.map(e=>{const t=e.role;let n="";return"string"==typeof e.content?n=e.content:Array.isArray(e.content)&&(n=e.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("\n")),`[${t}]: ${n}`}).join("\n\n"),i={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],system:"Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\nThis summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.\n\nBefore providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:\n\n1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:\n - The user's explicit requests and intents\n - Your approach to addressing the user's requests\n - Key decisions, technical concepts and code patterns\n - Specific details like:\n - file names\n - full code snippets\n - function signatures\n - file edits\n - Errors that you ran into and how you fixed them\n - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.\n\nYour summary should include the following sections:\n\n1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail\n2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.\n3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.\n4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.\n6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.\n7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.\n8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.\n9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.\n If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.\n\nHere's an example of how your output should be structured:\n\n<example>\n<analysis>\n[Your thought process, ensuring all points are covered thoroughly and accurately]\n</analysis>\n\n<summary>\n1. Primary Request and Intent:\n [Detailed description]\n\n2. Key Technical Concepts:\n - [Concept 1]\n - [Concept 2]\n - [...]\n\n3. Files and Code Sections:\n - [File Name 1]\n - [Summary of why this file is important]\n - [Summary of the changes made to this file, if any]\n - [Important Code Snippet]\n - [File Name 2]\n - [Important Code Snippet]\n - [...]\n\n4. Errors and fixes:\n - [Detailed description of error 1]:\n - [How you fixed the error]\n - [User feedback on the error if any]\n - [...]\n\n5. Problem Solving:\n [Description of solved problems and ongoing troubleshooting]\n\n6. All user messages:\n - [Detailed non tool use user message]\n - [...]\n\n7. Pending Tasks:\n - [Task 1]\n - [Task 2]\n - [...]\n\n8. Current Work:\n [Precise description of current work]\n\n9. Optional Next Step:\n [Optional Next step to take]\n\n</summary>\n</example>\n\nPlease provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.\n\nThere may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:\n<example>\n## Compact Instructions\nWhen summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.\n</example>\n\n<example>\n# Summary instructions\nWhen you are using compact - please focus on test output and code changes. Include file reads verbatim.\n</example>",messages:[{role:"user",content:`Please summarize the following conversation.\n\n${a}`}],model:`anthropic:${Ga}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let c=0,l=null;for(;c<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${ht.ALPHA.GENERATE} with model: ${Ga}`);const e=await this.request.post({endpoint:ht.ALPHA.GENERATE,body:i,headers:s,stream:!0});if(!e)throw new Error("No response stream received");const t=Be.fromReadableStream(e);let n="",r=null;t.on("text",e=>{n+=e}),t.on("error",e=>{r=e});const o=await t.finalMessage();if(r)throw r;return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:o.usage.input_tokens,output:o.usage.output_tokens}}}catch(e){l=e instanceof Error?e:new Error(String(e)),c++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${l.message}`),l;if(c>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),l;const n=1e3*Math.pow(2,c);dlog(`[CompactAgent] retrying API call (${c}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}throw l||new Error("Compact API call failed")}};async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!E(n))return null;const r=await D.readFile(n,"utf-8"),o=r.trim();return o&&"# Taste (Continuously Learned by CommandCode.ai)"!==o&&"# Taste (Continuously Learned by CommandCode)"!==o?r:null}catch(e){return null}}function extractMessageText(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t="";for(const n of e)"text"===n.type&&(t+=n.text);return t}async function buildAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced(),n={[pt.PROJECT_SLUG]:Pa.getCurrentProjectDirName(),[pt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};if(e===wt.ANTHROPIC){const e=await Bt.getValidAccessToken();e&&(n[pt.OAUTH_TOKEN]=`Bearer ${e}`)}return n}function hasUserAndAssistantMessage(e){let t=!1,n=!1;for(const r of e)if("user"===r.message.role&&(t=!0),"assistant"===r.message.role&&(n=!0),t&&n)return!0;return!1}async function generateSessionTitle(e){const{messages:t,sessionManager:n,request:r}=e;if(!hasUserAndAssistantMessage(t))return;if(await n.loadSessionTitle())return;let o="",s="";for(const e of t)if(o||"user"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,1e3)),s||"assistant"!==e.message.role||(s=extractMessageText(e.message.content).slice(0,1e3)),o&&s)break;if(!o||!s)return;const a=`You are generating a succinct session title for a coding session based on the provided description.\n\nThe title should be:\n- Clear, concise, and accurately reflect the task\n- No more than 6 words\n- Easy to understand by a general audience\n- Free of unnecessary jargon (use technical terms only if essential)\n- Written in sentence case (capitalize only the first word and proper nouns)\n\nReturn only the title as a plain string, not JSON.\n\nExample titles:\nAdd retry logic to API\nSimplify error handling flow\nClean up unused components\n\nSession description:\n<description>User: ${o}\n\n---\n\nAssistant: ${s}</description>\n\nGenerate the session title now.`,i={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:a}],model:Et,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},c=await buildAuthHeaders(),l=await r.post({endpoint:ht.ALPHA.GENERATE,body:i,headers:c,stream:!0}),d=Be.fromReadableStream(l);let u="";d.on("text",e=>{u+=e}),await d.finalMessage(),u=u.trim(),u&&(await n.saveSessionTitle(u),dlog("Session",`Title generated: ${u}`))}At(),Rt(),__name(getTasteContent,"getTasteContent"),Cn(),At(),qt(),Wt(),An(),$n(),Cn(),Rt(),__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle");var Va=new Da("ContextEngine"),Ka=200,Ja=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 Co({baseUrl:n}),this.callbacks=e,this.sessionManager=new Pa(t),this.learningAgent=new Ha({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new qa({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new Co({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,Va.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),Va.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=fs("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>Va.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n){let r=e,o=[];try{const t=await processFileReferences(e);if(r=t.processedContent,o=t.fileReferences,o.length>0){const e=o.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(r=`${n}\n\n${r}`);const s=fs(e);t&&t.length>0&&(s.metadata={...s.metadata,images:t}),o&&o.length>0&&(s.metadata={...s.metadata,fileReferences:o}),this.callbacks.onFeedUpdate(s);const a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),r.trim()&&a.push({type:"text",text:r});const i={role:"user",content:a},c=crypto.randomUUID(),l=this.createMessageWithMeta(i,{messageId:c});this.addMessageAndSync(l),this.checkpointManager.createSnapshot({messageId:c}).catch(e=>Va.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,s).catch(e=>Va.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const d=await this.processMessages();return this.triggerTitleGeneration(),d}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){Va.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}triggerTitleGeneration(){this.titleGenerationInFlight||(this.titleGenerationInFlight=!0,generateSessionTitle({messages:this.messages,sessionManager:this.sessionManager,request:this.request}).catch(e=>{dlog("Session",`Title generation failed: ${e instanceof Error?e.message:String(e)}`)}).finally(()=>{this.titleGenerationInFlight=!1}))}async processMessages(){let e="";this.requestInterrupted=!1,this.abortController=new AbortController,this.learningAgent.setAbortSignal(this.abortController.signal);let t=!1;for(;;)try{this.checkIfInterrupted(),t||(this.initializeInteractionTokens(),t=!0);const{body:n,headers:r}=await this.prepareAPICall(),o=await this.callAPIWithRetry({body:n,headers:r});this.checkIfInterrupted(),this.updateContextUsage(o),await this.checkAndCompactIfNeeded();const s=o.content.filter(e=>"tool_use"===e.type),a=o.content.filter(e=>"server_tool_use"===e.type);if(e=a.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===s.length){const t=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===a.length){const t=ws(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>Va.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>Va.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=fs(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>Va.error(`Failed to save messages: ${e}`)),this.triggerLearningAgent();continue}}break}const i=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(i.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:i})),e.trim()){const t=ws(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:s}),{toolResults:l,executedToolIds:d,permissionDenied:u}=c;if(u){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const m=[...l];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){m.push({type:"text",text:t});const e=fs(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>Va.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&Va.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){Va.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return Va.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.messages.map(e=>e.message)}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};Va.debug(`Manual compact: ${this.messages.length} messages`);const e=this.contextTokensUsed;return await this.summarizeAndCompact(),{tokensSaved:Math.max(0,e-this.contextTokensUsed),didCompact:!0}}async compactConversation({preserveCurrentInteraction:e=!1}={preserveCurrentInteraction:!1}){const t=this.messages.length,n=this.contextTokensUsed;let r=-1;if(e)for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if("user"===t.message.role){const n=t.message.content;if(!Array.isArray(n)){r=e;break}if(!n.some(e=>"tool_result"===e.type)){r=e;break}}}let o=0;const s=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],a=n.message.role;if(e&&t>=r&&-1!==r)s.push(n);else{if("user"===a){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){o+=estimateTokens(n.message);continue}s.push(n)}else s.push(n)}else if("assistant"===a){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)o+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?s.push({...n,message:{...n.message,content:r}}):o+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&s.push(n)}"user"!==a&&"assistant"!==a&&(o+=estimateTokens(n.message))}}this.messages=s,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,n-o);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:Ra}),{messagesRemoved:t-s.length,tokensSaved:o}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){}}))}async syncMessageToShare(e,t){try{const n=go.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:ht.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 o;n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n),n===wt.ANTHROPIC&&(o=await Bt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={tools:t,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},a={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:s,threadId:this.sessionManager.getSessionId(),permissionMode:e};Va.debug(`calling API (${s.model}, ${this.messages.length} msgs, ${t.length} tools)`);const i=await isTasteLearningEnabled(),c={[pt.PROJECT_SLUG]:Pa.getCurrentProjectDirName(),[pt.TASTE_LEARNING]:i.toString(),[pt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(c[pt.OAUTH_TOKEN]=`Bearer ${o}`),{body:a,headers:c}}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:ht.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const o=Be.fromReadableStream(n);o.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let s=null;o.on("error",e=>{s="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const a=await o.finalMessage();if(s)throw s;return this.callbacks.onRetryUpdate?.(null),a}catch(e){const o=r?.(),s=o?Object.assign(new Error(o.message),{type:o.type,error:{type:o.type,message:o.message}}):e;if(t=s,this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(s))throw trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"non_retryable_api_error"}),context:{component:Yn.CONTEXT_ENGINE,heading:"Non-retryable API error",code:s?.status||s?.statusCode}}),this.formatAPIError(s);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:Yn.CONTEXT_ENGINE,code:s?.status||s?.statusCode,"retry.attempts":10}}),this.formatAPIError(s);trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"generate_retry_attempt"}),context:{heading:"Generate API retry",component:Yn.CONTEXT_ENGINE,code:s?.status||s?.statusCode,"retry.attempt":n+1,"retry.max":10}});const a=Math.min(n,10),i=100*Math.pow(2,a),c=Math.max(i,1e3),l=Math.min(c,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:l,signal:this.abortController?.signal})}}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){const{message:t}=this.extractErrorMessage(e),n=t?.toLowerCase()||"",r="Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")||this.requestInterrupted||this.abortController?.signal.aborted,o="Insufficient credits"===t||n.includes("insufficient credits"),s=e instanceof yo||401===e?.status||e instanceof wo||403===e?.status,a=e?.type||e?.error?.type,i="rate_limit_error"===a||429===e?.status||n.includes("rate limit"),c="overloaded_error"===a||529===e?.status||n.includes("overloaded");return r||o||s||i||c}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.error?.message){const n=parseEmbeddedErrorJSON(e.error.message);return n?{...n,status:n.status||t}:{status:t,type:e.error.type||null,message:e.error.message}}const n=e?.message;if("string"==typeof n){const e=parseEmbeddedErrorJSON(n);if(e)return{...e,status:e.status||t}}return{status:t,type:e?.type||null,message:e?.message||null}}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.requestInterrupted||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=this.extractErrorMessage(e),n=t.status,r=t.type,o=t.message;dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",o);const s=o?.toLowerCase().includes("insufficient credits");if(s)return new Error("Insufficient credits");const a=o?.toLowerCase().includes("oauth authentication required");if(a)return e;if(e instanceof wo||403===e?.status)return e;if(e instanceof yo||401===e?.status)return new Error('Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.');const i=getSupportId();let c="";if(o)if(o.includes("Invalid 'Authorization' header"))c='Error: Authentication failed. Run "cmd login" to sign in again.';else{let e=o;for(;e.startsWith("Error: ");)e=e.substring(7);e.includes("Unexpected event order")&&(e="The API returned an error. This may be due to high traffic or a temporary issue.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>Ka&&(t=t.substring(0,Ka)+"..."),c=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const s=o.toLowerCase(),a="overloaded_error"===r||s.includes("overloaded"),l="rate_limit_error"===r||s.includes("rate limit");c+=a?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":l?'\n\nYou can wait a moment and try again, or type "continue" to retry.':'\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==i&&(c+=`\nRequest ID: ${i}`)}else if(e.toString){const t=e.toString();c=t.length>Ka?t.substring(0,Ka)+"...":t}else c="Error: Unknown error occurred";return new Error(c)}async executeToolBlocks(e){const t=new Set;let n=!1;const r=[],o=[];for(const s of e.toolBlocks){this.checkIfInterrupted();const e=crypto.randomUUID(),a=Go.includes(s.name),i=qo.includes(s.name)?this.getToolDescription(s):Promise.resolve(null);let c=null;try{a&&this.callbacks.onPermissionRequest&&(c=await i);const t=await this.checkToolPermission(s,c);if(t.needsPermission&&!t.allowed){this.handlePermissionDenied(s,e),n=!0;break}}catch(n){const r=n instanceof Error?n.message:"Permission check failed";this.showToolError(s,r,e,c),o.push({toolBlock:s,toolResult:{type:"tool_result",tool_use_id:s.id,content:`Error: ${r}`,is_error:!0}}),t.add(s.id);continue}null===c&&(c=await i),r.push({toolBlock:s,entryId:e,description:c})}const s=[];for(const{toolBlock:e,toolResult:n}of o)s.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=await this.executeSingleTool(e);return isAgentTool(e.name)||this.showToolSuccess(e,r,t,n),{toolBlock:e,toolResult:{type:"tool_result",tool_use_id:e.id,content:r}}}));for(let n=0;n<e.length;n++){const o=e[n],{toolBlock:a,entryId:i,description:c}=r[n];if("fulfilled"===o.status)s.push(o.value.toolResult),t.add(a.id);else{const e=o.reason instanceof Error?o.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(a.name)?t.add(a.id):(s.push({type:"tool_result",tool_use_id:a.id,content:`Error: ${e}`,is_error:!0}),t.add(a.id),this.showToolError(a,e,i,c))}}}return{toolResults:s,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 Va.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 Go.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),o=estimateTokens(r);return this.currentInteractionTokens+=o,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),r}handlePermissionDenied(e,t){const n=Fs(e.name,e.input),r={..."edit_file"===e.name?e.input:{},permissionDenied:!0},o={...Es(e.name,n,r),id:t},s=As(o,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(s)}showToolSuccess(e,t,n,r){let o="edit_file"===e.name?e.input:void 0;if("read_file"===e.name){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(o={...o||{},isTasteFile:!0,tasteCategory:e.category})}}const s={...e.input,...o?.isTasteFile?{isTasteFile:o.isTasteFile}:{},...o?.tasteCategory?{tasteCategory:o.tasteCategory}:{}},a=Fs(e.name,s),i={...Es(e.name,a,o),id:n,...r?{description:r}:{}},c=As(i,t);this.callbacks.onFeedUpdate(c)}showToolError(e,t,n,r){const o=Fs(e.name,e.input),s="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,a={...Es(e.name,o,s),id:n,...r?{description:r}:{}},i=As(a,xs(t));this.callbacks.onFeedUpdate(i)}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=ws(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:o}=Ho({serverToolBlock:e,contentBlocks:n}),s=Fs(e.name,e.input),a=Es(e.name,s),i=As(a,o?xs(r):r);this.callbacks.onFeedUpdate(i)}if(t.trim()){const e=ws(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:Ra})}async checkAndCompactIfNeeded(){const e=Math.floor(Ra*Ct.TIER_1_THRESHOLD),t=Math.floor(Ra*Ct.TIER_2_THRESHOLD),n=Math.floor(Ra*Ct.TIER_3_THRESHOLD);try{if(this.contextTokensUsed>n){Va.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){Va.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${Ct.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(Ct.TIER_2_KEEP_COUNT);return Va.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=Ct.TIER_1_KEEP_COUNT;if(t>n){Va.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);Va.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){Va.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){e>0&&this.callbacks.onFeedUpdate(ys(`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 o=new Set(r.slice(-e).map(e=>e.id)),s=new Set(r.filter(e=>!o.has(e.id)).map(e=>e.id)),a=[];for(const e of this.messages){const t=e.message.role,r=e.message.content;if("user"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_result"!==e.type||!s.has(e.tool_use_id)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;a.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_use"!==e.type||!s.has(e.id)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;a.push({...e,message:{...e.message,content:t}});continue}a.push(e)}this.messages=a,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,t-n);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:Ra}),{toolsRemoved:s.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return Va.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(Ct.TIER_2_KEEP_COUNT);Va.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});Va.debug(`Summarization complete: ${r.summary.length} chars, used ${r.tokensUsed.input}/${r.tokensUsed.output} tokens`);const o=this.createMessageWithMeta({role:"user",content:[{type:"text",text:`This is an auto-compacted summary of the earlier conversation that ran out of context.\n\n${r.summary}`}]},{isSummary:!0}),s=this.contextTokensUsed,a=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[o,...t],await this.sessionManager.saveMessages(this.messages);const i=estimateTokens(o.message),c=Math.max(0,s-a+i);this.contextTokensUsed=c,this.callbacks.onContextUsageUpdate?.({current:c,limit:Ra}),Va.debug(`Tier 3 summarization complete: reduced from ${s} to ~${c} tokens`)}catch(e){Va.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(Ct.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=Ct.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const o=this.messages[r],s=estimateTokens(o.message);if(t+s>e){n=r+1;break}t+=s;const a=o.message.content;Array.isArray(a)&&a.some(e=>"tool_result"===e.type)}n=Math.min(n,this.messages.length-3),n=Math.max(0,n);let r=0;this.messages[0]?.meta?.isSummary&&(r=1);for(let e=r;e<n;e++){const t=this.messages[e].message.content;if(Array.isArray(t)&&t.some(e=>"image"===e.type)){n=e;break}}for(;n>r&&"user"===this.messages[n].message.role;)n--;return{messagesToSummarize:this.messages.slice(r,n),messagesToKeep:this.messages.slice(n),keepStartIndex:n}}getCheckpointManager(){return this.checkpointManager}listCheckpoints(){return this.checkpointManager.listCheckpoints()}hasCheckpoints(){return this.checkpointManager.hasCheckpoints()}async restoreToCheckpoint(e){const{messageId:t,mode:n}=e;this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()});const r=this.sessionManager.getMessageIndexById({messageId:t,messages:this.messages});let o=0;if(-1!==r&&("conversation"===n||"both"===n))for(let e=r;e<this.messages.length;e++)o+=estimateTokens(this.messages[e].message);const s=await this.checkpointManager.restore({messageId:t,mode:n});return!s.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-o),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:Ra})),s}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}};function getShellPathAndName(){const e=process.env.SHELL||"/bin/bash",t=e.split("/").pop()?.toLowerCase()||"bash";return{path:e,name:t}}function getShellType(e){return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":"unknown"}function detectUserShell(){const{path:e,name:t}=getShellPathAndName();return"win32"===process.platform?{type:"unknown",path:e}:{type:getShellType(t),path:e}}At(),At(),At(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var Ya=["no job control","cannot set terminal process group"],Qa=null;function getShellInfo(){return Qa||(Qa=detectUserShell()),Qa}__name(getShellInfo,"getShellInfo");var Za=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{let s=!1;const a=__name(e=>{s||(s=!0,t(e))},"doResolve"),i=getShellInfo(),c="bash"===i.type||"zsh"===i.type,l=c?i.path:"/bin/bash",d=x(l,c?["-i","-c",e]:["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let u="",m="",g=null;n>0&&(g=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),a({stdout:u,stderr:m+(m?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(u.length+n.length>sa){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void a({stdout:u,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}u+=n}catch(e){m+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,d.kill("SIGTERM")}}),d.stderr?.on("data",e=>{try{const t=e.toString();if(m.length+t.length>aa)return void(m+="\n[Error output truncated: too large]");m+=t}catch(e){m+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{g&&clearTimeout(g);const n=c?m.split("\n").filter(e=>!Ya.some(t=>e.includes(t))).join("\n"):m;a({stdout:u.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{g&&clearTimeout(g),a({stdout:u,stderr:m+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),Xa=__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"),ei=__name(()=>{const[e,t]=z({isExecuting:!1,currentCommand:null});return{executeBash:G(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Za(e,{timeout:3e4,cwd:process.cwd()}),o=Xa(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]=As(r,o);break}}return n}),r()}catch(t){const o=t instanceof Error?t.message:"Unknown error occurred";n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const r=n[t];if("bash"===r.role&&"command"in r&&r.command===e&&!r.output){n[t]=As(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");At(),At(),Rt();var ti=class extends Fe{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 M.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 M.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await M.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 M.writeFile(n,JSON.stringify(t,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const n=t.join(this.projectRoot,".commandcode"),r=t.join(n,"settings.local.json"),o=`Bash(${e.split(" ")[0]}:*)`;try{let e;await M.mkdir(n,{recursive:!0});try{const t=await M.readFile(r,"utf-8");e=JSON.parse(t)}catch(t){e={permissions:{allow:[],deny:[],defaultMode:"ask"}}}e.permissions||(e.permissions={allow:[],deny:[],defaultMode:"ask"}),e.permissions.allow||(e.permissions.allow=[]),e.permissions.allow.includes(o)||e.permissions.allow.push(o),await M.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},ni=__name((e={})=>{const[t,n]=z(null),[r,o]=z(null),[s,a]=z(!1);return H(()=>{const t=e.projectRoot||process.cwd(),r=new ti(t);return r.on("permission-request",(t,n)=>{o(t),a(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),a(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:G(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:G(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:G(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),a(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),a(!1)}},[t]),clearSessionPermissions:G(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:G(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:G((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:G(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r="auto-accept"===("boolean"==typeof t?t?"auto-accept":"standard":t),o=["create","edit","delete","execute","shellCommands"];for(const e of o)n.setAutoApprove(e,r)}At(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),At();var ri=__name(()=>process.stdout.write("win32"===process.platform?"[2J[0f":"[2J[3J[H"),"clearConsole");function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",o=!1,s="";for(let e=0;e<t.length;e++){const a=t[e];'"'!==a&&"'"!==a||o?a===s&&o?(o=!1,s=""):" "!==a||o?r+=a:(r.trim()&&n.push(r.trim()),r=""):(o=!0,s=a)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const o=n.substring(0,r),s=n.substring(r+1).trim();return{commandName:o,rawArguments:s,positionalArgs:parsePositionalArguments({input:s})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let o=t;return o=o.replace(/\$ARGUMENTS/g,n),o=o.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:o}}function loadCustomCommands(){const e=[],n=t.join(process.cwd(),".commandcode","commands"),r=t.join(h.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,o=""){if(w.existsSync(n))try{const s=w.readdirSync(n,{withFileTypes:!0});for(const a of s){const s=t.join(n,a.name);if(a.isDirectory())loadCommandsFromDirectory(s,r,o?`${o}/${a.name}`:a.name);else if(a.isFile()&&a.name.endsWith(".md")){const n=t.basename(a.name,".md"),i=w.readFileSync(s,"utf-8").trim();e.push({name:n,source:r,content:i,subdirectory:o})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(r,"user"),loadCommandsFromDirectory(n,"project"),e}function customCommandsToMenuItems(e){return e.map(e=>{const t=`/${e.name}`;let n;return n=e.subdirectory?"project"===e.source?`(project: ${e.subdirectory})`:`(user: ${e.subdirectory})`:"project"===e.source?"(project)":"(user)",{command:t,description:`${e.content.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim()} ${n}`}})}function getCustomCommandContent(e){const t=loadCustomCommands(),n=e.startsWith("/")?e.substring(1):e,r=t.find(e=>e.name===n);return r?r.content:null}function isDirectoryEmpty(){try{return 0===P(process.cwd()).length}catch{return!1}}async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new Co({baseUrl:e});return await t.get({endpoint:ht.ALPHA.WHOAMI})}At(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),Gt(),At(),Rt(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),At(),__name(isDirectoryEmpty,"isDirectoryEmpty"),At(),Rt(),__name(getAuthenticatedEntity,"getAuthenticatedEntity"),In(),At();var oi=["Code","Code - Insiders","VSCodium","Cursor"],si="Code",ai={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},ii=__name(e=>u(e).href,"formatPathForTerminal"),ci=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),li=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),di=__name(({home:t,configSegments:n,variants:r})=>{for(const o of r){const r=li({home:t,configSegments:n,variant:o});if(y.existsSync(e.dirname(r)))return o}return null},"findExistingVariant"),ui=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&mi(t.when)},"isTerminalShiftEnterBinding"),mi=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),gi=__name(e=>{const t=ze(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),pi=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),hi=__name(({error:e,content:t})=>{const n=e.message;return pi(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"),fi=__name(e=>{let t="",n=!1,r=!1;for(let o=0;o<e.length;o++){const s=e[o];if(n)t+=s,r?r=!1:"\\"===s?r=!0:'"'===s&&(n=!1);else if('"'!==s){if(","===s){let t=o+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=s}else n=!0,t+=s}return t},"removeTrailingCommas"),yi=__name(e=>{try{const t=ze(e),n=fi(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:hi({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),wi=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:ii(t)}),"createSuccessResult"),Ei=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:ii(t)}),"createErrorResult"),Si=__name(()=>{const t=p.homedir(),n=p.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=ci(n);if(!r)return li({home:t,configSegments:[".config"],variant:si});const o=di({home:t,configSegments:r,variants:oi});return li({home:t,configSegments:r,variant:o??si})},"getVSCodeKeybindingsPath"),ki=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)ui(n)&&(n.command===ai.command&&n.args?.text===ai.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),vi=__name(t=>{try{if(!y.existsSync(t)){const n=e.dirname(t);return y.existsSync(n)||y.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=y.readFileSync(t,"utf-8");if(gi(n))return{rawContent:n,keybindings:[]};const r=yi(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:Ei({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):Ei({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return Ei({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),bi=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(ai,null,2);if(gi(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return Ei({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?Ei({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,o+1)+",\n"+n+e.substring(o+1)},"generateNewContent");function setupVSCodeTerminal(){const e=Si();try{const t=vi(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=ki(r);if(o.hasConflicting)return Ei({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return wi({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=bi({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(y.writeFileSync(e,s,"utf-8"),wi({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return Ei({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"),At(),Rt(),Cn(),At();var Ci={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return Ci[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Le(t);return e.join(h.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 D.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(t,n=process.cwd()){try{const r=getGlobalProjectSettingsPath(n),o=e.dirname(r);await D.mkdir(o,{recursive:!0}),await D.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),za.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 D.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"),At(),Cn(),Rt(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),At(),Cn();var Pi=e.join(p.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=A(e,{encoding:"utf8"}),n=We.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 D.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const o=await D.readdir(t);for(const s of o){if(!/^\d{4}$/.test(s))continue;const o=e.join(t,s);if(!(await D.stat(o)).isDirectory())continue;const a=await D.readdir(o);for(const t of a){if(!/^\d{2}$/.test(t))continue;const a=e.join(o,t);if(!(await D.stat(a)).isDirectory())continue;const i=await D.readdir(a);for(const o of i){if(!/^\d{2}$/.test(o))continue;const i=e.join(a,o);if(!(await D.stat(i)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${s}/${t}/${o}`});const c=(await D.readdir(i)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(i,t));r.push(...c)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const o=[];for(let s=0;s<e.length;s+=n){const a=e.slice(s,s+n),i=await Promise.all(a.map(t));for(const e of i)null!==e&&o.push(e);r?.(Math.min(s+n,e.length),e.length)}return o}async function findCodexSessions(t,n,r=0){const o=t||process.cwd(),s=[];dlog(`[Codex] scanning for project: ${o}`);const a=await findAllSessionFiles(Pi,n);if(0===a.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${a.length} session files to scan`),n?.({phase:"reading",totalFiles:a.length,processedFiles:0,matchedSessions:0});let i=0;const c=await processFilesInBatches(a,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===o)try{const r=await D.stat(t),o=e.basename(t,".jsonl");return{id:n.id||o,filePath:t,createdAt:new Date(n.timestamp||r.birthtime),lastModified:r.mtime,messageCount:0,agent:"codex",projectDir:n.cwd}}catch{return null}return null},10,(e,t)=>{i=s.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:i})});s.push(...c);const l=r>0?s.slice(0,r):s;return dlog(`[Codex] matched ${l.length} sessions for project`),n?.({phase:"complete",totalFiles:a.length,processedFiles:a.length,matchedSessions:l.length}),l.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("event_msg"===n.type&&"user_message"===n.payload?.type&&n.payload?.message){const e=n.payload.message;"string"==typeof e&&e.trim()&&t.push(e.trim())}}catch{continue}t.length>0&&dlog(`[Codex] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Codex] failed to extract prompts: ${e}`,t)}return t}async function loadProjectSettings(){return loadMergedProjectSettings()}async function saveProjectSettings(e){await saveGlobalProjectSettings(e)}function isOnboardingDone(e){return!0===e?.skipped||!0===e?.completed}function buildAgentSessionsList(e){return Object.entries(e).filter(([e,t])=>t&&t.length>0).map(([e,t])=>({agent:e,sessionIds:t,displayName:getAgentDisplayName(e)}))}async function checkOnboardingConditions(){try{const e=(await loadProjectSettings()).tasteOnboarding,t=!0===e?.demoShown;if(isOnboardingDone(e))return dlog("[Onboarding] "+(e?.skipped?"user skipped":"already completed")),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!0,agentSessions:[],demoShown:t};const n=await findNewSessions(e?.learnedSessions||{}),r=(n["claude-code"]?.length||0)+(n.codex?.length||0);return r>0?(dlog(`[Onboarding] found ${r} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:r,hasTasteContent:!0,agentSessions:buildAgentSessionsList(n),demoShown:t}):t?(dlog("[Onboarding] no new sessions to learn from"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t}):(dlog("[Onboarding] first time user, will show demo"),{shouldTrigger:!0,reason:"no_sessions",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:!1}}}async function getSessionFilesFromDir(e){try{return(await D.readdir(e)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints")).map(e=>e.replace(".jsonl",""))}catch{return[]}}async function findNewSessions(t){const n={},r=t["claude-code"]||[],o=t.codex||[];try{const t=e.join(p.homedir(),".claude","projects");await D.access(t);const o=getProjectDirName(process.cwd()),s=(await D.readdir(t)).filter(e=>e===o);for(const o of s){const s=e.join(t,o);if((await D.stat(s)).isDirectory()){const e=await getSessionFilesFromDir(s);e.length>0&&(n["claude-code"]=e.filter(e=>!r.includes(e)))}}dlog(`[Sessions] claude-code: ${n["claude-code"]?.length||0} new, ${r.length} learned`)}catch{dlog("[Sessions] claude projects dir not found")}try{const e=await findCodexSessionIds();e.length>0&&(n.codex=e.filter(e=>!o.includes(e)));dlog(`[Sessions] codex: ${n.codex?.length||0} new, ${o.length} learned`)}catch{dlog("[Sessions] codex sessions not found")}return n}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0,await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function markDemoShown(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.demoShown=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:o}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions();e.shouldTrigger?(dlog(`[Onboarding] starting taste learning (${e.reason})`),o(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),__name(loadProjectSettings,"loadProjectSettings"),__name(saveProjectSettings,"saveProjectSettings"),__name(isOnboardingDone,"isOnboardingDone"),__name(buildAgentSessionsList,"buildAgentSessionsList"),__name(checkOnboardingConditions,"checkOnboardingConditions"),__name(getSessionFilesFromDir,"getSessionFilesFromDir"),__name(findNewSessions,"findNewSessions"),__name(markSessionsAsLearned,"markSessionsAsLearned"),__name(markOnboardingSkipped,"markOnboardingSkipped"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markDemoShown,"markDemoShown"),__name(triggerTasteOnboarding,"triggerTasteOnboarding"),At(),Rt(),At();var Ti="# Taste (Continuously Learned by CommandCode.ai)",Ai=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return Ai.test(t)?t.replace(Ai,`$1${Ti}`):t}__name(migrateHeader,"migrateHeader");var xi=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await D.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await D.access(r);const e=await D.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await D.writeFile(r,t,"utf-8")}catch{await D.writeFile(r,Ti+"\n\n")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await D.access(n),!0}catch{return!1}}};An(),$n(),sn(),At(),At(),Rt(),At(),At(),Rt();var Ii=__name(()=>t.join(h.homedir(),".commandcode","agents"),"getRootAgentDir"),$i=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Ri=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=z("idle"),[a,i]=z(""),c=[...Fa.map(e=>e.name),...La.map(e=>e.name)],l=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void i("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?Ii():$i();await M.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),a=Array.from(e.selectedTools).map(e=>ja[e]||e).join(", "),i=0===e.selectedTools.size?"none":e.selectedTools.size===c.length?'"*"':JSON.stringify(a),l=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${i}\n---\n\n${e.sysPrompt}\n`;await M.writeFile(s,l,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),i(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");Z((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||l()});const d=Array.from(e.selectedTools).map(e=>ja[e]||e).join(", "),u="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return B.createElement(V,{flexDirection:"column",gap:1},B.createElement(V,{flexDirection:"column"},B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"Name:"),B.createElement(K,{color:"gray"},e.agentType)),B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"Location:"),B.createElement(K,{color:"gray"},u)),B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"Tools:"),B.createElement(K,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===c.length?"*":d))),B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"Description"),B.createElement(K,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),B.createElement(K,{color:"gray"},e.ccToolDefinition),B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"System Prompt:")),B.createElement(K,{color:"gray"},e.sysPrompt),!r&&B.createElement(V,{marginTop:1},"idle"===o&&B.createElement(V,{gap:1},B.createElement(K,{color:"green",dimColor:!0},"Press"),B.createElement(K,{color:"green",bold:!0},"Enter"),B.createElement(K,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===o&&B.createElement(K,{color:"yellow"},"Saving agent..."),"saved"===o&&B.createElement(K,{color:"green"},"✓ ",a),"error"===o&&B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"red"},"✗ Error: ",a),B.createElement(K,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),Di=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=z("menu"),a=[...Fa.map(e=>e.name),...La.map(e=>e.name)];let i=new Set;if("*"===e.tools||'"*"'===e.tools)i=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>Ba[e]||e);i=new Set(t)}const c={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(Z((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return B.createElement(V,{flexDirection:"column"},B.createElement(Ri,{config:c,onSaveComplete:()=>s("menu"),viewOnly:!0}),B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray"},"Press Enter to go back")));if("edit"===o)return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"yellow"},"Edit functionality coming soon..."),B.createElement(K,{color:"gray"},"Press Esc to go back"));if("delete"===o){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],o=__name(async r=>{if("confirm-delete"===r.value)try{await M.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return B.createElement(V,{flexDirection:"column",gap:1},B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"red"},"Delete agent"),B.createElement(K,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),B.createElement(V,null,B.createElement(He,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"},` ${t}`)})))}return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"white",bold:!0},e.name),B.createElement(V,{marginTop:1},B.createElement(He,{items:l,onSelect:d,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"},` ${t}`)})),B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Mi=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=z([]),[s,a]=z([]),[i,c]=z([]),[l,d]=z(!0),[u,m]=z(!1),[g,p]=z(null),[f,y]=z(!1),w=__name(()=>t.join(h.homedir(),".commandcode","agents"),"getRootAgentDir"),E=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),S=__name(async(e,n)=>{try{m(!1);const r=(await M.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await M.readFile(o,"utf-8"),{data:a,content:i}=Oe(s);let c=a.tools||"";return"*"!==c&&'"*"'!==c||(c="*"),{name:a.name||r.replace(".md",""),description:a.description||"",tools:c,sysPrompt:i.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");H(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([S(w(),"personal"),S(E(),"project")]),n=ba.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));o(e),a(t),c(n),d(!1)},"loadAgents")()},[u]);const k=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{k.push({label:e.name,value:e.filePath})}),s.forEach(e=>{k.push({label:e.name,value:e.filePath})});const v=r.length+s.length,b=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(p(e),y(!0))}},"handleAgentSelect");if(l)return B.createElement(K,{color:"gray"},"Loading agents...");if(f&&g){const e=g.filePath.startsWith("__builtin__:");return B.createElement(Di,{agent:g,onBack:()=>{y(!1),p(null)},setRevalidateAgent:m,isReadOnly:e})}const C=__name(({isSelected:e,label:t})=>{const n=k.find(e=>e.label===t),o=n?.value||"",a=r[0]?.filePath===o,i=s[0]?.filePath===o;return B.createElement(V,{flexDirection:"column"},a&&r.length>0&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray",bold:!0},"User agents")),i&&s.length>0&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray",bold:!0},"Project agents")),B.createElement(V,null,B.createElement(K,{color:"white"},e?">":" "),B.createElement(K,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return B.createElement(V,{flexDirection:"column"},B.createElement(V,{marginBottom:1},B.createElement(K,{color:"white",bold:!0},"Agents"),v>0?B.createElement(K,{color:"gray"}," ","(",v," agent",v>1?"s":"",")"):B.createElement(K,{color:"gray"}," (No custom agents)")),n&&B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{color:"green",dimColor:!0},"Created agent: ",n)),B.createElement(He,{items:k,onSelect:b,indicatorComponent:()=>null,itemComponent:C}),i.length>0&&B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(K,{color:"gray",bold:!0},"Default agents"),i.map(e=>B.createElement(K,{key:e.filePath,color:"gray"}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(K,{color:"gray"},"Create specialized subagents that Command Code can delegate to."),B.createElement(K,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");At(),Rt(),At(),At(),Rt();var Ni=__name(({onSelect:e})=>B.createElement(He,{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(K,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector");At(),pn(),Rt(),yn(),vn();var Oi=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=z(!1),[m,g]=z(!1),p=G(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),h=G(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||m){if(!m||t.isPasteEnd){if(m&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[m,a]);return"agentType"===e?B.createElement(B.Fragment,null,B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(ja).some(e=>Le(e)===Le(t))||Object.keys(ja).some(e=>Le(e)===Le(t)))&&B.createElement(K,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Le(t))&&B.createElement(K,{color:"red"},"⚠ This name is reserved. Reserved names:"," ",va.join(", "))),B.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Le(t);Object.values(ja).some(t=>Le(t)===e)||Object.keys(ja).some(t=>Le(t)===e)||isReservedAgentName(e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?B.createElement(B.Fragment,null,B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"white"},"Enter the system prompt for your agent:"),B.createElement(K,{color:"gray"},"Be comprehensive for best results.")),B.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?B.createElement(B.Fragment,null,B.createElement(K,{color:"white"},"When should ","Command Code"," use this agent?"),B.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&l()},onChange:h,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");At();var Fi=__name(({onSelect:e})=>B.createElement(He,{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(K,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector");At(),pn(),At();var Li=["·","○","◇","☆","✧","☆","◇","○","⌘"],_i=[8,5,4,4,4,4,4,5,20],Ui=[5,4,4,4,4,4,5],ji=__name(e=>{const t=e%88;let n=0;for(let e=0;e<_i.length;e++)if(n+=_i[e],t<n)return Li[e];const r=t-58;n=0;for(let e=0;e<Ui.length;e++)if(n+=Ui[e],r<n)return Li[7-e];return Li[0]},"getWaveSymbol"),Bi=["#8A6BA3","#B799E6","#E4CCFF","#FFFFFF","#E4CCFF","#B799E6","#8A6BA3"];function ShimmerText({text:e}){const[t,n]=z(0);H(()=>{const t=setInterval(()=>{n(t=>(t+1)%(e.length+10))},50);return()=>clearInterval(t)},[e.length]);const r=__name(e=>{const n=e-(t-5);return n>=0&&n<Bi.length?Bi[n]:"#B799E6"},"getCharColor");return B.createElement(K,null,e.split("").map((e,t)=>B.createElement(K,{key:t,color:r(t)},e)))}function CMDIcon(){const[e,t]=z(0);return H(()=>{const e=setInterval(()=>{t(e=>(e+1)%88)},15);return()=>clearInterval(e)},[]),B.createElement(K,{color:"#E4CCFF",bold:!0},ji(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var zi=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=z(0),s=getTerminalWidth();function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}H(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),s=e>0?t:-t,a=setInterval(()=>{o(e=>{const t=e+s;return s>0&&t>=n||s<0&&t<=n?n:t})},30);return()=>clearInterval(a)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");const a=s>70,i=s>40&&s<=70;return B.createElement(V,{width:s,height:1,paddingLeft:0,marginLeft:0},B.createElement(CMDIcon,null),B.createElement(V,{marginRight:1},B.createElement(ShimmerText,{text:e})),a?B.createElement(B.Fragment,null,B.createElement(V,{columnGap:1},B.createElement(K,{dimColor:!0},`(${formatTime3(t)}`),B.createElement(K,{dimColor:!0},"•"),B.createElement(K,{color:"gray"},Se.arrowDown),B.createElement(K,{dimColor:!0},`${formatToken(Math.round(r))}`),B.createElement(K,{dimColor:!0},"•"),B.createElement(V,{columnGap:1},B.createElement(K,{bold:!0,color:"gray"},"esc"),B.createElement(K,{dimColor:!0},"to interrupt)")))):i?B.createElement(V,{columnGap:1},B.createElement(K,{dimColor:!0},`(${formatToken(Math.round(r))})`)):B.createElement(B.Fragment,null))},"Status");vn(),yn();var Wi=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,a]=z(!1),[i,c]=z(0),l=G(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(a(!0),n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}},[s,t]);return B.createElement(V,{flexDirection:"column"},r?B.createElement(V,null,B.createElement(CMDIcon,null),B.createElement(K,{color:"white"},"Generating agent from description...")):B.createElement(TextInput,{key:i,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:l,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"red"},`${ke.warning} ${o}`)))},"RecommendedFlow");At();var Hi=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=z(!1),[a,i]=z(0),c=q(()=>[...Fa.map(e=>e.name),...La.map(e=>e.name)],[]),l=q(()=>[{name:"All tools",tools:c},{name:"Read-only tools",tools:c.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:c.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:c.filter(e=>"shell_command"===e)},{name:"Search tools",tools:c.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:c.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[c]),d=q(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),c.forEach(t=>{e.push({type:"tool",value:t})})):(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,l,e,c]),u=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=l.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${o?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${ja[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),m=u.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return Z((e,c)=>{if(c.upArrow)i(e=>{const t=e-1;return t<0?m.length-1:t});else if(c.downArrow)i(e=>{const t=e+1;return t>=m.length?0:t});else if(c.return||" "===e){const e=m[a];if(e){const a=d[e.value];if(!a)return;"continue"===a.type?r():"toggle"===a.type?(s(!o),i(0)):"category"===a.type?n(a.value):"tool"===a.type&&t(a.value)}}}),B.createElement(V,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===a;if("divider"===e.type)return B.createElement(V,{key:`divider-${t}`},B.createElement(K,{color:"gray"}," ",e.label));if("spacer"===e.type)return B.createElement(V,{key:`spacer-${t}`,height:1});if("label"===e.type)return B.createElement(V,{key:`label-${t}`},B.createElement(K,{color:"gray"}," ",e.label));const o="continue"===e.type;return B.createElement(V,{key:`item-${t}`},B.createElement(K,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),B.createElement(V,{marginTop:1},e.size===c.length&&B.createElement(K,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&B.createElement(K,{color:"gray"},e.size," tools selected"),0===e.size&&B.createElement(K,{color:"gray"},"No tools selected")))},"ToolsSelector");$n(),qt(),Gt(),An();var Gi=__name(({onComplete:e})=>{const[t,n]=z("location"),[r,o]=z(!1),[s,a]=z(null),[i,c]=z("agentType"),l=q(()=>[...Fa.map(e=>e.name),...La.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=z(d()),g=__name(t=>{n("location"),c("agentType"),m(d()),e(t)},"resetToDefaults"),p=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===u.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===i)return"Agent type (identifier)";if("sysPrompt"===i)return"System prompt";if("ccToolDefinition"===i)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),h=__name(e=>{m({...u,location:e}),n("method")},"handleLocationSelect"),f=__name(e=>{m({...u,method:e}),n("configuration")},"handleMethodSelect"),y=__name(async()=>{try{a(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===wt.ANTHROPIC&&(r=await Bt.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const s={[pt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(s[pt.OAUTH_TOKEN]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new Co({baseUrl:i}),l=await c.post({headers:s,endpoint:ht.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});m({...u,agentType:Le(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof fo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?a(_t):a("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),w=__name(()=>{m({...u,agentType:Le(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),S=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),v=__name(e=>{const t=new Set(u.selectedTools);t.has(e)?t.delete(e):t.add(e),m({...u,selectedTools:t})},"handleToggleTool"),b=__name(e=>{const t=[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(u.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),m({...u,selectedTools:n})},"handleToggleCategory");return B.createElement(V,{flexDirection:"column",gap:1},B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"white",bold:!0},"Create new agent"),B.createElement(K,{color:"gray"},p())),B.createElement(V,null,"location"===t&&B.createElement(Ni,{onSelect:h}),"method"===t&&B.createElement(Fi,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&B.createElement(Wi,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:y}),"configuration"===t&&"manual"===u.method&&B.createElement(V,{flexDirection:"column",gap:1},B.createElement(Oi,{step:i,agentType:u.agentType,sysPrompt:u.sysPrompt,ccToolDefinition:u.ccToolDefinition,onAgentTypeChange:e=>m({...u,agentType:e}),onSysPromptChange:e=>m({...u,sysPrompt:e}),onCCToolDefinitionChange:e=>m({...u,ccToolDefinition:e}),onAgentTypeSubmit:w,onSysPromptSubmit:E,onCCToolDefinitionSubmit:S})),"tools"===t&&B.createElement(Hi,{selectedTools:u.selectedTools,onToggleTool:v,onToggleCategory:b,onComplete:k}),"summary"===t&&B.createElement(Ri,{config:u,onSaveComplete:g})))},"AgentNew"),qi=__name(({onCancel:e})=>{const[t,n]=z(null),[r,o]=z(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return Z((t,n)=>{n.escape&&e()}),B.createElement(V,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"single",flexDirection:"column"},null===t&&B.createElement(Mi,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&B.createElement(Gi,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");At(),At();var Vi=__name(({messages:e})=>0===e.length?null:B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(V,{marginBottom:0},B.createElement(K,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>B.createElement(V,{key:t},B.createElement(K,{dimColor:!0},ke.pointerSmall," "),B.createElement(K,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages");At(),pn(),Rt(),yn(),sn(),At();var Ki=n(f(),"commandcode-images"),Ji={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{E(Ki)||b(Ki,{recursive:!0});const r=Ji[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(Ki,o),a=Buffer.from(e.data,"base64");return C(s,a),s}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:o,setDetectedContent:s,incrementInputKey:a}=e,i=G((e,t)=>{o(t=>[...t,e]),r(t),a()},[o,r,a]),c=W(!1),l=W(""),d=W(null),u=W(""),m=G(async(e,t)=>{let o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const c=await detectDroppedImageFile(o);if(c)return void i(c,t);const l=await detectClipboardImage();if(l)return void i(l,t);let d=o;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}]`;s(e=>[...e,d]),r(t+e)}else r(t+d);a()}},[i,n.length,s,r,a]),g=G(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(c.current){const e=l.current,t=u.current;l.current="",u.current="",c.current=!1,d.current=null,e&&await m(e,t)}},500)},[m]);return{handlePaste:G(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return c.current&&(c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)),await m(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!c.current)return c.current=!0,u.current=n.textBeforePaste??t,l.current=n.pastedContent??n.cleanedContent,g(),!0;if(c.current&&!n.isPasteEnd)return void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current)),g(),!0;if(c.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current));const e=l.current,t=u.current;return l.current="",u.current="",c.current=!1,await m(e,t),!0}if(n.isPasteEnd&&!n.isPasteStart&&!c.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return i(e,t),!0}return!1},[t,m,g,i]),resetPasteState:G(()=>{c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:G(()=>c.current,[])}}__name(saveTempImage,"saveTempImage"),$n(),At(),vn(),yn(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),At(),At();var Yi=["code --wait","cursor --wait","nano"],Qi=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return Qi.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 Yi)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var Zi=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 Zi;t=ensureWaitFlag(t);const r=n(f(),`commandcode-${Date.now()}.md`);return await O(r,e),new Promise((e,n)=>{const o=t.split(" ").filter(e=>e.length>0),s=o[0],a=o.slice(1),i=x(s,[...a,r],{stdio:"inherit"});i.on("close",async()=>{try{const t=await F(r,"utf-8");await L(r),e(t.trimEnd())}catch(e){n(e)}}),i.on("error",async e=>{try{await L(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[o,s]=z(!1),[a,i]=z(null),c=G(async()=>{if(!o){s(!0),i(null);try{const n=e.replace(/\n+$/,""),o=await openInEditor2(n);t(o),r?.()}catch(e){i(e instanceof Zi?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{s(!1)}}},[e,t,r,o]),l=G(()=>{i(null)},[]);return{isEditorOpen:o,editorError:a,handleOpenInEditor:c,clearEditorError:l}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),At(),At(),At(),At(),Rt(),Cn(),Rn(),jn(),At(),Rt();var Xi=t.join(h.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(Xi);w.existsSync(e)||w.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!w.existsSync(Xi))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=w.readFileSync(Xi,"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(),w.writeFileSync(Xi,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"),Rn();var ec=ye($),tc=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 tc.version}function isAlphaVersion(e){return e.includes("alpha")}function filterVersions(e){return{stable:e.filter(e=>!e.includes("alpha")),alpha:e.filter(e=>e.includes("alpha"))}}function getLatestVersion(e){return 0===e.length?null:e.sort(Ge.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Ge.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Ge.gt(t,e))return{latestVersion:t,updateAvailable:!0}}return{latestVersion:e,updateAvailable:!1}}async function checkForUpdateAvailable(){const e=fetchVersions();if(!e)return null;const t=getCurrentVersion(),{stable:n,alpha:r}=filterVersions(e),{latestVersion:o,updateAvailable:s}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:o,updateAvailable:s}}async function executeUpdate(e){try{return await ec(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;if(!Ge.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=Me(`Updating ${e} → ${t.targetVersion}`).start(),r=await executeUpdate(t.targetVersion);if(clearPendingUpdate(),!r)return n.fail("Update failed"),void console.log("Run `cmd update` to try again.");n.succeed(`Updated to v${t.targetVersion}`)}async function performAutoUpdate(e){const{silent:t,updateInfo:n,onStart:r}=e||{};if(isLocalDevelopmentBuild())return{success:!1};const o=n||await checkForUpdateAvailable();return o?.updateAvailable?(r?.(o.latestVersion),await executeUpdate(o.latestVersion)?{success:!0,updateInfo:o}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:o})):{success:!1}}function getCurrentGitBranch(){try{return 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 nc=new Set(["OPEN","MERGED","CLOSED"]),rc=null;function getCachedPRInfo(e){if(rc&&rc.branch===e){if(!(Date.now()-rc.timestamp>3e5))return rc.result;rc=null}}function setPRCache(e,t){rc={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((o,s)=>{R(e,[...t],{encoding:n,timeout:r},(e,t)=>{e?s(e):o(t.trim())})})}function parsePRResponse(e){try{const t=JSON.parse(e);return t.number&&t.url&&t.state&&nc.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 oc=__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"),sc=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=z(null),o=W(!1);return H(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,oc().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");At(),Rt(),In();var ac=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear (reset, new)",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.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))(ac||{}),ic=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{command:"/clear (reset, new)",description:"Clear the conversation history"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/agents",description:"Manage agent configurations"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/model",description:"Switch between Command Code models"},{command:"/compact",description:"Compact the conversation history"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/add-dir",description:"Add directory to workspace context"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/ide",description:"Install extension to fetch IDE context"},{command:"/help",description:"Show available shortcuts"},{command:"/exit",description:"Exit the REPL"}];function truncateText(e){const{text:t,maxWidth:n}=e;return t.length<=n?t:n<=3?t.substring(0,n):t.substring(0,n-3)+"..."}__name(truncateText,"truncateText");var cc=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=z(0),[s,a]=z(0),{stdout:i}=Q(),c=i?.columns??80,l=Math.max(20,c-22-2-1-2),d=q(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...ic.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!n)return e;const t=n.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let o=0;return n.startsWith("/"+t)?o+=100:n.includes(t)&&(o+=50),r.includes(t)&&(o+=25),{...e,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]),u=q(()=>{const e=s,t=Math.min(e+8,d.length);return d.slice(e,t)},[d,s]);return H(()=>{o(0),a(0)},[n]),Z((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>{const t=Math.max(0,e-1);return t<s&&a(t),t});else if(i.downArrow)o(e=>{const t=Math.min(d.length-1,e+1);return t>=s+8&&a(Math.max(0,t-8+1)),t});else if(i.return){const t=d[r];return void(t&&e(t.command))}}),0===d.length?B.createElement(V,{flexDirection:"column",paddingLeft:2},B.createElement(K,{color:"dim"},"No commands found")):(d.length,B.createElement(V,{flexDirection:"column",paddingLeft:1},B.createElement(V,{columnGap:2},B.createElement(V,{flexDirection:"column",width:22},u.map((e,t)=>{const n=s+t;return B.createElement(K,{key:n,color:r===n?"white":"dim",wrap:"truncate"},e.command)})),B.createElement(V,{flexDirection:"column"},u.map((e,t)=>{const n=s+t;return B.createElement(K,{key:n,color:r===n?"white":"dim",wrap:"truncate"},truncateText({text:e.description,maxWidth:l}))})))))},"CommandMenu");function loadGitignore(e){const t=qe(),r=n(e,".gitignore");if(E(r))try{const e=S(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}At(),__name(loadGitignore,"loadGitignore");var lc=__name(({onSelectFile:e,onClose:t,searchQuery:s=""})=>{const[i,c]=z(process.cwd()),[l,d]=z([]),[u,m]=z(0),[g,p]=z(0),h=s.trim()?15:10,f=G((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const s=n(t,e);try{const e=P(s),a=[];return e.forEach(e=>{const i=n(s,e);try{const e=T(i),n=o(t,i);if(r.ignores(n))return;a.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}),a.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),a.slice(0,50)}catch{}}if(e.includes("/")){const s=e.split("/"),a=s.pop()||"",i=n(t,s.join("/"));try{const e=P(i),s=[],c=a.toLowerCase();return e.forEach(e=>{const l=e.toLowerCase();if(!a||l.includes(c)){const a=n(i,e);try{const e=T(a),n=o(t,a);if(r.ignores(n))return;s.push({name:n,path:a,isDirectory:e.isDirectory()})}catch{}}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),s.slice(0,50)}catch{}}const s=[],a=e.toLowerCase(),i=__name((e,c=0)=>{if(!(c>8))try{P(e).forEach(l=>{const d=n(e,l);try{const e=T(d),n=o(t,d);if(r.ignores(n))return;const u=n.toLowerCase();(l.toLowerCase().includes(a)||u.includes(a))&&s.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==l&&i(d,c+1)}catch(e){}})}catch(e){}},"searchRecursively");return i(t),s.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),o=n===a,s=r===a;if(o&&!s)return-1;if(!o&&s)return 1;const i=n.split("/").pop()||"",c=r.split("/").pop()||"",l=i.includes(a),d=c.includes(a);if(l&&!d)return-1;if(!l&&d)return 1;const u=e.name.split("/").length,m=t.name.split("/").length;return u!==m?u-m:e.name.localeCompare(t.name)}),s.slice(0,50)},[]),y=G(e=>{try{const t=P(e),s=[],a=process.cwd(),i=loadGitignore(a);"/"!==e&&s.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=T(r),n=o(a,r);if(i.ignores(n))return;s.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(s),m(0),p(0)}catch{}},[]);H(()=>{if(s.trim()){const e=f(s);d(e),m(0),p(0)}else y(i)},[i,y,s,f]),Z((n,r)=>{if(r.escape)t();else if(r.upArrow)m(e=>{const t=Math.max(0,e-1);return t<g&&p(t),t});else if(r.downArrow)m(e=>{const t=Math.min(l.length-1,e+1);return t>=g+h&&p(t-h+1),t});else{if(r.rightArrow){const e=l[u];if(!e)return;return void(e.isDirectory&&!s.trim()&&c(a(e.path)))}if(r.return){const t=l[u];if(!t)return;return void e(t.path)}}});const w=l.slice(g,g+h);return B.createElement(V,{flexDirection:"column",paddingLeft:1},B.createElement(V,{marginBottom:1,flexDirection:"column"},B.createElement(K,{color:"dim"},s.trim()?`Searching for: "${s}"`:`Files: ${i}`),B.createElement(K,{color:"dim"},s.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===w.length?B.createElement(K,{color:"dim"},s.trim()?`No files found matching "${s}"`:"No files found in this directory"):w.map((e,t)=>{const n=g+t,r=e.name,o=n===u;return B.createElement(K,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList");At(),Rt(),In(),At();var dc=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20)return null;const r=__name(e=>e>=90?"red":e>=70?"yellow":"dim","getColor"),o=`context: ${n}% left before auto-compact`;return B.createElement(V,{paddingRight:1},B.createElement(K,{color:r(t)},o))},"ContextUsage");At();var uc=__name(()=>{const[e,t]=z("continuous learning"),n=W([]),r=W(0),o=W(null),s=W(!1);H(()=>{const e=__name(e=>"analyzing"===e.type?(s.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):s.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(s.current=!1,void(n.current.length>0?(r.current=0,a()):t("continuous learning"))):void 0,"handleNewEvent"),a=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const s="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,a()},s)},"cycleThroughNextEvent");return za.on("new-event",e),()=>{za.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const a=9+e.length+9>100;let i=e;if(a){const t=100;e.length>t&&(i=e.substring(0,t-3)+"...")}else{const t=82;e.length>t&&(i=e.substring(0,t-3)+"...")}return B.createElement(V,null,!a&&B.createElement(K,{color:"green"},"● taste: "),B.createElement(K,null,i),!a&&B.createElement(K,{dimColor:!0}," (ctrl+t)"))},"LearningFeedMini");At();var mc=__name(({mode:e,pendingExitKey:t})=>{if(t)return B.createElement(K,{dimColor:!0},"Press Ctrl+C again to exit");switch(e){case"auto-accept":return B.createElement(V,{flexDirection:"row"},B.createElement(K,{color:"#E4CCFF"},"» accept edits on "),B.createElement(K,{dimColor:!0},"(shift+tab)"));case"plan":return B.createElement(V,{flexDirection:"row"},B.createElement(K,{color:"#FFB86C"},"plan mode "),B.createElement(K,{dimColor:!0},"(shift+tab)"));default:return B.createElement(K,{color:"dim"},"? shortcuts")}},"ModeIndicator");At(),At();var gc=__name(({url:e,text:t,dimColor:n=!1,color:r})=>{const o=`]8;;${e}${t}]8;;`;return B.createElement(K,{dimColor:n,color:r},o)},"TerminalLink"),pc=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?"#FBBF24":"#A78BFA";return B.createElement(B.Fragment,null,t&&B.createElement(K,{dimColor:!0}," · "),B.createElement(K,{color:n},"PR "),B.createElement(gc,{url:e.url,text:`#${e.number}`,dimColor:!0}))},"PRLinkBadge"),hc=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?B.createElement(B.Fragment,null,t&&B.createElement(K,{dimColor:!0}," · "),B.createElement(K,{color:"connected"===e.type?"green":"yellow"},e.message)):null,"ConnectionIndicatorBadge"),fc=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:a,connectionIndicator:i,pendingExitKey:c,updateStatus:l,updateFailedInfo:d,currentProvider:u,showProviderInfo:m,isBashMode:g,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y})=>{const w=e>=60;return B.createElement(B.Fragment,null,B.createElement(V,{flexDirection:"column",paddingLeft:1},"auto-accept"!==r&&"plan"!==r||c?B.createElement(V,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(V,{flexDirection:"row",columnGap:0},B.createElement(mc,{mode:r,pendingExitKey:c}),!c&&B.createElement(pc,{prInfo:o}),!c&&B.createElement(hc,{indicator:i})),w&&B.createElement(V,{flexDirection:"column",alignItems:"flex-end"},s&&B.createElement(uc,null),a&&B.createElement(dc,{usage:a}))):B.createElement(B.Fragment,null,B.createElement(V,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(mc,{mode:r}),w&&s&&B.createElement(uc,null)),B.createElement(V,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(V,{flexDirection:"row",columnGap:0},B.createElement(K,{color:n?"#5FAFAF":void 0,dimColor:!n},t),B.createElement(pc,{prInfo:o}),B.createElement(hc,{indicator:i})),w&&a&&B.createElement(dc,{usage:a}))),(l||d||m&&u)&&B.createElement(V,{flexDirection:"row",columnGap:1},l&&B.createElement(K,null,ke.tick," ","Command Code"," updated:"," ",B.createElement(K,{dimColor:!0},"v",l.updatedFrom),B.createElement(K,{dimColor:!0}," ",ke.arrowRight," "),B.createElement(K,null,"v",l.updatedTo)),!l&&d&&B.createElement(K,{color:"yellow",dimColor:!0},ke.info," Update available:"," ",d.currentVersion," ",ke.arrowRight," ",d.latestVersion),m&&u&&B.createElement(K,{color:"green",dimColor:!0},ke.bullet," Provider:"," ",getProviderDisplayName(u)))),g&&B.createElement(V,{paddingLeft:1},B.createElement(K,{color:"green"},"! for bash mode")),h&&p&&B.createElement(V,{paddingLeft:1},B.createElement(K,{color:"#E4CCFF"},"SHARED: ",p.url," (copied to clipboard)")),f&&B.createElement(V,{paddingLeft:1},B.createElement(K,{color:f.includes("NOT SHARED")?"red":"#E4CCFF"},f)),y&&B.createElement(V,{paddingLeft:1},B.createElement(K,{color:"#E4CCFF"},y)))},"BottomIndicator");At();var yc=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=z([]),[o,s]=z(0),[a,i]=z(!0);H(()=>{c()},[]);const c=__name(async()=>{i(!0);const e=await Pa.listSessions();r(e.slice(0,30)),i(!1)},"loadSessions");if(Z((r,a)=>{a.escape?t():a.upArrow?s(e=>Math.max(0,e-1)):a.downArrow?s(e=>Math.min(n.length-1,e+1)):a.return&&n.length>0&&o<n.length&&e(n[o].id)}),a)return B.createElement(V,{flexDirection:"column",paddingLeft:2},B.createElement(K,{color:"gray"},"Loading sessions..."));if(0===n.length)return B.createElement(V,{flexDirection:"column",paddingLeft:2},B.createElement(K,{color:"gray"},"No previous sessions found"),B.createElement(K,{color:"dim",dimColor:!0},"Press ESC to go back"));const l=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),d=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),u=__name((e,t=50)=>{const n=d(e);return n.length<=t?n:n.substring(0,t-3)+"..."},"truncateMessage"),m=__name(e=>e.title?d(e.title):u(e.firstMessage),"getSessionSummary");return B.createElement(V,{flexDirection:"column",paddingLeft:1,width:"100%"},B.createElement(K,{color:"cyan",bold:!0},"Resume Session"),B.createElement(K,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),B.createElement(V,{marginTop:1}),B.createElement(V,{columnGap:2,marginBottom:1},B.createElement(V,{width:5},B.createElement(K,{color:"gray"}," ")),B.createElement(V,{width:13},B.createElement(K,{color:"gray"},"Modified")),B.createElement(V,{width:20},B.createElement(K,{color:"gray"},"Git Branch")),B.createElement(V,{width:11},B.createElement(K,{color:"gray"},"# Messages")),B.createElement(V,null,B.createElement(K,{color:"gray"},"Summary"))),B.createElement(V,{columnGap:2},B.createElement(V,{flexDirection:"column",width:5},n.map((e,t)=>B.createElement(K,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${ke.pointer} ${t+1}.`:` ${t+1}.`))),B.createElement(V,{flexDirection:"column",width:13},n.map((e,t)=>B.createElement(K,{key:`mod-${e.id}`,color:o===t?"white":"gray"},l(e.lastModified)))),B.createElement(V,{flexDirection:"column",width:20},n.map((e,t)=>B.createElement(K,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),B.createElement(V,{flexDirection:"column",width:11},n.map((e,t)=>B.createElement(K,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),B.createElement(V,{flexDirection:"column"},n.map((e,t)=>B.createElement(K,{key:`summary-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},m(e))))))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete · Esc":"Delete · Esc":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],o=0;for(let s=0;s<e;s++){const e=`[Image #${s+1}]`.length,a=e+(r.length>0?1:0);r.length>0&&o+a>t?(n.push(r),r=[s],o=e):(r.push(s),o+=a)}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 createOSC8Link(e,t,n=!0){return`${n?"[33m":""}]8;;${e}${t||e}]8;;${n?"[0m":""}`}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const o=`[Image #${e+1}]`,s=n?createOSC8Link(`file://${n}`,o,!1):o;return B.createElement(K,null,r?" ":"",t?B.createElement(K,{inverse:!0},o):s)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:o}){if(0===e.length)return null;const s=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:o}),a=Math.max(1,r-(s.length+2)),i=buildImageRows({imageCount:e.length,rowWidth:a});return B.createElement(V,{flexDirection:"column",width:"100%",alignItems:"flex-end"},i.map((e,r)=>B.createElement(V,{key:r,flexDirection:"row"},B.createElement(V,{flexShrink:0,marginRight:1},0===r&&B.createElement(K,{color:"dim"},s)),B.createElement(V,{flexDirection:"row"},e.map((e,r)=>B.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}At(),At(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),At(),__name(createOSC8Link,"createOSC8Link"),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),At(),Pr();var wc=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=z(null),[s,a]=z(!1),i=W(!1),c=W(null),[l,d]=z(!1),[u,m]=z("connected"),g=W(null),p=W(null),h=G((e,t)=>{p.current&&(clearTimeout(p.current),p.current=null),m(e),d(!0),void 0!==t&&(p.current=setTimeout(()=>{d(!1)},t))},[]),f=G(()=>{p.current&&(clearTimeout(p.current),p.current=null)},[]),y=G(async(e=!1)=>{if(!i.current){i.current=!0;try{let t=c.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new Sr,c.current=t;const r=e?200:500;n=await t.connect(r)}const r=g.current;if(null===r?n?h("connected",3e3):h("disconnected",5e3):r!==n&&(n?h("connected",2e3):h("disconnected",5e3)),g.current=n,a(n),n){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),c.current=null),o(r)}else o(null)}catch{!0===g.current&&h("disconnected",5e3),g.current=!1,a(!1),o(null),c.current?.disconnect(),c.current=null}finally{i.current=!1}}},[h]);return H(()=>{if(!t||n)return;y(!0);const e=setInterval(()=>y(!1),500);return()=>{clearInterval(e),f(),c.current?.disconnect(),c.current=null}},[t,n,y,f]),{context:r,connected:s,refresh:y,connectionIndicator:{visible:l,message:"connected"===u?"IDE ✓":"IDE disconnected",type:u}}},"useVSCodeContext");At();var Ec=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:o}=e.activeFile;t.push(`File: ${n} (${r}, line ${o.line})`)}if(e.selection){const{text:n,startLine:r,endLine:o}=e.selection,s=e.activeFile?.language||"";t.push(`Selected lines ${r}-${o}:`),t.push(`\`\`\`${s}`),t.push(n),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt"),Sc=["\n","\r","[13;2u","[27;2;13~","[27;2;13~","[13;2u"],kc=["","[118;5u","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isNewlineShortcutKey(e){const{inputChar:t,key:n,isPasting:r}=e;return!r&&(!(!n.return||!n.shift)||!(!n.ctrl||!n.return)||!(!n.ctrl||"j"!==t)||!("\r"!==t||n.return||n.ctrl||n.shift||n.meta)||Sc.includes(t))}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isNewlineShortcutKey,"isNewlineShortcutKey"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var vc=__name(()=>B.createElement(V,{flexDirection:"column",paddingLeft:1},B.createElement(K,{color:"dim",bold:!0},"Available Shortcuts:"),B.createElement(V,{columnGap:4},B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"dim"},"! for bash mode"),B.createElement(K,{color:"dim"},"/ for commands"),B.createElement(K,{color:"dim"},"@ for file paths"),B.createElement(K,{color:"dim"},"shift + tab to toggle auto-accept")),B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"dim"},"double tap esc to clear input"),B.createElement(K,{color:"dim"},"ctrl + j / shift + ⏎ for newline"),B.createElement(K,{color:"dim"},"ctrl + g to open in editor"),B.createElement(K,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),bc=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:s="Enter your input…",showFileList:a,setShowFileList:i,fileSearchQuery:c,setFileSearchQuery:l,onCommand:d,contextUsage:u,tasteLearning:m=!1,tasteUsage:g=!1,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,updateStatus:w,updateFailedInfo:E,currentProvider:S,showProviderInfo:k,permissionMode:v="standard",onToggleAutoAccept:b,hintMessage:C,historyManager:P,pendingExitKey:T=null,onOverlayVisibilityChange:A,onDoubleEscapeEmpty:x,onAltP:I,isProcessing:$=!1,ideContextEnabled:R=!0})=>{const[D,M]=z(0),[N,O]=z(!1),[F,L]=z(!1),[_,U]=z(!1),[j,J]=z(!1),[Y,X]=z(""),[ee,te]=z(!1),ne=W(0),re=W(0),[oe,se]=z([]),[ae,ie]=z([]),[ce,le]=z(-1),[de,ue]=z(""),me=W(!1),ge=W(!1),[pe,he]=z(-1),[fe,ye]=z(""),we=W(0),{isEditorOpen:Ee,editorError:Se,handleOpenInEditor:ve,clearEditorError:be}=useExternalEditor({input:e,setInput:n,setInputKey:M,onEditorClose:__name(()=>{me.current=!1},"onEditorClose")}),{handlePaste:Ce,resetPasteState:Pe,isPasting:Te}=useBracketedPaste({input:e,detectedContent:oe,setInput:n,setDetectedImages:ie,setDetectedContent:se,incrementInputKey:__name(()=>M(e=>e+1),"incrementInputKey")}),{context:Ae,connected:xe,refresh:Ie,connectionIndicator:$e}=wc({enabled:R,paused:$}),{stdout:Re}=Q(),De=Re?.columns??80,{pr:Me}=sc();H(()=>{const e=a||j||ee;A?.(e)},[a,j,ee,A]);const Ne=G(()=>{ie([]),le(-1)},[]),Oe=G(()=>{n(""),L(!1),J(!1),X(""),te(!1),se([]),Ne(),ue(""),Pe(),he(-1),ye(""),M(e=>e+1)},[n,Pe,Ne]),Fe=G(()=>{me.current=!0,n(e+"\n"),M(e=>e+1),setTimeout(()=>{me.current=!1},0)},[e,n]);Z(async(t,r)=>{if(-1!==ce&&r.leftArrow)return void le(prevImageIndex({currentIndex:ce,imageCount:ae.length}));if(-1!==ce&&r.rightArrow)return void le(nextImageIndex({currentIndex:ce,imageCount:ae.length}));if(r.upArrow){if(a||j||ee)return;const t=e.indexOf("\n"),r=-1===t||we.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ae.length,selectedImageIndex:ce,historyIndex:pe}))return void le(ae.length-1);if(-1!==ce&&le(-1),0!==e.length&&-1===pe&&!r)return;const o=P?.count()??0;if(0===o)return;-1===pe&&ye(e);const s=Math.min(pe+1,o-1);return void(s!==pe&&(he(s),n(P?.getAt(s)||""),M(e=>e+1)))}if(r.downArrow){if(a||j||ee)return;if(-1===pe)return;const t=e.lastIndexOf("\n");if(!(-1===t||we.current>t))return;const r=pe-1;return he(r),n(-1===r?fe:P?.getAt(r)||""),void M(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Ne();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return me.current=!0,void ve();if(getIsExpandToolShortcut(r,t))return me.current=!0,n(e),M(e=>e+1),void setTimeout(()=>{me.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Te()}))return ge.current=!0,Fe(),void setTimeout(()=>{ge.current=!1},0);if(r.meta&&r.backspace)return void Oe();if(r.meta&&"w"===t)return me.current=!0,void Oe();const o=r.ctrl&&"v"===t||kc.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();return r&&(ie(e=>[...e,r]),n(t),M(e=>e+1)),void(me.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!==ce&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ae,index:ce});return ie([...e]),void le(t)}if(r.escape){if(-1!==ce)return void le(-1);if(j)return;if(ee)return te(!1),n(de),void M(e=>e+1);const t=Date.now();return t-ne.current<500?(e.length>0?Oe():x?.(),ne.current=0,re.current=0):(ne.current=t,N||F||(re.current=t)),O(!1),void L(!1)}N&&(r.backspace||r.delete)&&0===e.length&&O(!1)}});const Le=G(async t=>{if(Ee)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void I?.();if(await Ce(t))return;if(me.current)return void(me.current=!1);-1!==pe&&he(-1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!N)return O(!0),n(""),void M(e=>e+1);if("!"===s&&!F)return O(!1),L(!0),n(""),void M(e=>e+1)}if("/"!==s||j||"/"!==t||(J(!0),X("")),j&&!t.startsWith("/")&&(J(!1),X("")),j&&t.startsWith("/")){const e=t.substring(1);X(e)}"@"!==s||a||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(i(!0),l(""));const c=t.lastIndexOf("@");if(t.length<e.length&&-1!==c&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(c+1),n=!e.includes(" "),r=c>0?t[c-1]:"";n&&isPrecededByWhitespace(r)&&(i(!0),l(e))}if(a)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),l("");else{const n=t.substring(e+1);l(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);l(e),i(!1)}else l(n)}}N&&(t!==e||t.length<e.length)&&O(!1),Se&&be(),0===t.length&&(L(!1),J(!1),X(""),te(!1),Ne(),se([]),l(""),ue(""),Pe()),n(t)},[N,e,n,a,i,j,F,ae,pe,Ce,Pe,I,Se,be,Ee,Ne]),_e=G(async()=>{if(Ie(),re.current=0,N)return void O(!1);let n=e.trim();if(!F&&n.startsWith("/"))return P?.add(n),d&&d(n),L(!1),J(!1),X(""),Ne(),se([]),he(-1),void ye("");n.length>0&&P?.add(n),he(-1),ye("");let r=[];const o=ae.length>0,s=oe.length>0;if(!F&&o&&(r=[...ae]),!F&&s){let e=n;oe.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:F?"bash":"user",images:r,ideContext:Ae?Ec(Ae):void 0}),L(!1),J(!1),X(""),Ne(),se([])},[t,d,N,e,F,ae,oe,P,Ie,Ne]),Ue=G(t=>{const r=o(process.cwd(),t);let s;if(a&&""!==c){const t=e.lastIndexOf("@");s=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else s=`${e}${r} `;n(s),i(!1),l(""),M(e=>e+1)},[n,i,e,a,c,l]),je=G(()=>{i(!1),l("")},[i,l]),Be=G(t=>{if("/resume"===t)P?.add(t),he(-1),ye(""),ue(e),J(!1),X(""),te(!0),n(""),M(e=>e+1);else{const e=Object.values(ac).includes(t);J(!1),X(""),e?(P?.add(t),he(-1),ye(""),n(""),M(e=>e+1),d&&d(t)):(n(t+" "),M(e=>e+1))}},[d,n,e,P]),ze=G(()=>{J(!1),X(""),n(""),he(-1),ye(""),M(e=>e+1)},[n]),We=G(e=>{te(!1),n(""),ue(""),he(-1),ye(""),M(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),He=G(()=>{te(!1),n(de),he(-1),ye(""),M(e=>e+1)},[de,n]),Ge=G(e=>{we.current=e},[]),qe=q(()=>{const t=Me&&("OPEN"===Me.state||"MERGED"===Me.state);return"auto-accept"===v||"plan"===v||xe||t?!N&&!ee:!N&&0===e.length&&!F&&!ee},[N,e,F,ee,v,xe,Me]),Ve=W(new Map),Ke=q(()=>ae.map((e,t)=>{if(Ve.current.has(e))return Ve.current.get(e)??null;const n=saveTempImage(e,t+1);return Ve.current.set(e,n),n}),[ae]),Je=__name(()=>N||a||j||ee||_?0:qe||T||F?3:4,"getBottomMargin"),Ye=__name(()=>!(!xe||!Ae?.selection&&!Ae?.activeFile?.relativePath),"hasIDEContext"),Qe=__name(()=>{const e=xe?Ae?.selection:null;if(e)return`${e.lineCount} lines selected`;const t=xe?Ae?.activeFile:null;if(t?.relativePath){const e=t.relativePath.split("/").pop()||"",n=De<80?15:De<120?25:40;return`In ${e.length>n?e.slice(0,n-1)+"…":e}`}return"? shortcuts"},"getIndicatorText");return B.createElement(V,{width:"100%",flexDirection:"column",marginBottom:Je()},!ee&&B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(ImageRowsDisplay,{detectedImages:ae,selectedImageIndex:ce,imageTempPaths:Ke,termWidth:De,inHistory:-1!==pe}),B.createElement(K,{color:F?"green":"gray"},ke.line.repeat(De)),B.createElement(TextInput,{key:D,value:e,placeholder:Ee?"Save and close the editor to continue...":s,onChange:Le,onSubmit:()=>{if(!ge.current)return Date.now()-re.current<100?(re.current=0,void Fe()):void(a||j||ee||Ee||_e());ge.current=!1},showCursor:!Ee&&r&&-1===ce,onCursorChange:Ge,prefix:`${F?"!":ke.pointer} `,prefixColor:F?"green":"white"}),B.createElement(K,{color:F?"green":"gray"},ke.line.repeat(De))),N&&B.createElement(vc,null),_&&B.createElement(V,{paddingTop:1},B.createElement(K,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),a&&B.createElement(lc,{onSelectFile:Ue,onClose:je,searchQuery:c}),j&&B.createElement(cc,{onSelectCommand:Be,onClose:ze,searchQuery:Y}),ee&&B.createElement(yc,{onSelectSession:We,onClose:He}),(qe||T)&&B.createElement(fc,{termWidth:De,indicatorText:Qe(),isIDEIndicator:Ye(),permissionMode:v,prInfo:Me,tasteLearning:m,contextUsage:u,connectionIndicator:$e,pendingExitKey:T,updateStatus:w,updateFailedInfo:E,currentProvider:S,showProviderInfo:k,isBashMode:F,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y}),Se&&B.createElement(V,{paddingLeft:1,flexDirection:"column"},B.createElement(K,{color:"yellow"},Se)))},"InputBox"),Cc=B.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:a,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:S,updateFailedInfo:k,currentProvider:v,showProviderInfo:b,permissionMode:C,onToggleAutoAccept:P,hintMessage:T,historyManager:A,pendingExitKey:x,onResetPendingExitKey:I,onDoubleEscapeEmpty:$,retryAttempt:R,onAltP:D})=>{const[M,N]=z(0),O=W(o);return H(()=>{x&&o!==O.current&&o.length>0&&I?.(),O.current=o},[o,x,I]),H(()=>{if(!t)return void N(0);const e=setInterval(()=>{N(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),B.createElement(V,{flexDirection:"column"},B.createElement(Vi,{messages:e}),B.createElement(V,{flexDirection:"row",justifyContent:"space-between"},B.createElement(V,{flexDirection:"column"},(t||n.isExecuting)&&null===R&&B.createElement(zi,{tokens:m,timeElapsed:M,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),T&&B.createElement(V,{marginLeft:1},B.createElement(K,{dimColor:!0}," ","⎿"," Tip: ",T)))),B.createElement(bc,{input:o,setInput:s,onSubmit:a,placeholder:"Ask your question...",showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:S,updateFailedInfo:k,currentProvider:v,showProviderInfo:b,permissionMode:C,onToggleAutoAccept:P,hintMessage:T,historyManager:A,pendingExitKey:!x||t||n.isExecuting?null:x,onDoubleEscapeEmpty:$,onAltP:D,isProcessing:t}))});At();var Pc=__name(({onClose:e})=>{const[t,n]=z(za.getEvents());Z((t,n)=>{n.ctrl&&"t"===t&&(ri(),e())},{isActive:!0}),H(()=>{const e=__name(()=>{n(za.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return za.on("new-event",e),za.on("cleared",t),()=>{za.off("new-event",e),za.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`confidence: ${parseFloat(e).toString()}%`}const a={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:a,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),s=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),a=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails");return B.createElement(V,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(Ve,{name:"vice"},B.createElement(K,null,oo()))),B.createElement(V,{marginBottom:1,width:"100%",justifyContent:"space-between"},B.createElement(V,null,B.createElement(K,{bold:!0},"Learning Feed"),B.createElement(K,{dimColor:!0}," - Real-time taste learning activity")),B.createElement(K,{dimColor:!0},"Press ctrl+t to close")),B.createElement(V,{flexDirection:"column"},0===t.length?B.createElement(V,null,B.createElement(K,{dimColor:!0},"No learning events yet...")):B.createElement(V,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:i}=o(e.message),c="moved"===t?a(e.details):null,l="upgraded"===t||"downgraded"===t?s(r):null;return B.createElement(V,{key:e.id,marginBottom:1},B.createElement(V,{flexDirection:"column"},B.createElement(V,null,B.createElement(K,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),c?B.createElement(K,{dimColor:!0}," (",c.fullPath,")"):e.details?B.createElement(K,{dimColor:!0}," (",e.details,")"):null),B.createElement(V,{marginLeft:1},B.createElement(K,{dimColor:!0},"⎿"," "),c?B.createElement(B.Fragment,null,B.createElement(K,null,c.category," package ("),B.createElement(K,{dimColor:!0},c.oldPath),B.createElement(K,null," → ",c.newPath),B.createElement(K,null,")")):l?B.createElement(B.Fragment,null,B.createElement(K,null,l.text," ("),B.createElement(K,{dimColor:!0},"confidence: "),B.createElement(K,{dimColor:!0},l.oldPercent,"%"),B.createElement(K,null," → "),B.createElement(K,{color:l.diff>0?"green":"red"},l.newPercent,"%"),B.createElement(K,null,")")):B.createElement(B.Fragment,null,B.createElement(K,null,r),i&&B.createElement(K,{dimColor:!0}," (",i,")")))))}return B.createElement(V,{key:e.id,marginBottom:1},B.createElement(K,{dimColor:!0},ke.pointerSmall," ",e.message))}))))},"LearningFeedFull");At(),Rt(),Gt();var Tc=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(0),[s,a]=z(!0),[i,c]=z(null);H(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),a(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),a(!1)}},"loadMemoryFiles")()},[]);const l=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(Z((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&l(d[r]),"1"===t&&d[0]&&l(d[0]),"2"===t&&d[1]&&l(d[1]))}),s)return B.createElement(V,{paddingLeft:1,paddingTop:1},B.createElement(K,{color:"dim"},"Loading memory files..."));if(i)return B.createElement(V,{paddingLeft:1,paddingTop:1},B.createElement(K,{color:"red"},"❌ ",i));const u=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return B.createElement(V,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},B.createElement(V,null,B.createElement(K,{color:"white",bold:!0},"Select memory to edit:")),B.createElement(V,{columnGap:4,marginTop:1},B.createElement(V,{flexDirection:"column"},u.map((e,t)=>B.createElement(K,{key:t,color:r===t?"white":"dim"},r===t?`${jt} `:" ",e.label))),B.createElement(V,{flexDirection:"column"},u.map((e,t)=>B.createElement(K,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector");At(),At(),At();var Ac=class extends Je{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}list(e,t=!1,n=""){let r=super.list(e,t,n);return r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),r}},xc=new Ke;xc.setOptions({renderer:new Ac({strong:ee.bold,em:ee.italic,del:ee.strikethrough,codespan:ee.yellow,code:ee.yellow,heading:ee.bold.underline,firstHeading:ee.bold.underline,link:ee.cyan,href:ee.cyan.underline,blockquote:ee.gray.italic,table:ee.reset,hr:ee.reset,paragraph:ee.reset,html:ee.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var Ic=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=q(()=>{if(!e)return"";const t=[],n=e.replace(Ic,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=xc.parse(n);return"string"!=typeof r?e:r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").trim()}catch{return e}},[e]);return B.createElement(K,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return B.createElement(V,null,B.createElement(K,null,ke.nodejs),B.createElement(V,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage"),At(),Gt();var $c={"Interrupted by user":"Interrupted by user","Insufficient credits":_t};function UserMessage({content:e}){const t="Interrupted by user"===e,n="Insufficient credits"===e,r=e.startsWith("Error:"),o=t||n||r;let s=o&&$c[e]||e;return B.createElement(V,{paddingX:1,backgroundColor:o?void 0:"#333333"},B.createElement(K,{color:o?"red":"#AAAAAA",bold:!o},ke.pointer),B.createElement(V,{marginLeft:1},B.createElement(K,{color:o?"red":"white",wrap:"wrap"},s)))}__name(UserMessage,"UserMessage"),At(),Wt(),$n();var Rc="#6B7280";function truncateToolOutputForDisplay({output:e,maxLines:t=1}){const n=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),r=n.split("\n");return r.length<=t?n:r.slice(0,t).join("\n")}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,dimDiff:a=!1,maxLines:i}){const c=Ye.diffLines(e,t);let l=0,d=0,u=0,m=0;c.forEach(e=>{e.added?(l+=e.count||1,m+=e.count||1):e.removed&&(d+=e.count||1,m+=e.count||1)});const g=[];c.forEach((e,t)=>{const n=e.value.split("\n").filter(e=>e);e.added||e.removed?n.forEach((n,r)=>{e.removed?(u++,g.push(B.createElement(V,{key:`${t}-${r}-removed`,width:"100%"},B.createElement(K,{color:"gray",dimColor:a},u.toString().padStart(3)," "),B.createElement(V,{backgroundColor:"#712F37"},B.createElement(K,{dimColor:a},"-"),B.createElement(K,{dimColor:a}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(B.createElement(V,{key:`${t}-${r}-added`,width:"100%"},B.createElement(K,{color:"gray",dimColor:a},u.toString().padStart(3)," "),B.createElement(V,{backgroundColor:"#325B30"},B.createElement(K,{dimColor:a},"+"),B.createElement(K,{dimColor:a}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:B.createElement(V,{flexDirection:"column"},o&&!r&&B.createElement(K,{color:"gray"},"Updated"," ",B.createElement(K,{color:"white",bold:!0},n)," ","with ",B.createElement(K,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",B.createElement(K,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&B.createElement(K,{color:"red"},"Rejected update to",B.createElement(K,{color:"red"},` ${n}`)),B.createElement(V,{flexDirection:"column",marginLeft:s},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=Ls(e);return t?B.createElement(V,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?"☒":"☐";let r,o=!1;switch(e.status){case"completed":r="#22C55E",o=!0;break;case"in_progress":r="#E4CCFF";break;default:r="white"}return B.createElement(V,{key:e.id||t,flexDirection:"row"},B.createElement(V,{width:2},B.createElement(K,{color:r},n)),B.createElement(K,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):B.createElement(K,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:a=!1}){const i="Thinking…"===e,c="Todos"===e,l="Edit"===e,d=!0===s?.isTasteFile,u=s?.tasteCategory,m=!0===s?.permissionDenied,g=!i&&!c&&!d,{name:p}=detectTerminal(),h="iTerm2"===p?"shift":"ctrl",f=!0===s?.isAgent,y=t&&f?(()=>{const e=t.split(/[.\n]/)[0];return e?e+(t.includes(".")||t.includes("\n")?".":""):t})():t,w=!i&&y&&!d,E=s?.status,S=s?.tokensUsed||0,k="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0;let v,b;if(r)v="yellow",b="→";else if(o)v="red",b=ke.nodejs;else if(i)v=Rc,b="✻";else if(c&&n){const e=Ls(n),t=e?.every(e=>"completed"===e.status);v=t?"#22C55E":"#D4A017",b=ke.nodejs}else v="#22C55E",b=ke.nodejs;return B.createElement(V,null,i&&B.createElement(K,{color:v},b),B.createElement(V,{flexDirection:"column",marginLeft:i?1:0},B.createElement(V,null,i?B.createElement(B.Fragment,null,B.createElement(K,{color:Rc},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!a&&B.createElement(K,{dimColor:!0},"(",`${h}+o to expand`,")")):d?B.createElement(B.Fragment,null,B.createElement(K,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),B.createElement(K,null," ","Using your taste ",u?"package of ":"packages",u&&B.createElement(K,{bold:!0},u))):B.createElement(K,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),w&&B.createElement(K,null," ",B.createElement(Markdown,null,`(${y})`))),f&&("running"===E||n)&&B.createElement(V,{columnGap:1,marginLeft:g?1:0},g&&B.createElement(K,null,"⎿"," "),"running"===E?B.createElement(K,{color:"gray"},"Running (",formatTime2(k)," | ",formatTokens(S),")"):"interrupted"===E?B.createElement(K,{color:"red",wrap:"wrap"},"Interrupted by user"):"error"===E||o?B.createElement(K,{color:"red",wrap:"wrap"},n," (",formatTime2(k)," | ",formatTokens(S),")"):"Interrupted by user"===n?B.createElement(B.Fragment,null,B.createElement(K,{color:"red",wrap:"wrap"},"Interrupted by user")):B.createElement(B.Fragment,null,B.createElement(K,{wrap:"wrap"},"Done"),B.createElement(K,{color:"gray"}," ","(",formatTime2(k)," | ",formatTokens(S),")"))),n&&!d&&!f&&B.createElement(V,{columnGap:1,marginLeft:g?1:0},g&&B.createElement(K,null,"⎿"," "),c?formatTodosForDisplay(n):i?a?B.createElement(V,{width:"100%",flexDirection:"column"},B.createElement(K,null," "),B.createElement(K,{color:Rc,wrap:"wrap",italic:!0},n)):null:l&&s?.oldValue&&s?.newValue?B.createElement(V,{flexDirection:"column"},(()=>{const e=a?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:m,permissionDenied:m,maxLines:e});return B.createElement(B.Fragment,null,n,r&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"… (",o-10," more lines) (",`${h}+o to expand`,")")))})(),m&&n&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"red",wrap:"wrap"},n))):B.createElement(V,{width:"100%"},B.createElement(K,{color:o?"red":"",wrap:"wrap"},a?n:B.createElement(B.Fragment,null,truncateToolOutputForDisplay({output:n,maxLines:"Question"===e?10:1}),n.includes("\n")&&"Question"!==e&&B.createElement(K,{dimColor:!0}," ","(",`${h}+o to expand`,")"))))),r&&!f&&B.createElement(V,{columnGap:1,marginLeft:1},B.createElement(K,null,"⎿"," "),B.createElement(K,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,s;return n?(o="yellow",s="→"):r?(o="red",s="✗"):(o="green",s="✓"),B.createElement(V,null,B.createElement(K,{color:o},s),B.createElement(V,{flexDirection:"column",marginLeft:1},B.createElement(V,null,B.createElement(K,{color:"gray"},"$ "),B.createElement(K,{color:o,bold:!0},e)),B.createElement(V,{columnGap:1,marginLeft:1},B.createElement(K,null,"⎿"," "),B.createElement(K,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),At(),__name(BashMessage,"BashMessage"),At(),At(),Rt();At(),Rt();var Dc="Coding agent that continuously learns your taste of writing code.",Mc=34,Nc=[{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:"Esc Esc",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],Oc=[{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:"--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"}],Fc=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/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:"/add-dir",description:"Manage additional directory scope"},{key:"/exit",description:"Exit the REPL"}],Lc=[{key:"cmd info",description:"Display system information"},{key:"cmd config",description:"Manage CLI configuration"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],_c=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Uc=[{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"}],jc='Start with a prompt: cmd "fix the login bug"';At(),jn();var Bc="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]:[Bc]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||Bc;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||Bc}catch{return Bc}}function HelpMessage(){const e=getInvokedCommandName(),t=q(()=>Fc.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return B.createElement(V,{flexDirection:"column",paddingY:1},B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(V,null,B.createElement(K,{bold:!0},"Command Code"),B.createElement(K,{color:"gray"}," v","0.11.6")),B.createElement(K,{color:"gray"},Dc)),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Usage"),B.createElement(V,{paddingLeft:2},B.createElement(K,null,e," <command> [options]"))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Options"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Oc.map(t=>B.createElement(V,{key:t.key},B.createElement(K,null,t.key.replace(/^cmd/,e).padEnd(Mc)),B.createElement(K,{color:"gray"},t.description))))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Commands"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Lc.map(t=>B.createElement(V,{key:t.key},B.createElement(K,null,t.key.replace(/^cmd/,e).padEnd(Mc)),B.createElement(K,{color:"gray"},t.description))))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Slash Commands"),B.createElement(V,{flexDirection:"column",paddingLeft:2},t.map(e=>B.createElement(V,{key:e.key},B.createElement(K,null,e.key.padEnd(Mc)),B.createElement(K,{color:"gray"},e.description))))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Keyboard Shortcuts"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Nc.map(e=>B.createElement(V,{key:e.key},B.createElement(K,null,e.key.padEnd(Mc)),B.createElement(K,{color:"gray"},e.description))))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Examples"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Uc.map(t=>B.createElement(V,{key:t.key},B.createElement(K,null,t.key.replace(/^cmd/,e).padEnd(Mc)),B.createElement(K,{color:"gray"},t.description))))),B.createElement(V,{marginBottom:1},B.createElement(K,{color:"cyan"},"❯"),B.createElement(K,{color:"gray"}," ",jc.replace(/cmd/,e))),B.createElement(V,{flexDirection:"column"},B.createElement(K,{bold:!0},"Links"),B.createElement(V,{flexDirection:"column",paddingLeft:2},_c.map(e=>B.createElement(V,{key:e.key},B.createElement(K,null,e.key.padEnd(Mc)),B.createElement(K,{color:"cyan"},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?B.createElement(HelpMessage,null):B.createElement(V,{flexDirection:"column"},B.createElement(K,{wrap:"wrap"},B.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return B.createElement(V,null,B.createElement(K,{color:"red"},t?ke.pointer:ke.warning),B.createElement(V,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?B.createElement(K,{color:"red",wrap:"wrap"},e):B.createElement(Markdown,{color:"red"},e)))}function AutoCompactMessage({content:e}){return B.createElement(V,null,B.createElement(K,{dimColor:!0},ke.info),B.createElement(V,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(K,{dimColor:!0},e)))}function InfoMessage({content:e,metadata:t}){return t?.isAutoCompact?B.createElement(AutoCompactMessage,{content:e}):B.createElement(V,null,B.createElement(K,{dimColor:!0},ke.info),B.createElement(V,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(K,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return B.createElement(V,{flexDirection:"column",marginBottom:0,marginTop:-1},B.createElement(V,{columnGap:1},B.createElement(K,null,"⎿"," "),B.createElement(V,{flexGrow:1,flexShrink:1,minWidth:0},B.createElement(K,{color:n?"yellow":void 0},e))),t&&B.createElement(V,{marginLeft:3},B.createElement(K,{dimColor:!0},"See ",t)))}function IDEStatusMessage({status:e,ide:t,details:n}){return B.createElement(V,{flexDirection:"column"},B.createElement(V,null,"connected"===e&&B.createElement(K,null,B.createElement(K,{color:"green"},ke.tick),B.createElement(K,null," Connected to "),B.createElement(K,{color:"cyan"},t)),"installed"===e&&B.createElement(K,null,B.createElement(K,{color:"green"},ke.tick),B.createElement(K,null," Installed for "),B.createElement(K,{color:"cyan"},t)),"needs_reload"===e&&B.createElement(K,null,B.createElement(K,{color:"yellow"},ke.circle),B.createElement(K,null," "),B.createElement(K,{color:"cyan"},t),B.createElement(K,null," extension needs reload")),"failed"===e&&B.createElement(K,null,B.createElement(K,{color:"red"},ke.cross),B.createElement(K,null," Install failed")),"not_in_ide"===e&&B.createElement(K,null,B.createElement(K,{color:"yellow"},ke.circle),B.createElement(K,null," Not in IDE"))),n?.map((e,t)=>B.createElement(K,{key:t,dimColor:!0}," ",e)))}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"}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),In(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),At(),__name(ErrorMessage,"ErrorMessage"),At(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(InfoMessage,"InfoMessage"),At(),__name(CommandResultMessage,"CommandResultMessage"),At(),__name(IDEStatusMessage,"IDEStatusMessage"),jn(),Rt(),In(),__name(getModelShortName,"getModelShortName");var zc=B.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const s=t?["header",...e]:e,a=oo();getTerminalWidth();const i=getPackageJson().version||"0.0.0",c=o?getModelShortName(o):"sonnet-4.5",l=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",u=l.replace(d,"~"),m=getGitHeaderInfo();return B.createElement(J,{items:s,key:n,style:{width:"100%"}},e=>{if("header"===e)return B.createElement(V,{key:"header",marginBottom:1,flexDirection:"column"},B.createElement(Ve,{name:"vice"},B.createElement(K,null,a.trimEnd())),B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(V,null,B.createElement(K,{color:"gray"},"# "),B.createElement(K,{bold:!0},"Command Code"),B.createElement(K,{color:"gray"}," v",i)),B.createElement(K,{color:"gray"},"# models: ",c," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),B.createElement(V,null,B.createElement(K,{color:"gray"},"# ",u,m&&m.isLocal&&m.branch&&B.createElement(K,{color:"gray"}," (branch: ",m.branch,")")))));const t=e,n=(()=>{switch(t.role){case"user":return B.createElement(UserMessage,{content:t.input});case"assistant":return B.createElement(AssistantMessage,{content:t.input});case"tool":return B.createElement(ToolMessage,{name:Ms(t.name||""),input:t.input,output:t.output||"",isPending:$s(t),hasError:Is(t),metadata:t.metadata,expandedOutput:r});case"bash":return B.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:$s(t),hasError:Is(t)});case"system":return B.createElement(SystemMessage,{content:t.input});case"info":return B.createElement(InfoMessage,{content:t.input,metadata:t.metadata});case"error":return B.createElement(ErrorMessage,{content:t.input});case"command-result":return B.createElement(CommandResultMessage,{message:t.input,details:t.details,hasError:t.hasError??!1});case"ide-status":return B.createElement(IDEStatusMessage,{status:t.status,ide:t.ide,details:t.details});default:return B.createElement(B.Fragment,null)}})();return B.createElement(V,{key:t.id,marginBottom:1,width:"90%"},n)})});function getModelOptions(){return Object.values(kt).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}At(),Rt(),__name(getModelOptions,"getModelOptions");var Wc=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0;return B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(V,null,B.createElement(K,{color:"#E4CCFF",bold:!0},"Select model")),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),B.createElement(He,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const o=r.find(e=>e.label===t),s=o?.value===n,a=e?"green":"gray";return B.createElement(V,null,B.createElement(K,{color:a},` ${(o?.label||t).padEnd(24)}`),B.createElement(K,{dimColor:!0},o?.description),s&&B.createElement(K,{color:"green"}," ✓"))}}),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press "),B.createElement(K,{dimColor:!0,bold:!0},"Esc"),B.createElement(K,{dimColor:!0}," to cancel")))},"ModelSelector");At(),Rt();var Hc=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[o]=z(0),s=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],a=__name(e=>{const t=s.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),i=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),c=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const n=t.basename(e.filePath),r=t.relative(process.cwd(),e.filePath);return r&&!r.startsWith("../")&&r.length<50?r:n||e.filePath}catch{return e.filePath}},"getDisplayPath"),l=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,color:"yellow"},`${l()} ${"edit"===e.action?c():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&B.createElement(V,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c(),marginLeft:0}).diffContent),B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0},"Do you want to ",i()," ",B.createElement(K,{color:"cyan"},c()),"?")),B.createElement(He,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:o,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"cyan"},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(K,{color:t?"cyan":"white"},e.includes("(shift+tab)")?B.createElement(B.Fragment,null,e.split("(shift+tab)")[0],B.createElement(K,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?B.createElement(B.Fragment,null,e.split("(")[0],B.createElement(K,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt");At(),In();var Gc=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,a=n&&-1===s;return B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(V,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},B.createElement(V,null,B.createElement(K,{bold:!0},"Select AI Provider")),n&&B.createElement(V,{flexDirection:"row"},B.createElement(K,{dimColor:!0},"Current: "),B.createElement(K,{color:"green"},getProviderDisplayName(n)),a&&B.createElement(K,{color:"yellow"}," [OAuth enforced]"))),B.createElement(V,{marginBottom:0},B.createElement(K,{dimColor:!0},"Available Providers:")),B.createElement(He,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"cyan":"gray",bold:e},` ${t}`)}),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");At();var qc=__name(({staticKey:e})=>B.createElement(J,{items:[{staticKey:e}],key:e},()=>B.createElement(K,{key:e},"\0")),"Responsive");function RetryMessage({attempt:e}){const[t,n]=z(0);if(H(()=>{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(V,{marginBottom:1},B.createElement(K,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}At(),__name(RetryMessage,"RetryMessage"),At(),Gt();var Vc=[{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"}],Kc=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=q(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=z(Math.max(0,r.length-1)),[a,i]=z(Math.max(0,r.length-8)),[c,l]=z("checkpoint"),[d,u]=z(null),[m,g]=z(0),p=q(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),h=q(()=>p?Vc:Vc.filter(e=>"conversation"===e.mode),[p]);if(H(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),Z((e,p)=>{p.escape?"mode"===c?(l("checkpoint"),u(null),g(0)):n():"checkpoint"===c?p.upArrow?s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t}):p.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(t-8+1),t}):p.return&&r.length>0&&(u(r[o]),l("mode"),g(0)):"mode"===c&&(p.upArrow?g(e=>Math.max(0,e-1)):p.downArrow?g(e=>Math.min(h.length-1,e+1)):p.return&&d&&h[m]&&t({messageId:d.messageId,mode:h[m].mode}))}),0===r.length)return B.createElement(V,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),B.createElement(K,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press "),B.createElement(K,{dimColor:!0,bold:!0},"Esc"),B.createElement(K,{dimColor:!0}," to close")));if("mode"===c&&d)return B.createElement(V,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Restore to: "),B.createElement(K,{color:"white"},truncateString2({text:d.userPrompt||"checkpoint",maxLength:50}))),B.createElement(V,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return B.createElement(V,{key:e.mode,flexDirection:"column"},B.createElement(V,{flexDirection:"row"},B.createElement(K,{color:n?"#E4CCFF":void 0},n?`${jt} `:" "),B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:n?"#E4CCFF":"white"},e.label),B.createElement(K,{dimColor:!0},e.description))),!r&&B.createElement(K,null," "))})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press "),B.createElement(K,{dimColor:!0,bold:!0},"Enter"),B.createElement(K,{dimColor:!0}," to confirm, "),B.createElement(K,{dimColor:!0,bold:!0},"Esc"),B.createElement(K,{dimColor:!0}," to go back")));const f=r.slice(a,a+8);return B.createElement(V,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),B.createElement(K,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),B.createElement(V,{marginTop:1}),B.createElement(V,{flexDirection:"column"},f.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,c=t===f.length-1,l=n===r.length-1;return B.createElement(V,{key:e.messageId,flexDirection:"column"},B.createElement(V,{flexDirection:"row"},B.createElement(K,{color:s?"#E4CCFF":void 0},s?`${jt} `:" "),B.createElement(V,{flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:s?"#E4CCFF":"white"},truncateString2({text:e.userPrompt||"(no prompt)",maxLength:60})),B.createElement(K,{dimColor:!0}," • "),B.createElement(K,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),l&&" (latest)")),B.createElement(K,{dimColor:!0},i>0?`${i} file${i>1?"s":""} changed`:"No code changes"))),!c&&B.createElement(K,null," "))})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press "),B.createElement(K,{dimColor:!0,bold:!0},"Enter"),B.createElement(K,{dimColor:!0}," to select, "),B.createElement(K,{dimColor:!0,bold:!0},"Esc"),B.createElement(K,{dimColor:!0}," to cancel")))},"RewindSelector");At();var Jc=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=X(),[r,o]=z([]),[s,a]=z(0),[i,c]=z(!0),[l,d]=z(0),u=30;H(()=>{m()},[]);const m=__name(async()=>{c(!0);const e=await Pa.listSessions();o(e),c(!1)},"loadSessions");if(Z((t,o)=>{o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t}):o.downArrow?a(e=>{const t=Math.min(r.length-1,e+1);return t>=l+u&&d(t-u+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),i)return B.createElement(V,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(K,{color:"gray"},"Loading sessions..."));const g=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5),a=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:s<7?`${s} day${s>1?"s":""} ago`:1===a?"1 week ago":`${a} weeks ago`},"formatRelativeTime"),p=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"gray"},"No sessions available"));const h=r.slice(l,l+u),f=l;return B.createElement(V,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>u&&B.createElement(V,{marginBottom:1},B.createElement(K,{color:"dim"},"Showing ",l+1,"-",Math.min(l+u,r.length)," ","of ",r.length," sessions",l>0&&" (↑ for more)",l+u<r.length&&" (↓ for more)")),B.createElement(V,{columnGap:2,marginBottom:1},B.createElement(V,{width:7},B.createElement(K,{color:"gray"}," ")),B.createElement(V,{width:13},B.createElement(K,{color:"gray"},"Modified")),B.createElement(V,{width:11},B.createElement(K,{color:"gray"},"# Messages")),B.createElement(V,{width:20},B.createElement(K,{color:"gray"},"Git Branch")),B.createElement(V,null,B.createElement(K,{color:"gray"},"Summary"))),B.createElement(V,{columnGap:2},B.createElement(V,{flexDirection:"column",width:7},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${ke.pointer} ${n+1}.`:` ${n+1}.`)})),B.createElement(V,{flexDirection:"column",width:13},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`mod-${e.id}`,color:s===n?"white":"gray"},g(e.lastModified))})),B.createElement(V,{flexDirection:"column",width:11},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),B.createElement(V,{flexDirection:"column",width:20},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),B.createElement(V,{flexDirection:"column"},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`summary-${e.id}`,color:s===n?"white":"gray"},p(e.firstMessage))}))))},"SessionTable");function moveFocusDown(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?n>0?{...e,zone:"suggestions",suggestionIndex:0}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:e:"suggestions"===e.zone?e.suggestionIndex<n-1?{...e,suggestionIndex:e.suggestionIndex+1}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:{...e,zone:"input"}:e.activeDirIndex<r-1?{...e,activeDirIndex:e.activeDirIndex+1}:{...e,zone:"input"}}function moveFocusUp(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?r>0?{...e,zone:"active-dir",activeDirIndex:r-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:e:"suggestions"===e.zone?e.suggestionIndex>0?{...e,suggestionIndex:e.suggestionIndex-1}:{...e,zone:"input"}:e.activeDirIndex>0?{...e,activeDirIndex:e.activeDirIndex-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:{...e,zone:"input"}}function getAdjustedSuggestionOffset(e){const{selectedIndex:t,currentOffset:n,maxVisible:r,totalSuggestions:o}=e;return o<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),o=e.replace(/\\/g,"/");if(o.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${o.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:o};const s=o.lastIndexOf("/");return-1===s?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:o.slice(0,s+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),o=n.startsWith(".")||r.includes("/.");return w.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!o||!e.name.startsWith(".")).filter(e=>!n||e.name.toLowerCase().startsWith(n.toLowerCase())).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>`${r}${e.name}/`)}catch(e){const t=e.code;return"ENOENT"!==t&&"ENOTDIR"!==t&&console.error(`Warning: Could not list directory suggestions: ${t}`),[]}}function getFooterText(e){return"active-dir"===e.focusZone?"[Enter] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}At(),Ft(),At(),Ft(),__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 Yc=__name(({onClose:e})=>{const[t,n]=z(""),[r,o]=z(null),[s,a]=z([]),[i,c]=z(getAdditionalDirectories()),[l,d]=z({zone:"input",suggestionIndex:0,activeDirIndex:0}),[u,m]=z(0);H(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),H(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const g=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),c(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),p=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void c(getAdditionalDirectories());o({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),c(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");Z((r,a)=>{if(a.escape)e();else{if(a.return)return"active-dir"===l.zone&&i[l.activeDirIndex]?void p(i[l.activeDirIndex]):"suggestions"===l.zone&&s[l.suggestionIndex]?void g(s[l.suggestionIndex]):void g(t);if((a.delete||a.backspace)&&"active-dir"===l.zone&&i[l.activeDirIndex])p(i[l.activeDirIndex]);else{if(a.tab&&s.length>0){const e=s[l.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}if(a.downArrow)d(e=>moveFocusDown(e,{suggestionCount:s.length,activeDirCount:i.length}));else if(a.upArrow)d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:i.length}));else if("input"===l.zone){if(a.backspace||a.delete)return n(e=>e.slice(0,-1)),void o(null);!r||a.ctrl||a.meta||(n(e=>e+r),o(null))}}}}),H(()=>{"suggestions"===l.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:l.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[l,s.length]),H(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=s.length?{...e,zone:"input",suggestionIndex:Math.max(0,s.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=i.length?{...e,zone:"input",activeDirIndex:Math.max(0,i.length-1)}:e)},[s.length,i.length]);const h=s.slice(u,u+8),f=getFooterText({focusZone:l.zone});return B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},B.createElement(K,{bold:!0,color:"cyan"},"Add directory to workspace"),B.createElement(K,{color:"gray"},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,{color:"gray"},"Added directories"),0===i.length?B.createElement(K,{color:"gray"}," None yet"):i.map((e,t)=>{const n="active-dir"===l.zone&&l.activeDirIndex===t;return B.createElement(K,{key:e,color:n?"yellow":"green",bold:n},n?` ${ke.pointer} `:" ",formatDirectoryForDisplay(e))})),B.createElement(V,{marginTop:1},B.createElement(K,{bold:!0,color:"white"},"Path")),B.createElement(V,null,B.createElement(K,{color:"input"===l.zone?"cyan":"gray"},"input"===l.zone?ke.pointer:" "),B.createElement(K,null," "),B.createElement(K,{color:"white"},t),"input"===l.zone&&B.createElement(K,{color:"gray"},"█")),!t&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray"},"Examples: ../shared ~/docs /abs/path")),r&&B.createElement(V,{marginTop:1},B.createElement(K,{color:{error:"red",warning:"yellow",success:"green"}[r.tone]},r.text)),s.length>0&&B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(K,{color:"gray"},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===l.zone&&l.suggestionIndex===n;return B.createElement(K,{key:e,color:r?"cyan":"gray",bold:r},r?` ${ke.pointer} `:" ",e)})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},f)))},"AddDirModal");At(),Rt();var Qc=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=z(0),o=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],s=__name(e=>{const r=o.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),a=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"",n=t?`${e.command} ${t}`:e.command;return n.length>60?n.substring(0,57)+"...":n},"getCommandDisplay");return B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,color:"yellow"},"Execute Shell Command")),B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0},"Command Code needs to execute ",B.createElement(K,{color:"cyan"},a()),".")),e.workingDirectory&&B.createElement(V,{marginBottom:1},B.createElement(K,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0,italic:!0},e.description)),B.createElement(He,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"cyan"},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(K,{color:t?"cyan":"white"},e.includes("(shift+tab)")?B.createElement(B.Fragment,null,e.split("(shift+tab)")[0],B.createElement(K,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt");At();var Zc=__name(({onClose:e,staticKey:t})=>{const[n,r]=z([]),[o,s]=z(!0),[a,i]=z(null),{stdout:c}=Q(),l=c?.columns??80,d=__name((e,t)=>e.length<=t?e:t<=3?e.substring(0,t):e.substring(0,t-3)+"...","truncateText");H(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),n=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];r(n)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=__name(async t=>{const r=n.find(e=>e.value===t.value);if(r)try{await Qe([{file:r.filePath,line:1}]),ri(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(m()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelect");Z((t,n)=>{n.escape&&(ri(),e())});const m=__name(()=>{const e=process.platform;return"win32"===e?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===e?"~/.zshrc":"~/.bashrc")},"getEditorSetupMessage");return o?B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills"),B.createElement(K,{dimColor:!0},"Loading skills...")):a?B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,{color:"red",bold:!0},"Agent Skills"),B.createElement(K,{dimColor:!0},a),B.createElement(V,{marginTop:1}),B.createElement(K,{dimColor:!0},"Press ",B.createElement(K,{bold:!0},"Esc")," to close")):0===n.length?B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills"),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"No skills found")),B.createElement(K,{dimColor:!0},"Create skills in:"),B.createElement(K,{dimColor:!0}," ~/.commandcode/skills/ (user)"),B.createElement(K,{dimColor:!0}," .commandcode/skills/ (project)"),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press ",B.createElement(K,{bold:!0},"Esc")," to close"))):B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(V,null,B.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills")),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Select a skill to open in your editor. Skills provide specialized guidance for coding tasks.")),B.createElement(He,{items:n,onSelect:u,initialIndex:0,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const r=n.find(e=>e.label===t),o=r?.location?` (${r.location})`:"",s=Math.max(30,l-35),a=r?.description?d(r.description,s):"";return B.createElement(V,null,B.createElement(K,{color:e?"green":"white"},` ${t}`),B.createElement(K,{color:"gray"},o.padEnd(25-t.length)),B.createElement(K,{color:"gray"},a))}}),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press ",B.createElement(K,{bold:!0},"Esc")," to cancel")))},"SkillsConfig");At(),An();var Xc=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=z(!1),[s,a]=z(!0);H(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{a(!1)}},"loadSettings")()},[]),Z((t,n)=>{if(!n.return&&" "!==t)return n.escape?(ri(),void e()):void 0;i()});const i=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return s?B.createElement(V,{key:n,borderStyle:"single",borderColor:"blue",padding:1,flexDirection:"column"},B.createElement(K,{color:"blue",bold:!0},"Taste Settings"),B.createElement(K,{dimColor:!0},"Loading configuration...")):B.createElement(V,{key:n,borderStyle:"single",borderColor:"gray",padding:1,flexDirection:"column"},B.createElement(K,{bold:!0},"Taste Learning"),B.createElement(K,{dimColor:!0},"Configure taste learning preferences for this project"),B.createElement(V,{marginTop:1}),B.createElement(V,{justifyContent:"space-between"},B.createElement(K,null,"Taste learning",B.createElement(K,{dimColor:!0}," - Learn from your interactions")),B.createElement(K,{color:r?"green":"gray"},r?"enabled":"disabled")),B.createElement(V,{marginTop:1}),B.createElement(K,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),B.createElement(K,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig");At(),Cn(),At(),At();var el=__name(e=>{const[t,n]=z(e),[r,o]=z(null);return H(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),o(null)},"handleReset"),r=__name(e=>{"error"!==e.type?n(t=>{if("step_start"===e.type){const n=t.findIndex(t=>t.id===e.step);return n<0?t:t.map((t,r)=>r<n?{...t,active:!1,complete:!0}:r===n?{...t,active:!0,message:e.message||"",...e.label&&{label:e.label},..."complete"===e.step&&{complete:!0},...void 0!==e.learningCount&&void 0!==e.categories&&void 0!==e.storage&&t.summary&&{summary:{learningCount:e.learningCount,categories:e.categories,storage:e.storage}}}:t)}if("progress"===e.type){const n=t.findIndex(e=>e.active);return n<0?t:t.map((t,r)=>r===n?{...t,items:[...t.items,e.message]}:t)}if("insight"===e.type){const n=t.findIndex(e=>"learning"===e.id);return n<0?t:t.map((t,r)=>r===n?{...t,insights:[...t.insights,e.message]}:t)}return t}):o(e.message)},"handleNewEvent");return za.on("reset",t),za.on("new-event",r),()=>{za.off("reset",t),za.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new Co({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;if(n===wt.ANTHROPIC)try{const e=await Bt.getValidAccessToken();validateOAuthToken({token:e,provider:n}),o=e}catch(e){dlog("Failed to get or validate Anthropic OAuth token:",e instanceof Error?e.message:String(e))}const s={[pt.PROJECT_SLUG]:Pa.getCurrentProjectDirName(),[pt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(s[pt.OAUTH_TOKEN]=`Bearer ${o}`),{request:t,headers:s}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}At(),At(),Cn(),At(),Cn(),At(),At(),Rt(),qt(),Cn(),An(),$n(),__name(createRequestClient,"createRequestClient"),At(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),At(),At(),Rt(),Cn(),Wt(),At();var tl="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:${tl}`,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}`),za.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()}`),za.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=Be.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 ${ht.ALPHA.GENERATE} with model: ${tl}`);const r=buildRequestBody2(n);let o;try{o=await e.post({endpoint:ht.ALPHA.GENERATE,body:r,headers:t,stream:!0}),dlog("[ObserverAPI] got response stream")}catch(e){throw dlog(`[ObserverAPI] request failed: ${e instanceof Error?e.message:String(e)}`),e}await processStream(o),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const a=buildObserverPrompt(n,4);await callObserverAPI(e,t,a)}async function observeSessionPrompts(e){if(za.observerHasRun)return;za.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${r.length} batches`);const o=Math.min(r.length,6);for(let t=0;t<o;t++){if(za.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const o=r[t];try{await processBatch(e,n,o,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),za.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 nl=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(p.homedir(),".claude","projects");await D.access(r);const o=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await D.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await D.stat(s)).isDirectory())continue;const r=(await D.readdir(s)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const o of r){const r=e.join(s,o),a=await D.stat(r),i=o.replace(".jsonl","");if(n.push({id:i,filePath:r,createdAt:a.birthtime,lastModified:a.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{za.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&za.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 D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[];try{za.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const o=await loadProjectSettings(),s=o.tasteOnboarding?.learnedSessions||{},a=s["claude-code"]?.length||0,i=s.codex?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${i} learned`);const c=await findNewSessions(s),l=c["claude-code"]||[],d=c.codex||[],u=l.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${l.length} new, codex=${d.length} new`),0===u){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=e.length+t.length,r=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);za.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:n>0?`From ${r.join(" + ")} sessions`:"No sessions found for this project"});const o=[];return e.length>0&&o.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&o.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:n,learnedSessions:a+i,agentSessions:o,status:"already-learned"}}if(l.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>l.includes(e.id));n.push(...e)}if(d.length>0){const e=(await this.findCodexSessions()).filter(e=>d.includes(e.id));r.push(...e)}const m=n.length+r.length;dlog(`[Import] total sessions: ${m} (claude-code: ${n.length}, codex: ${r.length})`),za.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){za.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const p=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${p.length} batches`);const h=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});za.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${p.length} batch${1===p.length?"":"es"}`});try{const o=getApiBaseUrl(),s=new Co({baseUrl:o});let a=!0;for(let e=0;e<p.length;e++){const t=p[e],n=e+1,r=p.length;r>1&&za.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),i=new Ha({request:s,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),c=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await i.checkAndProcess({messages:c})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),za.markLearningComplete(),await h,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const i=await this.extractLearningSummary(),c=[];if(n.length>0&&c.push(`Claude Code (${n.length})`),r.length>0&&c.push(`Codex (${r.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),za.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}return za.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${c.join(" + ")}`,learningCount:i.totalLearnings,categories:i.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),za.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 D.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),o=r?r.length:0;return{totalLearnings:o,categories:n.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}},rl=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),ol=__name(e=>{const[t,n]=z({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return H(()=>{za.reset(),za.markImportStarted(),(async()=>{try{const t=await Promise.race([nl.importAndLearn(),rl(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");At();var sl=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{Z((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");At(),Cn();var al=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=z(null),[o,s]=z(null),a=W(!1);return H(()=>{if(a.current)return;let n=null;return(async()=>{try{a.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{za.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{za.reset(),e()}}At(),Cn(),At(),Cn(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var il=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=W(n),o=G(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=G(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=G(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=G(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current())},[e]),c=G(async()=>{dlog("[Handler] demo complete → done"),e("done"),await markDemoShown(),await completeOnboarding(()=>r.current())},[e]),l=G(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current())},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:a,handleErrorDismiss:i,handleDemoComplete:c,handleSkip:l}},"useOnboardingHandlers");At(),Cn();var cl=__name(({conditions:e,autoLearn:t})=>{const[n,r]=z("checking"),o=W(!1);return H(()=>{if(e&&!o.current){if(o.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),H(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");At(),At();var ll=__name(({error:e})=>B.createElement(V,{padding:1},B.createElement(V,{flexDirection:"column",borderColor:"red",padding:1},B.createElement(V,{marginBottom:1},B.createElement(K,null,"Error initializing onboarding: ",e)),B.createElement(V,null,B.createElement(K,null,"Continuing without onboarding...")))),"OnboardingError");At(),At();var dl=[{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}],ul=__name(({onComplete:e})=>{const[t,n]=z(0),[r,o]=z(!1),s=t>=dl.length;H(()=>{if(t>=dl.length)return;if(r)return;const e=dl[t],o=setTimeout(()=>{n(e=>Math.min(e+1,dl.length))},e.duration);return()=>clearTimeout(o)},[t,r]),Z((t,r)=>{r.escape?e():s?(r.return||" "===t)&&e():" "===t?o(e=>!e):r.return&&n(e=>Math.min(e+1,dl.length))});const a=dl.slice(0,t);return B.createElement(V,{flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:"cyan"},"Meet Your Coding Taste")),B.createElement(V,null,B.createElement(K,null,"Command Code learns your coding style as you work.")),B.createElement(V,null,B.createElement(K,null,"Here's how your preferences evolve in real-time:")),B.createElement(V,{flexDirection:"column",marginY:1},0===a.length&&!s&&B.createElement(K,{dimColor:!0},"Starting demo..."),a.map((e,t)=>"user"===e.type?B.createElement(V,{key:t},B.createElement(K,{color:"white"},`${ke.pointer} ${e.text}`)):B.createElement(V,{key:t,marginBottom:1,marginTop:0,marginLeft:1},B.createElement(V,null,B.createElement(K,null,"⎿"),B.createElement(V,{flexDirection:"column",marginLeft:2,marginTop:0},B.createElement(K,{color:"green"},e.text),e.details&&B.createElement(K,{dimColor:!0},"Saved(",e.details,")")))))),s&&B.createElement(V,{flexDirection:"column",marginY:1,width:80},B.createElement(V,null,B.createElement(K,{color:"green",bold:!0},"Demo Complete!"," ")),B.createElement(K,null,"Command Code will now use these preferences to generate better suggestions tailored to your coding style. The more you code, the smarter it gets."),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press Enter to get started →"))),!s&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"," ",r?"(paused)":"")))},"TasteDemoComponent");At(),Rt();var ml=__name(()=>`(run /${St.LEARN_TASTE} anytime)`,"getSkipHint"),gl=__name(()=>B.createElement(K,null,"Skip for now"," ",B.createElement(K,{dimColor:!0},ml())),"SkipOptionText"),pl=__name(({sessionCount:e,agentSessions:t,onImport:n,onDemo:r,onSkip:o,demoShown:s=!1})=>{const[a,i]=z(1),c=s?2:3,l=s?2:3;return Z((e,t)=>{if(t.escape)o();else if(t.upArrow)i(e=>1===e?c:e-1);else if(t.downArrow)i(e=>e===c?1:e+1);else if("1"!==e)if("2"!==e)if("3"!==e||s){if(t.return){if(1===a)return void n();if(2===a)return void(s?o():r());o()}}else o();else s?o():r();else n()}),B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},B.createElement(K,{color:"cyan",bold:!0},"Build Your Coding Taste"),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),B.createElement(V,{marginTop:1},B.createElement(K,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:1===a?"cyan":"gray"},1===a?ke.pointer:" "," 1. Yes, learn from my sessions (recommended)")),!s&&B.createElement(V,null,B.createElement(K,{color:2===a?"cyan":"gray"},2===a?ke.pointer:" "," ","2. No, show me a demo instead")),B.createElement(V,null,B.createElement(K,{color:a===l?"cyan":"gray"},a===l?ke.pointer:" "," ",l,". ",B.createElement(gl,null)))),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice"),hl=__name(({onDemo:e,onSkip:t})=>{const[n,r]=z(1);return Z((o,s)=>{s.escape?t():s.upArrow||s.downArrow?r(e=>1===e?2:1):"1"!==o?"2"!==o?s.return&&(1===n?e():t()):t():e()}),B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",padding:1},B.createElement(K,{color:"cyan",bold:!0},"No Previous Sessions Found"),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,null,"No previous sessions found to analyze."),B.createElement(V,{marginTop:1},B.createElement(K,null,"Would you like to see how taste learning works?"))),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:1===n?"cyan":"gray"},1===n?ke.pointer:" "," 1. Yes, show me a demo")),B.createElement(V,null,B.createElement(K,{color:2===n?"cyan":"gray"},2===n?ke.pointer:" "," 2."," ",B.createElement(gl,null)))),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"NoSessionsChoice");At(),At();var fl=__name(({error:e})=>B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"red",paddingX:2,paddingY:1,marginBottom:2},B.createElement(K,{color:"red",bold:!0},"Oops, something went wrong:"),B.createElement(V,{marginTop:1},B.createElement(K,null,e))),"ErrorSection");At(),At(),At(),At(),At();var yl=[ke.bullet,ke.squareSmallFilled,ke.lozenge,ke.star,ke.triangleRight,ke.triangleUp,ke.circleFilled,ke.pointer],wl=__name(()=>B.createElement(K,{backgroundColor:"green",color:"black"}," TASTE "),"TasteBadge"),El=["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"],Sl=__name(()=>{const[e,t]=z(()=>Math.floor(Math.random()*El.length));H(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*El.length))},2e3);return()=>clearInterval(e)},[]);const n=El[e];return B.createElement(K,{color:"yellow"},n,"...")},"PulsingText"),kl=__name(e=>String(e).padStart(3," "),"padNum"),vl=__name(e=>yl[e%yl.length],"getSymbol"),bl=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${kl(t)} ↓${kl(n)} (↑↓ scroll)`,"buildStatusLine"),Cl=__name(({insights:e})=>{const[t,n]=z(0),[r,o]=z(!0),s=e.length,a=s>10,i=Math.max(0,s-10);if(H(()=>{r&&a&&n(i)},[s,r,a,i]),Z((e,t)=>{if(a)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(i,e+1);return t===i&&o(!0),t}))}),0===s)return null;const c=e.slice(t,t+10),l=t,d=s-t-10;return B.createElement(V,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&B.createElement(K,{dimColor:!0},bl(s,l,d,r)),c.map((e,n)=>{const r=t+n;return B.createElement(V,{key:r,marginBottom:0},B.createElement(K,{dimColor:!0},vl(r)," ",e))}))},"ScrollableInsights"),Pl=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:c})=>{if(a)return B.createElement(V,{flexDirection:"column",marginBottom:0},B.createElement(wl,null),B.createElement(V,{marginTop:0},B.createElement(K,{dimColor:!0},"⎿"),B.createElement(V,{marginLeft:2},i?B.createElement(K,{color:"green"},"learned your coding taste"):B.createElement(Sl,null))));const l=__name(()=>{const[e,t]=z(!0);return H(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),B.createElement(K,{color:"yellow"},e?ke.circleFilled:ke.circle)},"PulsingDot"),d=__name(()=>r?B.createElement(K,{color:"green"},ke.nodejs):n?B.createElement(l,null):B.createElement(K,{dimColor:!0},ke.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||c&&c.learningCount>0;return!r||n||u?B.createElement(V,{flexDirection:"column",marginBottom:0},(n||r)&&B.createElement(V,{marginBottom:0},B.createElement(V,{marginRight:1},d()),B.createElement(K,{color:r?"white":n?"yellow":"dim"},e)),r&&t&&(!c||0===c.learningCount)&&B.createElement(V,{marginLeft:3,marginBottom:0},B.createElement(K,{dimColor:!0},t)),o.length>0&&B.createElement(V,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>B.createElement(K,{key:t,dimColor:!0},`${ke.bullet} ${e}`))),s.length>0&&B.createElement(Cl,{insights:s}),r&&c&&c.learningCount>0&&B.createElement(V,{flexDirection:"column",marginLeft:1,marginBottom:0},B.createElement(V,{marginBottom:1,flexDirection:"row"},B.createElement(K,null,"⎿"),B.createElement(V,{marginLeft:2},B.createElement(K,{color:"green"},"Learned ",c.learningCount," preference",1===c.learningCount?"":"s",c.categories.length>0?` across ${c.categories.length} ${1===c.categories.length?"category":"categories"}`:""))),B.createElement(V,{flexDirection:"column",marginLeft:1},B.createElement(K,{dimColor:!0},ke.pointerSmall," Stored in"," ",c.storage),B.createElement(K,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),Tl=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return B.createElement(V,{flexDirection:"column",marginBottom:1},e.map((e,n)=>B.createElement(V,{key:e.id,marginLeft:0===n?0:3},B.createElement(Pl,{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"),Al=__name(({steps:e})=>B.createElement(Tl,{steps:e}),"ProgressSection");At();var xl=__name(({isImporting:e=!1,waitingForInput:t=!1})=>B.createElement(B.Fragment,null,e&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"ESC to cancel")),t&&B.createElement(V,{marginTop:1},B.createElement(K,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");At();var Il=[{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"}}],$l=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=el(Il),{isImporting:s,waitingForInput:a,error:i}=ol(t);return sl({onEscape:e,onEnter:__name(()=>{a&&(i&&n?n():e())},"onEnter"),enabled:s||a}),B.createElement(V,{flexDirection:"column",padding:1},o&&B.createElement(fl,{error:o}),!o&&B.createElement(Al,{steps:r}),B.createElement(xl,{isImporting:s,waitingForInput:a}))},"ImportProgress"),Rl=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onDemoComplete:a,onDemo:i,onSkip:c})=>"asking"===e?"has_sessions"!==t?.reason?B.createElement(hl,{onDemo:i,onSkip:c}):B.createElement(pl,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onDemo:i,onSkip:c,demoShown:t.demoShown}):"learning"===e?B.createElement($l,{onComplete:r,onError:o,onErrorDismiss:s}):"demo"===e?B.createElement(ul,{onComplete:a}):null,"OnboardingStepRenderer"),Dl=__name(({onComplete:e,autoLearn:t=!1})=>{H(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=al({autoLearn:t,onShouldSkip:e}),{step:s,setStep:a}=cl({conditions:n,autoLearn:t}),{handleImportStart:i,handleImportComplete:c,handleImportError:l,handleErrorDismiss:d,handleDemoComplete:u,handleSkip:m}=il({onStepChange:__name(e=>{a(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?B.createElement(ll,{error:r}):"done"===s?null:B.createElement(Rl,{step:s,conditions:n,onImportStart:i,onImportComplete:c,onImportError:l,onErrorDismiss:d,onDemoComplete:u,onDemo:()=>a("demo"),onSkip:m})},"TasteOnboarding");At(),Rt();var Ml=__name(({onTrust:e,onExit:t})=>{const{exit:n}=X(),[r,o]=z(1),s=process.cwd().replace(process.env.HOME||"","~");return Z((s,a)=>{a.upArrow||a.downArrow?o(1===r?2:1):a.return?1===r?e():(t(),n()):"1"===s?e():("2"===s||a.escape||a.ctrl&&"c"===s)&&(t(),n())}),B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",padding:1},B.createElement(K,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray"},s)),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),B.createElement(V,{marginTop:1},B.createElement(K,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:1===r?"cyan":"gray"},1===r?ke.pointer:" "," 1. Yes, proceed")),B.createElement(V,null,B.createElement(K,{color:2===r?"cyan":"gray"},2===r?ke.pointer:" "," 2. No, exit"))))},"TrustPrompt");At(),xn(),In();var Nl=__name(({onComplete:e,onCancel:t})=>{const[n,r]=z(!1),[o,s]=z(""),{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u,cancel:m}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return Z((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");m()}}),n?B.createElement(Pn,{onSuccess:()=>{e(!0,o?`Logged in as ${o} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,o?`Logged in as ${o}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):B.createElement(Fr,{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u})},"LoginOverlay");At(),At(),$n();var Ol=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),Fl=__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"),Ll=__name(({icon:e,label:t,children:n})=>B.createElement(K,null,B.createElement(K,{color:"cyan"},e," "),B.createElement(K,{dimColor:!0},t.padEnd(12)),n),"Row"),_l=__name(({title:e})=>B.createElement(K,null,B.createElement(K,{color:"gray"},"───"),B.createElement(K,{color:"white"}," ",e," "),B.createElement(K,{color:"gray"},"─".repeat(35))),"Header"),Ul=__name(({title:e,marginTop:t=0,children:n})=>B.createElement(V,{flexDirection:"column",marginTop:t},B.createElement(_l,{title:e}),B.createElement(V,{flexDirection:"column",paddingY:1},n)),"Section"),jl=__name(({cpuCount:e,totalMem:t})=>B.createElement(Ul,{title:"System Information"},B.createElement(Ll,{icon:Se.bullet,label:"Date"},B.createElement(K,null,formatDate())),B.createElement(Ll,{icon:Se.pointer,label:"Platform"},B.createElement(K,{color:"green"},Ol(p.platform())),B.createElement(K,{dimColor:!0}," ","(",p.platform(),", ",p.arch(),")")),B.createElement(Ll,{icon:Se.triangleUp,label:"Hostname"},B.createElement(K,null,p.hostname())),B.createElement(Ll,{icon:Se.bullet,label:"User"},B.createElement(K,{color:"yellow"},p.userInfo().username)),B.createElement(Ll,{icon:Se.bullet,label:"CPUs"},B.createElement(K,{color:"magenta"},e," cores")),B.createElement(Ll,{icon:Se.bullet,label:"Memory"},B.createElement(K,{color:"cyan"},t," GB")),B.createElement(Ll,{icon:Se.play,label:"Uptime"},B.createElement(K,null,Fl(p.uptime()))),B.createElement(Ll,{icon:Se.arrowRight,label:"Home"},B.createElement(K,{dimColor:!0},p.homedir())),B.createElement(Ll,{icon:Se.pointer,label:"Shell"},B.createElement(K,null,process.env.SHELL||"N/A")),B.createElement(Ll,{icon:Se.bullet,label:"Node"},B.createElement(K,{color:"green"},process.version))),"SystemInfoSection"),Bl=__name(({cpus:e})=>B.createElement(Ul,{title:"CPU Details",marginTop:1},e.map((e,t)=>B.createElement(Ll,{key:t,icon:Se.bullet,label:`Core ${t}`},B.createElement(K,null,e.model.trim()),B.createElement(K,{color:"yellow"}," @ ",e.speed," MHz")))),"CPUDetailsSection"),zl=__name(({networkInterfaces:e})=>B.createElement(Ul,{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(Ll,{key:`${e}-${n}`,icon:Se.bullet,label:e},B.createElement(K,{color:"green"},t.address))):null})),"NetworkSection"),Wl=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>B.createElement(V,{flexDirection:"column"},B.createElement(K,null,"System Information"),B.createElement(K,null,"─".repeat(40)),B.createElement(K,null,"Date ",formatDate()),B.createElement(K,null,"Platform ",Ol(p.platform())," (",p.platform(),","," ",p.arch(),")"),B.createElement(K,null,"Hostname ",p.hostname()),B.createElement(K,null,"User ",p.userInfo().username),B.createElement(K,null,"CPUs ",e.length," cores"),B.createElement(K,null,"Memory ",t," GB"),B.createElement(K,null,"Uptime ",Fl(p.uptime())),B.createElement(K,null,"Home ",p.homedir()),B.createElement(K,null,"Shell ",process.env.SHELL||"N/A"),B.createElement(K,null,"Node ",process.version),r&&B.createElement(B.Fragment,null,B.createElement(K,null,"\n","CPU Details"),B.createElement(K,null,"─".repeat(40)),e.map((e,t)=>B.createElement(K,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),B.createElement(K,null,"\n","Network"),B.createElement(K,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>B.createElement(K,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Hl=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>B.createElement(V,{flexDirection:"column"},B.createElement(jl,{cpuCount:e.length,totalMem:t}),r&&B.createElement(Bl,{cpus:e}),r&&B.createElement(zl,{networkInterfaces:n})),"StyledInfo"),Gl=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=X();H(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=p.cpus(),o=p.networkInterfaces(),s=Math.round(p.totalmem()/1024/1024/1024);return t?B.createElement(Wl,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e}):B.createElement(Hl,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e})},"InfoUI"),ql={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},Vl=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),Kl=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(Vl("__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"),Jl=__name(()=>{const e=Kl();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&ql[t]?ql[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),Yl=__name(()=>{if("win32"===h.platform()){const e=process.env.COMSPEC;return e?c(e):process.env.SHELL?c(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=c(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?c(e):"N/A"},"getShellName"),Ql=__name(()=>{const e=Kl();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),Zl=__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:Ol(h.platform()),terminal:Jl(),shell:Yl(),version:Zl(),ide:Ql()}}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()}`}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),At(),At(),Cn();var Xl=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(p.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await D.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 D.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await D.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 D.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await D.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await D.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 Xl}__name(createHistoryManager,"createHistoryManager"),At();var ed=__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"),td=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r,hideReview:o=!1})=>{if(o&&1===e.length)return null;const s=[];if(e.forEach((o,a)=>{const i=a===t&&!r,c=n.has(a);let l,d;i?(l="●",d="cyan"):c?(l="✓",d="green"):(l="○",d="gray"),s.push(B.createElement(K,{key:a},B.createElement(K,{color:d},l),B.createElement(K,{color:i?"cyan":void 0}," ",o.header),a<e.length-1?B.createElement(K,{dimColor:!0}," | "):null))}),!o){const e=r;s.push(B.createElement(K,{key:"review"},B.createElement(K,{dimColor:!0}," | "),B.createElement(K,{color:e?"cyan":"gray"},e?"●":"○"),B.createElement(K,{color:e?"cyan":void 0,bold:e}," ","Review")))}return B.createElement(V,null,s)},"TabIndicator"),nd=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,o]=z(0),[s,a]=z(new Map),i=W(new Map),[c,l]=z(""),[d,u]=z(new Set),[m,g]=z(null),[p,h]=z(!1),[f,y]=z(!1),[w,E]=z(!1),[S,k]=z(null),[v,b]=z(!1),C=e[r],P=C?.multiSelect??!1,T=s.get(r),A=C?[...C.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]])),$=__name(e=>{"submit"===e.value?F():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),R=__name(()=>{if(!T||0===T.length)return 0;const e=T[0],t=C.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),D=__name(e=>{if(!p)if(P){const t=ed(e.value,C.options.length-1);if(null===t)return;const n=C.options[t]?.label||"";u(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=ed(e.value,C.options.length-1);if(null===t)return;h(!0);const n=C.options[t]?.label||"";O([n])}},"handleSelect"),M=__name(()=>{if(p)return;h(!0);const e=Array.from(d);O(e)},"handleMultiSelectDone"),N=__name(()=>{if(!p&&c.trim())if(P){const e=new Set(C.options.map(e=>e.label));u(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(c.trim()),n})}else h(!0),O([c.trim()])},"handleOtherSubmit"),O=__name(t=>{i.current.set(r,t);const s=new Map(i.current);a(s);const c=__name(t=>{const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){u(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),n?.multiSelect||1!==r?.length)l("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);l(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;c(e),o(e),h(!1),E(!1),k(null),b(!1)}else if(e.every((e,t)=>s.has(t))){if(n&&1===e.length)return void F();u(new Set),l(""),y(!0),h(!1)}else{const t=e.findIndex((e,t)=>!s.has(t));-1!==t&&(c(t),o(t)),h(!1),E(!1),k(null),b(!1)}},"finishQuestion"),F=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:i.current.get(t)||[]}));t({answers:n})},"submitAnswers"),L=__name(t=>{y(!1),o(t),b(!1),E(!1),k(null);const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){u(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),n?.multiSelect||1!==r?.length)l("");else{const e=r[0],t=!n.options.some(t=>t.label===e);l(t&&e?e:"")}},"editQuestion"),_=__name(t=>{if(t<0||t>=e.length)return;P&&(d.size>0?i.current.set(r,Array.from(d)):i.current.delete(r),a(new Map(i.current))),h(!1),E(!1),k(null),b(!1);const n=e[t],s=i.current.get(t);if(n?.multiSelect&&s){u(new Set(s));const e=s.find(e=>!n.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),n?.multiSelect||1!==s?.length)l("");else{const e=s[0],t=!n.options.some(t=>t.label===e);l(t&&e?e:"")}o(t)},"navigateToQuestion"),U=__name(()=>{if(!m||!P)return;if("done"===m.value)return;const e=ed(m.value,C.options.length-1);if(null===e)return;const t=C.options[e]?.label||"";u(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return Z((t,o)=>{if(" "===t&&P&&!w&&U(),"d"!==t||!P||w||f||M(),!f&&!p){if(o.downArrow&&!w&&!v&&!n&&m&&x.length>0&&m.value===x[x.length-1]?.value&&E(!0),o.upArrow&&!w&&!v&&m&&x.length>0&&m.value===x[0]?.value&&(P?b(!0):n||(E(!0),k(x.length-1))),o.upArrow&&w){E(!1),k(x.length-1);const e=x[x.length-1];e&&g(e)}if(o.downArrow&&w)if(E(!1),P)b(!0);else{k(0);const e=x[0];e&&g(e)}if(o.upArrow&&v&&(b(!1),E(!0)),o.downArrow&&v){b(!1),k(0);const e=x[0];e&&g(e)}o.return&&v&&P&&M()}if(p||w||v||(f?o.leftArrow&&L(e.length-1):o.leftArrow&&r>0?_(r-1):o.rightArrow&&(r<e.length-1?_(r+1):(P&&(d.size>0?i.current.set(r,Array.from(d)):i.current.delete(r),a(new Map(i.current))),y(!0)))),o.escape&&!p)if(f)y(!1);else if(w){E(!1);const e=S??x.length-1;k(e);const t=x[e];t&&g(t)}else if(v){b(!1);const e=x[x.length-1];e&&g(e)}}),C||f?f?B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(td,{questions:e,currentIndex:e.length,answeredQuestions:new Set(s.keys()),isReviewPage:!0})),e.map((e,t)=>B.createElement(V,{key:t,marginBottom:1,flexDirection:"column"},B.createElement(K,{dimColor:!0},t+1,". ",e.question),B.createElement(K,{color:"green"}," ",s.get(t)?.join(", ")||"No answer"))),B.createElement(He,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:$,initialIndex:0,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"cyan"},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(K,{color:t?"cyan":"white"},e)}),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},ke.arrowLeft," to go back and edit"))):B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(td,{questions:e,currentIndex:r,answeredQuestions:new Set(s.keys()),isReviewPage:!1,hideReview:n})),B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0},C.question)),w||v?B.createElement(V,{flexDirection:"column"},x.map((e,t)=>{const n=I.get(e.label),r=P&&n&&d.has(n.label),o=!P&&n&&T?.includes(n.label),s=r||o;return B.createElement(V,{key:t,flexDirection:"column"},B.createElement(V,null,B.createElement(K,null," "),B.createElement(K,{color:s?"green":"white"}," ",t+1,"."," "),P&&(s?B.createElement(K,{color:"green"},"[",ke.tick,"]"," "):B.createElement(K,{dimColor:!0},"[ ] ")),B.createElement(K,{color:s?"green":"white"},n?.label||""),!P&&s&&B.createElement(K,{color:"green"}," ",ke.tick)),n?.description&&B.createElement(V,null,B.createElement(K,null," "),B.createElement(K,{dimColor:!0},P?" ":" ",n.description)))})):B.createElement(He,{key:`${r}-${S??"default"}`,items:x,initialIndex:S??R(),onSelect:D,onHighlight:g,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"cyan"},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=I.get(e),r=P&&n&&d.has(n.label),o=!P&&n&&T?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",c=a?.[2]||e;return B.createElement(V,{flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:t?"cyan":s?"green":"white"}," ",i,"."," "),P&&(s?B.createElement(K,{color:"green"},"[",ke.tick,"]"," "):B.createElement(K,{dimColor:!0},"[ ] ")),B.createElement(K,{color:t?"cyan":s?"green":"white"},c),!P&&s&&B.createElement(K,{color:"green"}," ",ke.tick)),n?.description&&B.createElement(K,{dimColor:!0},P?" ":" ",n.description))}}),!n&&B.createElement(V,null,B.createElement(K,{color:"cyan"},w?ke.pointer:" "),B.createElement(K,{color:w?"cyan":void 0}," ",x.length+1,"."," "),P&&(d.has(c.trim())?B.createElement(K,{color:"green"},"[",ke.tick,"] "):B.createElement(K,{dimColor:!0},"[ ] ")),B.createElement(Ze,{value:c,onChange:e=>{const t=c.trim();l(e),P&&u(n=>{const r=new Set(n);return t&&r.has(t)&&r.delete(t),e.trim()&&r.add(e.trim()),r})},onSubmit:N,placeholder:"Type something...",focus:w})),P&&B.createElement(V,null,B.createElement(K,{color:"cyan"},v?ke.pointer:" "),B.createElement(K,{color:v?"cyan":void 0,bold:v}," ",r===e.length-1?"Submit":"Next")),e.length>1&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function LiveAgentStatusInner({entry:e}){const t=Ms(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,a=e.metadata?.elapsedSeconds||0,i=e.metadata?.recentTools||[],[c,l]=z(".");return H(()=>{const e=setInterval(()=>{l(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),B.createElement(V,{flexDirection:"column",marginBottom:1,width:"90%"},B.createElement(V,null,B.createElement(K,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${t} `),o&&B.createElement(K,null," ","(",o,")")),B.createElement(V,{columnGap:1,marginLeft:1},B.createElement(K,null,"⎿"," "),B.createElement(K,{color:"gray"},"Running (",formatTime2(a)," | ",formatTokens(s),")",c)),i.length>0&&B.createElement(V,{flexDirection:"column",marginLeft:1},i.map((e,t)=>{const n=Ms(e.name);return B.createElement(V,{key:t,columnGap:1},B.createElement(K,{color:"gray"},"⎿"),B.createElement(K,{color:"gray"}," ",n),e.input&&B.createElement(K,{color:"gray"},"(",e.input,")"))})))}function LiveAgentStatus({entry:e}){return"tool"!==e.role?null:B.createElement(LiveAgentStatusInner,{entry:e})}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:Vo,capabilities:{},clientInfo:Ko}})});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}At(),$n(),__name(LiveAgentStatusInner,"LiveAgentStatusInner"),__name(LiveAgentStatus,"LiveAgentStatus"),At(),At(),At(),or(),Cr(),At(),ir(),Cn(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient");var rd=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(!0),[s,a]=z(0),[i,c]=z("list"),[l,d]=z(null);H(()=>{u()},[]);const u=__name(async()=>{o(!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,o,s="disconnected";return n&&"connected"===n.status?(s="connected",r=n.tools.length):n&&"error"===n.status?(s="error",o=n.error):e.config.oauth&&(s=await hasTokens(e.name)?"authenticated":"requires_auth"),{name:e.name,config:e.config,scope:e.scope,status:s,toolCount:r,error:o}}));n(r)}catch{}finally{o(!1)}},"loadServers"),m=q(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),g=m[s]??null;Z((t,n)=>{n.ctrl&&"c"===t?e():n.escape?"actions"===i||"confirm-remove"===i?(c("list"),d(null)):e():"list"===i&&(n.upArrow&&(a(e=>Math.max(0,e-1)),d(null)),n.downArrow&&(a(e=>Math.min(m.length-1,e+1)),d(null)),n.return&&g&&(c("actions"),d(null)))});const p=__name(e=>{switch(e){case"connected":return B.createElement(K,{color:"green"},"✓");case"authenticated":return B.createElement(K,{color:"cyan"},"✓");case"requires_auth":return B.createElement(K,{color:"yellow"},"⚠");case"error":return B.createElement(K,{color:"red"},"✗");default:return B.createElement(K,{color:"gray"},"○")}},"getStatusIcon"),h=__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"),f=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),y=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),w=__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||c("confirm-remove");else{if(!g.config.oauth)return void d({text:"No OAuth configured for this server",color:"yellow"});d({text:`Authenticating ${g.name}...`,color:"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:`✓ Authenticated with ${g.name}`,color:"green"});try{const e=getMcpConnectionManager();await e.reconnectServer(g.name)}catch{}await u()}else d({text:`✗ Auth failed: ${t.error}`,color:"red"})}catch(e){d({text:`✗ Failed: ${e instanceof Error?e.message:String(e)}`,color:"red"})}}else{d({text:`Connecting ${g.name}...`,color:"cyan",loading:!0});try{const e=getMcpConnectionManager();await e.reconnectServer(g.name),d({text:`✓ Connected to ${g.name}`,color:"green"}),await u()}catch(e){d({text:`✗ Failed: ${e instanceof Error?e.message:String(e)}`,color:"red"})}}else d({text:"Already authenticated",color:"green"});else d({text:"Already connected",color:"green"});else c("list")},"handleActionSelect"),E=__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}),c("list"),await u(),a(e=>Math.min(e,Math.max(0,m.length-2)))}catch(e){d({text:`✗ Failed: ${e instanceof Error?e.message:String(e)}`,color:"red"}),c("actions")}else c("actions")},"handleRemoveConfirm");if(r)return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"#E4CCFF",bold:!0},"Manage MCP servers"),B.createElement(K,{dimColor:!0},"Loading..."));if("confirm-remove"===i&&g)return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"red",bold:!0},"Remove ",g.name,"?"),B.createElement(K,{dimColor:!0},"This will remove the server from ",g.scope," config."),B.createElement(V,{marginTop:1},B.createElement(He,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:E,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"}," ",t)})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===i&&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(V,{flexDirection:"column"},B.createElement(K,{color:"#E4CCFF",bold:!0},g.name),B.createElement(V,null,p(g.status),B.createElement(K,{dimColor:!0}," ",h(g))),B.createElement(V,{marginTop:1},B.createElement(He,{items:e,onSelect:w,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"}," ",t)})),l&&B.createElement(V,{marginTop:1},l.loading&&B.createElement(K,{color:l.color},B.createElement(De,{type:"dots"})," "),B.createElement(K,{color:l.color},l.text)),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to go back")))}let S=null;return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"#E4CCFF",bold:!0},"Manage MCP servers"),B.createElement(K,{dimColor:!0},t.length," ",1===t.length?"server":"servers"),0===t.length?B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,{dimColor:!0},"No MCP servers configured."),B.createElement(K,{dimColor:!0},'Use "cmd mcp add" to add a server.'),B.createElement(K,{dimColor:!0},"Docs: https://commandcode.ai/docs/mcp")):B.createElement(V,{marginTop:1,flexDirection:"column"},m.map((e,t)=>{const n=e.scope!==S;S=e.scope;const r=t===s;return B.createElement(B.Fragment,{key:e.name},n&&B.createElement(V,{marginTop:0===t?0:1},B.createElement(K,{bold:!0},f(e.scope)),B.createElement(K,{dimColor:!0}," (",y(e.scope),")")),B.createElement(V,{paddingLeft:1},B.createElement(K,{color:r?"white":"gray"},r?"› ":" "),B.createElement(K,{color:r?"white":void 0,bold:r},e.name),B.createElement(K,{dimColor:!0}," · "),p(e.status),B.createElement(K,{color:"connected"===e.status?"green":"authenticated"===e.status?"cyan":"requires_auth"===e.status?"yellow":"gray"}," ",h(e))))})),l&&B.createElement(V,{marginTop:1},l.loading&&B.createElement(K,{color:l.color},B.createElement(De,{type:"dots"})," "),B.createElement(K,{color:l.color},l.text)),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Cn();var{setText:od}=Ne,{runIDESetup:sd}=await Promise.resolve().then(()=>(Ar(),Tr));function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}__name(createKillShellPermissionRequest,"createKillShellPermissionRequest");var ad=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:o,updateFailedInfo:s,initialPrompt:a,skipOnboarding:i=!1,initialPermissionMode:c})=>{const{exit:l}=X(),[d,u]=z(""),[m,g]=z("Ready..."),p=W(!1),[h,f]=z(null),[y,w]=z(o);H(()=>{if(y){const e=setTimeout(()=>{w(null)},3e4);return()=>clearTimeout(e)}},[y]);const{stdout:E}=Q(),[S,k]=z(!1),[v,b]=z(!1),[C,P]=z(!1),[T,A]=z(!1),[x,I]=z(!1),[$,R]=z(!1),[D,M]=z(!1),[N,O]=z(!1),[F,L]=z(!1),[_,U]=z(null),[j,q]=z(null),[J,Y]=z(getConfiguredModel()),[ee,te]=z(!1),[ne,re]=z(!1),[se,ae]=z(!1),ie=W(null),ce=W(null),[le,de]=z(0),[ue,me]=z(!1),{executeBash:ge,executionState:pe}=ei(),[he,fe]=z(""),[ye,we]=z([]),[Ee,Se]=z([]),[ke,ve]=z(!1),[be,Ce]=z([]),[Pe,Te]=z(crypto.randomUUID()),[Ae,xe]=z(!1),[Ie,$e]=z(!1),[Re,De]=z(!1),Me=W(null),[Ne,Oe]=z(!1),[Fe,Le]=z(!1),[_e,Ue]=z(!0),[je,Be]=z(!1),[ze,We]=z(!1),[He,Ge]=z(null),[qe,Ve]=z(!1),Ke=W(!1),[Je,Ye]=z(!1),[Qe,Ze]=z(0),[Xe,et]=z(null),[tt,nt]=z(null),[rt,ot]=z(null),st=W(!1),at=W(!1),it=W(rt);H(()=>{it.current=rt},[rt]);const[ct,lt]=z(!1),[dt,ut]=z(""),[mt,gt]=z(!1),[pt,ft]=z(()=>c||(r?"auto-accept":"standard")),yt=W(pt);H(()=>{yt.current=pt},[pt]);const[wt,Et]=z(""),vt=W(null),bt=W(null),Ct=__name(()=>{vt.current&&clearTimeout(vt.current),bt.current&&clearTimeout(bt.current),ie.current&&clearTimeout(ie.current),ce.current&&clearTimeout(ce.current)},"cleanupTimers"),[Pt,Tt]=z(!1),[At,xt]=z(!1),$t=W(null),Rt=W(0),[Dt,Mt]=z(null),Nt=G(()=>{$t.current=null,Mt(null),bt.current&&(clearTimeout(bt.current),bt.current=null)},[]);H(()=>{if(Je){Ct();try{l()}catch{process.exit(0)}}},[Je,l]);const Ot=G(()=>{We(!0),Be(!1),Ve(!1),ri(),de(e=>e+1),e&&xe(!0)},[e,t]),Ft=__name(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(e=>{dlog("[MCP] Failed to initialize",e)})},"initializeMcpInBackground"),Lt=__name(async()=>{try{const e=await isTasteLearningEnabled();gt(e),e&&await xi.initializeProject()}catch(e){}},"loadTasteStatus"),_t=__name(async()=>{const e=await getConfiguredProvider();q(e);const t=await isOAuthEnforced();te(t)},"loadCurrentProvider"),Ut=W([]),jt=W(null),zt=W(null),[Wt,Ht]=z(null),[Gt,qt]=z(null),{requestShellPermission:Vt,service:Kt,respondToPrompt:Jt,clearSessionPermissions:Yt,setEnabled:Qt}=ni({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{Ht({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),jt.current&&g("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Ht({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),jt.current&&g("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?g("Permission granted"):g("Permission denied")},"onPermissionResponse")}),Zt=__name(e=>{vt.current&&clearTimeout(vt.current),Et(e),vt.current=setTimeout(()=>{Et(""),vt.current=null},5e3)},"showHintMessage");H(()=>()=>Ct(),[]),H(()=>{Kt&&applyAutoAcceptMode({enabled:pt,service:Kt})},[pt,Kt]),H(()=>{(async()=>{if(await Pa.isProjectInitialized())if(Le(!0),Ue(!1),Lt(),_t(),Ft(),t){const e=await Pa.listSessions();if(e.length>0){const t=e[0];Tn(t.id)}}else e&&xe(!0);else if(n)if(await Pa.initializeProject(),Le(!0),Ue(!1),Lt(),_t(),Ft(),t){const e=await Pa.listSessions();if(e.length>0){const t=e[0];Tn(t.id)}}else e&&xe(!0);else isDirectoryEmpty()?(await Pa.initializeProject(),Le(!0),Ue(!1),Lt(),_t(),Ft()):(Oe(!0),Ue(!1))})()},[e,t,n,l]),H(()=>{i||triggerTasteOnboarding({projectTrusted:Fe,onboardingComplete:ze,isOnboardingMode:je,tasteOnboardingCheckedRef:Ke,setIsOnboardingMode:Be})},[Fe,ze,je,i]),H(()=>{if(je&&!He){const e=bs();Ge(e.id),we(t=>[...t,e])}else!je&&He&&(we(e=>e.filter(e=>e.id!==He)),Ge(null))},[je,He]),H(()=>{Ut.current=be},[be]);const Xt=G(e=>({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?Se(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(Se(t=>t.filter(t=>t.id!==e.id)),we(t=>[...t,e])):we(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Ut.current];return Ut.current=[],Ce([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ze(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{et(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{f(e)},"onRetryUpdate"),onProviderChange:__name(e=>{q(e)},"onProviderChange"),onStatusUpdate:__name(e=>{p.current=!0,g(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{if("shell_command"===e&&Kt){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",r={command:t.command||"",args:t.args,workingDirectory:t.directory,description:n||`Execute shell command: ${t.command} ${e}`};return Kt.requestShellPermission(r).then(e=>e.allowed)}if("kill_shell"===e&&Kt){const e=createKillShellPermissionRequest(t);return Kt.requestShellPermission(e).then(e=>e.allowed)}if(Kt){const n={action:e.includes("edit")?"edit":e.includes("write")?"create":e.includes("delete")?"delete":"edit",filePath:t.filePath||t.file_path||t.path||t.absolutePath||"unknown",description:t.description||`${e} operation`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return Kt.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{qt({params:e,resolve:t,reject:n}),g("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const t=it.current;return t?{sessionId:e||Pe,secret:t.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>yt.current,"getPermissionMode")}),[pt,Pe,Kt]);H(()=>{(async()=>{if(j&&"anthropic"===j&&ee)try{await Bt.getValidAccessToken()||g("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){g("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[j,ee]),H(()=>{if(!ke)return void(p.current=!1);if(null!==h)return;const e=setInterval(()=>{p.current||g(Ds())},7e3);return()=>clearInterval(e)},[ke,h]);const en=G(()=>{const e=!ke&&!Wt&&!Gt,t=jt.current?.hasCheckpoints()??!1;e&&t&&Tt(!0)},[ke,Wt]),tn=G(()=>{if(!jt.current)return;jt.current.interrupt(!0);const e=Ee.length>0;if(ve(!1),f(null),Se([]),g("Interrupted by user"),!e){const e=vs("Interrupted by user");we(t=>[...t,e])}if(Ut.current.length>0){const e=Ut.current.join("\n");u(t=>t?e+"\n"+t:e),Ce([]),Ut.current=[]}},[Ee]),nn=__name(()=>{ft(e=>{let t;return t="standard"===e?"auto-accept":"auto-accept"===e?"plan":"standard","auto-accept"===t&&Wt&&(Jt({label:"Yes",value:"yes",description:"Allow this action",scope:void 0}),Wt.resolve(!0),Ht(null)),"plan"===t&&Wt&&(Wt.resolve(!1),Ht(null)),t}),ri(),de(e=>e+1)},"handleToggleAutoAccept");async function getBillingLink(){if(tt)return tt;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return nt(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return nt(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}Z((e,t)=>{if(t.shift&&t.tab||"[Z"===e)nn();else if(C||T||x||$||D||N||_||F||Pt||At||Ie)Dt&&Nt();else{if(""===e||t.ctrl&&"c"===e){if(ke&&jt.current)return void tn();const e=Date.now(),t=e-Rt.current;return Rt.current=e,void("ctrl-c"===$t.current&&t<2e3?(bt.current&&(clearTimeout(bt.current),bt.current=null),Ye(!0)):(u(""),$t.current="ctrl-c",Mt("ctrl-c"),bt.current&&clearTimeout(bt.current),bt.current=setTimeout(()=>{$t.current=null,Mt(null),bt.current=null},2e3)))}if(t.ctrl&&"t"===e)return ri(),L(e=>!e),void de(e=>e+1);if(getIsExpandToolShortcut(t,e))return ri(),me(e=>!e),void de(e=>e+1);if(t.meta&&"p"===e||isAltP(e))R(!0);else{if(t.escape){if(Gt)return Gt.reject(new Error("Question cancelled by user")),qt(null),void g("Question cancelled");Wt?(Jt({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),Wt.resolve(!1),Ht(null),g("Permission denied")):ke&&jt.current&&tn()}t.meta||t.ctrl}}}),H(()=>{const e=__name(()=>{ri(),de(e=>e+1)},"handleResize");if(E)return E.on("resize",e),()=>{E.off("resize",e)}},[E]),H(()=>{jt.current||!Fe||Ae||Re||(jt.current=new Ja(Xt(),Pe),(async()=>{await pn()})())},[Pe,Ae,Re,Fe]),H(()=>{if(!Fe)return;const e=createHistoryManager();return Me.current=e,e.init(),()=>{e.cleanup()}},[Fe]),H(()=>{a&&Fe&&!_e&&jt.current&&!Ae&&!at.current&&(at.current=!0,rn({role:"user",input:a}))},[a,Fe,_e,Ae]),__name(getBillingLink,"getBillingLink");const rn=__name(async({role:e,input:t,images:n,ideContext:r})=>{if(t.length)if(y&&w(null),Ze(0),"bash"===e){if(st.current)return;st.current=!0;const e=Ss(t);we([...ye,e]),u(""),await ge(t,e=>{we(e)},()=>{ri(),de(e=>e+1)}),st.current=!1}else{if(ke)return Ce(e=>[...e,t]),void u("");if(st.current)return;st.current=!0,ve(!0),g(Ds()),u("");try{jt.current&&await jt.current.sendMessage(t,n,r)}catch(e){if("Interrupted by user"===e?.message||e?.message?.toLowerCase().includes("interrupt")||e?.message?.toLowerCase().includes("abort")||"InterruptedError"===e?.name||"AbortError"===e?.name||"ECONNABORTED"===e?.code);else if("Insufficient credits"===e.message){g("Insufficient credits");const e=await getBillingLink(),t=vs(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);we(e=>[...e,t])}else if(e.message.startsWith("Error:")){g("Error");const t=vs(e.message);we(e=>[...e,t])}else{g("Error");const t=e.message||"An unexpected error occurred",n=vs(t);we(e=>[...e,n])}}finally{ve(!1),"Interrupted by user"!==m&&"Permission denied"!==m&&"Insufficient credits"!==m&&g("Ready..."),st.current=!1}}},"handleSubmit"),on=__name(()=>{we(e=>[...e,ks("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),sn=__name(()=>{const e=fs(`/${St.TERMINAL_SETUP}`),t=setupVSCodeTerminal(),n=Cs(t.message,!t.success,t.details);we(t=>[...t,e,n])},"handleTerminalSetupCommand"),an=__name(async()=>{const e=await sd(),t=Ps(e.status,e.ide,e.details);we(e=>[...e,t])},"handleIDESetupCommand"),cn=__name(async()=>{if(we([]),Se([]),ri(),ot(null),lt(!1),ut(""),jt.current){const e=jt.current.getSessionManager();e&&await e.deleteShareInfo(),jt.current=null;const t=crypto.randomUUID();Te(t),Yt(),jt.current=new Ja(Xt(t),t)}de(e=>e+1),et(null),Ze(0)},"handleClearCommand"),ln=__name(()=>{jt.current?jt.current.hasCheckpoints()?Tt(!0):we(e=>[...e,ys("No checkpoints available. Start sending messages to create checkpoints.")]):we(e=>[...e,ys("No active conversation to rewind.")])},"handleRewindCommand"),dn=__name(async e=>{const{messageId:t,mode:n}=e;if(Tt(!1),jt.current)try{const e=jt.current.listCheckpoints().find(e=>e.messageId===t);g("Restoring checkpoint...");const r=await jt.current.restoreToCheckpoint({messageId:t,mode:n});if(r.success){const t=jt.current.getSessionManager(),n=jt.current.getMessages(),o=t.reconstructFeedFromMessages(n);we(o),ri(),de(e=>e+1),e&&e.userPrompt&&u(e.userPrompt);const s=[];r.filesRestored>0&&s.push(`${r.filesRestored} file${r.filesRestored>1?"s":""} restored`),r.filesDeleted>0&&s.push(`${r.filesDeleted} file${r.filesDeleted>1?"s":""} deleted`),r.messagesRemoved>0&&s.push(`${r.messagesRemoved} message${r.messagesRemoved>1?"s":""} removed`);const a=s.length>0?`Restored to checkpoint: ${s.join(", ")}.`:"Restored to checkpoint.";we(e=>[...e,ys(a)]),g("Ready...")}else we(e=>[...e,vs(`Failed to restore: ${r.error}`)]),g("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;we(e=>[...e,vs(t)]),g("Ready...")}},"handleRewindSelect"),un=__name(()=>{Tt(!1)},"handleRewindCancel"),mn=__name(async()=>{if(jt.current)if(jt.current.isRequestInProgress())we(e=>[...e,ys("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{ve(!0),g("Compacting conversation...");const e=await jt.current.manualCompact();ri(),de(e=>e+1);let t="Compacted conversation.";e.didCompact||(t="Conversation is already compact."),e.didCompact&&e.tokensSaved>0&&(t=`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`),we(e=>[...e,ys(t)]),ve(!1),g("Ready..."),et({current:jt.current.getContextTokensUsed()||0,limit:Ra})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;we(e=>[...e,vs(t)]),ve(!1),g("Ready...")}else we(e=>[...e,ys("No active conversation to compact.")])},"handleCompactCommand"),gn=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await Tn(t)}const t=parseCommandInput({input:e});if(!t)return;const{commandName:n,rawArguments:r,positionalArgs:o}=t;switch(n){case"/exit":return void Ye(!0);case"/clear":return void await cn();case"/help":return void on();case"/share":return void hn();case"/unshare":return void Cn();case"/taste":return void P(!0);case"/learn-taste":return void await Pn();case"/skills":return void A(!0);case"/provider":return void(isInternalTeamFlagEnforced()?I(!0):g("Provider selection not available"));case"/model":return void R(!0);case"/memory":return void M(!0);case"/init":return void fn();case"/agents":return void b(!0);case"/mcp":return void yn();case"/compact":return void await mn();case"/rewind":return void ln();case"/login":return void await En();case"/logout":return void await vn();case"/feedback":return void await bn();case"/terminal-setup":return void sn();case"/ide":return void await an();case"/add-dir":return void $e(!0)}const s=getCustomCommandContent(n);if(s){const e=processCommandTemplate({template:s,rawArguments:r,positionalArgs:o});await rn({input:e.content,role:"user"})}},"handleCommand"),pn=__name(async()=>{const e=jt.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&ot({url:t.url,secret:t.secret})}},"loadShareInfo"),hn=__name(async()=>{if(Pe){if(rt)return await od(rt.url),g(""),lt(!0),void setTimeout(()=>{lt(!1)},3e3);try{g("Creating share link...");const e=jt.current?.getMessages()||[],t=go.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new Co({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:ht.ALPHA.SHARE.CREATE,body:{sessionId:Pe,messages:t}}),o={url:r.url,secret:r.secret};ot(o);const s=jt.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await od(r.url),g(""),lt(!0),setTimeout(()=>{lt(!1)},5e3)}catch(e){g(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else g("No active session to share")},"handleShareCommand"),fn=__name(async()=>{try{const e=process.cwd(),t=`Created AGENTS.md at ${await initProjectMemory(e)}. You can now edit it with /memory or open it in your editor.`;we(e=>[...e,ys(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;we(e=>[...e,ys(t)])}},"handleInitCommand"),yn=__name(()=>{O(!0)},"handleMcpCommand"),wn=__name(()=>{O(!1)},"handleMcpClose"),En=__name(async()=>{const e=It();if(await getAuthKey(e)){let e="";try{const t=await loadCredentials();e=t?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const t=e&&"API Key"!==e&&"Manual API Key"!==e?` as ${e}`:"";return void we(e=>[...e,ys(`Already logged in${t}`)])}xt(!0)},"handleLoginCommand"),Sn=G((e,t)=>{xt(!1),e?(we(e=>[...e,ys(t)]),jt.current&&jt.current.refreshRequest()):we(e=>[...e,vs(t)]),g("Ready...")},[]),kn=G(()=>{xt(!1),we(e=>[...e,ys("Authentication cancelled.")]),g("Ready...")},[]),vn=__name(async()=>{const e=await performLogout();e.success?(jt.current&&jt.current.refreshRequest(),e.wasAuthenticated?e.warnings.length>0?we(t=>[...t,ys(`Successfully logged out from Command Code. Warnings: ${e.warnings.join(", ")}`)]):we(e=>[...e,ys("Successfully logged out from Command Code.")]):we(e=>[...e,ys("Not currently authenticated.")])):we(t=>[...t,vs(`Logout failed: ${e.error}`)])},"handleLogoutCommand"),bn=__name(async e=>{const t=buildGitHubIssueUrl(e);try{await oe(t,{wait:!1,background:!0}),we(e=>[...e,ys(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`)])}catch(e){we(e=>[...e,vs("Failed to open browser"),ks(createOSC8Link(t,"Open GitHub issue manually"))])}},"handleFeedbackCommand"),Cn=__name(async()=>{if(Pe){if(!rt)return ut("NOT SHARED: Session is not currently shared"),void setTimeout(()=>ut(""),5e3);try{g("Removing share link...");const e=new Co({baseUrl:getApiBaseUrl()});await e.delete({endpoint:ht.ALPHA.SHARE.DELETE,body:{sessionId:Pe,secret:rt.secret}});const t=jt.current?.getSessionManager();t&&await t.deleteShareInfo(),ut("UNSHARED: Sharing has stopped"),g(""),ot(null),setTimeout(()=>{ut("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;g(t),setTimeout(()=>g(""),5e3)}}else g("No active session to unshare")},"handleUnshareCommand"),Pn=__name(async()=>{Ve(!0),Be(!0);const e=bs();Ge(e.id),we(t=>[...t,e])},"handleLearnCommand"),Tn=__name(async e=>{const t=crypto.randomUUID();zt.current=t;try{we([]),Se([]),jt.current=null,ft("standard"),Te(e),xe(!1),De(!0),jt.current=new Ja(Xt(e),e);const{feedEntries:n,corruptedLines:r,totalLines:o}=await jt.current.loadSession(e);if(zt.current!==t)return;await pn();const s=[];if(0===n.length&&o>0?s.push(vs(`Session could not be loaded. ${o} lines could not be parsed.`)):0===n.length?s.push(ys("Session loaded but contains no messages.")):(r>0&&s.push(ys(`Warning: ${r} message(s) could not be loaded.`)),s.push(...n)),zt.current!==t)return;we(s),ri(),de(e=>e+1)}catch(e){if(zt.current!==t)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";we([vs(`Failed to load session: ${n}. Starting fresh session.`)]),xe(!1),De(!1),Te(crypto.randomUUID())}},"handleSelectSession"),An=__name(async()=>{we([]),Se([]),jt.current=null,ft("standard"),Te(crypto.randomUUID()),xe(!1),De(!1)},"handleNewSession"),xn=__name(async()=>{try{await Pa.initializeProject(),Oe(!1),e?(console.log("No conversations found to resume."),Ye(!0)):(Le(!0),Lt(),_t())}catch(e){console.error("Failed to initialize project:",e),Oe(!1),Ye(!0)}},"handleTrust"),In=__name(()=>{Ye(!0)},"handleNoTrust"),$n=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void U({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),q(e),I(!1);const n=getProviderDisplayName(e);g(`Provider set to ${n}`),ie.current&&clearTimeout(ie.current),re(!0),ie.current=setTimeout(()=>{re(!1),ie.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),g("Failed to set provider"),I(!1)}},"handleProviderSelect"),Rn=__name(()=>{I(!1)},"handleProviderCancel"),Dn=__name(e=>{const t=Object.values(kt).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),Mn=__name(async e=>{try{await setSelectedModel({model:e}),Y(e),R(!1);const t=Dn(e);g(`Model set to ${t}`),ce.current&&clearTimeout(ce.current),ae(!0),ce.current=setTimeout(()=>{ae(!1),ce.current=null},5e3)}catch(e){console.error("Failed to set model:",e),g("Failed to set model"),R(!1)}},"handleModelSelect"),Nn=__name(()=>{R(!1)},"handleModelCancel"),On=__name(()=>{if(_){U(null),I(!1),q(_.provider);const e=getProviderDisplayName(_.provider);g(`${e} authentication successful`),ie.current&&clearTimeout(ie.current),re(!0),ie.current=setTimeout(()=>{re(!1),ie.current=null},5e3)}},"handleAuthSuccess"),Fn=__name(()=>{U(null)},"handleAuthCancel");if(Je)return null;if(Ne)return B.createElement(B.Fragment,null,B.createElement(qc,{staticKey:le}),B.createElement(Ml,{onTrust:xn,onExit:In}));if(_e)return null;if(Ae)return B.createElement(Jc,{onSelectSession:Tn,onNewSession:An});if(!Fe)return null;if(Gt)return B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(zc,{staticKey:le,feed:ye,showHeader:!0,expandedToolOutput:ue,currentModel:J}),B.createElement(V,{marginY:1},B.createElement(nd,{questions:Gt.params.questions,hideCustomInput:Gt.params.hideCustomInput,onResponse:e=>{if(Gt.params.exitPlanMode){const t=e.answers[0]?.selectedOptions[0]||"";t.startsWith("Yes, auto-accept")?(ft("auto-accept"),ri(),de(e=>e+1)):t.startsWith("Yes, exit")&&(ft("standard"),ri(),de(e=>e+1))}if(Gt.params.enterPlanMode){const t=e.answers[0]?.selectedOptions[0];t?.startsWith("Yes")&&(ft("plan"),ri(),de(e=>e+1))}Gt.resolve(e),qt(null),g("Answers submitted")}})));if(Wt){if("shell_command"===Wt.toolName){const e=Wt.params;return B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(zc,{staticKey:le,feed:ye,showHeader:!0,expandedToolOutput:ue,currentModel:J}),Ee.map(e=>B.createElement(LiveAgentStatus,{key:e.id,entry:e})),B.createElement(V,{marginY:1},B.createElement(Qc,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;Wt.resolve(t),Ht(null),t?(g("Shell command allowed"),"standard"===pt&&Zt("Use shift+tab to enable auto-accept")):g("Shell command denied")},onToggleAutoAccept:nn})))}if("kill_shell"===Wt.toolName){const e=createKillShellPermissionRequest(Wt.params);return B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(zc,{staticKey:le,feed:ye,showHeader:!0,expandedToolOutput:ue,currentModel:J}),B.createElement(V,{marginY:1},B.createElement(Qc,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;Wt.resolve(t),Ht(null),t?(g("Process termination allowed"),"standard"===pt&&Zt("Use shift+tab to enable auto-accept")):g("Process termination denied")},onToggleAutoAccept:nn})))}{const e={action:Wt.toolName.includes("edit")?"edit":Wt.toolName.includes("write")?"create":Wt.toolName.includes("delete")?"delete":"edit",filePath:Wt.params.filePath||Wt.params.file_path||Wt.params.path||Wt.params.absolutePath||Wt.params.notebook_path||"unknown",description:`Allow ${Wt.toolName} operation`,oldContent:"edit_file"===Wt.toolName?Wt.params.oldContent:void 0,newContent:"edit_file"===Wt.toolName?Wt.params.newContent:void 0};return B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(zc,{staticKey:le,feed:ye,showHeader:!0,expandedToolOutput:ue,currentModel:J}),Ee.map(e=>B.createElement(LiveAgentStatus,{key:e.id,entry:e})),B.createElement(V,{marginY:1},B.createElement(Hc,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;Wt.resolve(t),Ht(null),t?(g("File operation allowed"),"standard"===pt&&Zt("Use shift+tab to enable auto-accept")):g("File operation denied")},onToggleAutoAccept:nn})))}}return F?B.createElement(Pc,{onClose:()=>{L(!1),de(e=>e+1)}}):C?B.createElement(B.Fragment,null,B.createElement(qc,{staticKey:le}),B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Press Esc to return to conversation")),B.createElement(Xc,{onClose:()=>P(!1),onSettingsChange:Lt,staticKey:le}))):T?B.createElement(B.Fragment,null,B.createElement(qc,{staticKey:le}),B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Press Esc to return to conversation")),B.createElement(Zc,{onClose:()=>A(!1),staticKey:le}))):B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(zc,{staticKey:le,feed:ye.filter(e=>"taste-onboarding"!==e.role),showHeader:!0,expandedToolOutput:ue,currentModel:J}),He&&B.createElement(Dl,{onComplete:Ot,autoLearn:qe}),Ee.map(e=>B.createElement(LiveAgentStatus,{key:e.id,entry:e})),B.createElement(RetryMessage,{attempt:h}),!x&&!$&&!_&&!D&&!N&&!v&&!Pt&&!At&&!Ie&&!He&&B.createElement(Cc,{queuedMessages:be,isProcessing:ke,executionState:pe,status:m,input:d,setInput:u,onSubmit:rn,showFileList:S,setShowFileList:k,fileSearchQuery:he,setFileSearchQuery:fe,onCommand:gn,outputTokens:Qe,contextUsage:Xe,tasteLearning:mt,shareInfo:rt,showShareNotification:ct,unshareNotificationMessage:dt,updateStatus:y,updateFailedInfo:s,currentProvider:j,showProviderInfo:ne,permissionMode:pt,onToggleAutoAccept:nn,hintMessage:wt,historyManager:Me.current,pendingExitKey:Dt,onResetPendingExitKey:Nt,onDoubleEscapeEmpty:en,retryAttempt:h,onAltP:()=>R(!0)}),x&&B.createElement(V,{marginY:1},B.createElement(Gc,{onSelect:$n,onCancel:Rn,currentProvider:j})),$&&B.createElement(V,{marginY:1},B.createElement(Wc,{onSelect:Mn,onCancel:Nn,currentModel:J})),v&&B.createElement(V,{marginY:1},B.createElement(qi,{onCancel:()=>b(!1)})),D&&B.createElement(V,{marginY:1},B.createElement(Tc,{onClose:()=>M(!1)})),N&&B.createElement(V,{marginY:1},B.createElement(rd,{onClose:wn})),Pt&&jt.current&&B.createElement(V,{marginY:1},B.createElement(Kc,{checkpoints:jt.current.listCheckpoints(),onSelect:dn,onCancel:un})),_&&B.createElement(V,{marginY:1},B.createElement(_.Component,{onSuccess:On,onCancel:Fn})),At&&B.createElement(V,{marginY:1},B.createElement(Nl,{onComplete:Sn,onCancel:kn})),Ie&&B.createElement(V,{marginY:1},B.createElement(Yc,{onClose:()=>{$e(!1)}})))},"InteractiveCLI");vn(),un();var id=__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"),cd=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),ld=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),dd=__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"),ud=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),md=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),gd=__name(()=>{md()},"initializeTerminal"),pd=__name(async(e={})=>{const t=id(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),gd(),cd(e)){const e=await Pa.isProjectInitialized(),t=e?await Pa.listSessions():[],n=ld({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=dd({options:e}),r=ud();Y(B.createElement(ad,{...n}),r)},"interactiveMode");At(),Rt(),qt(),An(),$n(),Wt();var hd=null,fd=!1,yd=new Set([$o,Ro,Oo]);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(fd)return;fd=!0;const e=__name(e=>{hd?.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(),hd=new AbortController;let t=e.query||"";if(!t){process.stdin.isTTY&&(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1));try{t=await readStdin()}catch(e){const t=e instanceof Error?e.message:"Unknown error";process.stderr.write(`Error reading from stdin: ${t}\n`),process.exit(1)}}t.trim()||(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1)),await isAuthenticated()||(process.stderr.write('Error: Not authenticated. Please run "cmd login" first.\n'),process.exit(3)),e.dangerouslySkipPermissions&&process.stderr.write("Warning: Running with --dangerously-skip-permissions. File writes and shell commands will execute without prompts.\n");try{const n=await processQuery({query:t,signal:hd.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 yo&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof wo&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof vo&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof ho&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof bo&&(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 wd=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===wt.ANTHROPIC&&(r=await Bt.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o=getEnvironmentContext(),s=await getMemoryContent([]),a=await getTasteContent(),i=generateSkillsXML(await loadAllSkillSummaries())||null,c=crypto.randomUUID(),l=await isTasteLearningEnabled(),d={[pt.PROJECT_SLUG]:Pa.getCurrentProjectDirName(),[pt.TASTE_LEARNING]:l.toString(),[pt.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(d[pt.OAUTH_TOKEN]=`Bearer ${r}`),{tools:e,config:o,memory:s,taste:a,skills:i,headers:d,sessionId:c}}async function callApi(e,t,n,r){const o={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:`anthropic:${getConfiguredModel()}`},s={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:o,threadId:t.sessionId},a=await e.post({body:s,stream:!0,endpoint:ht.ALPHA.GENERATE,headers:t.headers,signal:r});return Be.fromReadableStream(a).finalMessage()}async function executeToolCall(e,t,n){if(yd.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 yo||t instanceof wo||t instanceof vo||t instanceof ho||t instanceof bo)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1}=e,o=getApiBaseUrl(),s=new Co({baseUrl:o}),a=[{role:"user",content:t}],i=await setupConversationContext();let c=0,l="";for(;c<wd;){if(c++,n.aborted)throw new Error("Cancelled");const e=await callApi(s,i,a,n),t=e.content.filter(e=>"text"===e.type),o=e.content.filter(e=>"tool_use"===e.type),d=t.map(e=>e.text).join("");if(d&&(l+=d),0===o.length)break;const u=[];for(const e of o){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);u.push(t)}a.push({role:"assistant",content:e.content}),a.push({role:"user",content:u})}return c>=wd&&process.stderr.write(`Warning: Reached maximum conversation turns (${wd}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),l}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery"),Ft();var Ed=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),Sd=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),kd=__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"),vd=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),bd=__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=bd(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=Ed(e);await Sd();const r=kd(t),o=vd({options:t,runtimeOptions:r,initialPrompt:n});pd(o)}__name(interactiveModeAction,"interactiveModeAction"),At(),Cn(),Ar(),globalThis.COMMAND_CODE_CWD=process.cwd();var Cd=__name(()=>process.cwd(),"getCwd"),Pd=__name(()=>process.argv.slice(2),"getArgs"),Td=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),Ad=__name(()=>{const e=Cd(),t=Pd(),n=Td(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`)},"logStartupInfo");async function preRun(){Ad(),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"),At(),Rt(),Cn(),jn(),In();var xd=getPackageJson(),Id=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=xd.version,t=getInvokedCommandName(),n=Fc.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ee.bold("Command Code")+ee.gray(` v${e}`)),console.log(ee.gray(Dc)),console.log(),console.log(ee.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ee.bold("Options"));for(const e of Oc){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Mc)+ee.gray(e.description))}console.log(),console.log(ee.bold("Commands"));for(const e of Lc){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Mc)+ee.gray(e.description))}console.log(),console.log(ee.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Mc)+ee.gray(e.description));console.log(),console.log(ee.bold("Keyboard Shortcuts"));for(const e of Nc)console.log(" "+e.key.padEnd(Mc)+ee.gray(e.description));console.log(),console.log(ee.bold("Examples"));for(const e of Uc){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Mc)+ee.gray(e.description))}console.log(),console.log(ee.cyan("❯")+" "+ee.gray(jc.replace(/cmd/,t))),console.log(),console.log(ee.bold("Links"));for(const e of _c)console.log(" "+e.key.padEnd(Mc)+ee.cyan(e.description));console.log()}function createProgram(){const e=new be;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(xd.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 Ce("--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",Id,[]).addOption(new Ce(mt).hideHelp()).addOption(new Ce(gt).hideHelp()).addOption(new Ce("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ce("--local","Use local server").hideHelp()).addOption(new Ce("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(`[cmd] ${r&&r!==n?"subcommand":"running"}: ${n}`);const o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const a=t.args;a.length>0&&dlog(`[cmd] arguments: ${a.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),At(),nr();var $d=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=p.platform(),n=p.arch();let r,o,s,a;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,o=e.user?.id,s=e.org?.login,a=e.org?.id)}catch{}if(!o)try{const e=await loadCredentials();o=e?.userId}catch{}systemInfo({userName:r,userId:o,orgLogin:s,orgId:a,nodeVersion:e,platform:t,arch:n})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){$d||($d=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Me("Opening GitHub issues...").start();try{await oe(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"),At(),__name(openGitHubIssue,"openGitHubIssue");var Rd=new be("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);At();var Dd=new be("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});At();var Md=new be("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{const{waitUntilExit:t}=Y(B.createElement(Gl,{verbose:e.verbose,text:e.text}));await t()});At(),Rt(),Cn(),nr();var Nd=new be(St.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{const{unmount:e}=Y(B.createElement($l,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:Yn.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 be("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 Ce("-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().action(async(e,t,n,r)=>{const o=getInvokedCommandName();try{let s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ee.red(`Error: Invalid server name '${e}'`)),console.error(ee.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(ee.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ee.gray("Valid options: stdio, http")),process.exit(1));let a=!1;if("http"===n.transport){t||(console.error(ee.red("Error: URL is required for http transport")),console.error(ee.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ee.red(`Error: Invalid URL '${t}'`)),process.exit(1)}s={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(ee.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ee.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ee.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(ee.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${sr}/callback`]});e&&(n=e.clientId,t=e.clientSecret)}s.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},console.log(ee.gray("A browser window will open for authentication.\n"));const o=await performOAuthFlow(e,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(ee.gray(` ${e}`))},"onStatus")});o.success?console.log(ee.green("✓ Successfully authenticated")):(a=!0,console.log(ee.yellow(`Warning: Authentication failed: ${o.error}`)),console.log(ee.gray("You can retry with: cmd mcp auth "+e)),console.log(ee.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,a=process.argv.indexOf("--");let i,c=[];if(-1!==a){const e=process.argv.slice(a+1);0===e.length&&(console.error(ee.red("Error: Command is required for stdio transport")),console.error(ee.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),i=e[0],c=e.slice(1)}else if(t){i=t;const n=o.indexOf(e);-1!==n&&o.length>n+2&&(c=o.slice(n+2))}else console.error(ee.red("Error: Command is required for stdio transport")),console.error(ee.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ee.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);s={transport:"stdio",enabled:!0,command:i,...c.length>0&&{args:c},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:s,scope:n.scope});const i="user"===n.scope?"global":"project"===n.scope?"project":"local";if(a?console.log(ee.yellow(`✓ Added MCP server '${e}' to ${i} config (authentication pending)`)):console.log(ee.green(`✓ Added MCP server '${e}' to ${i} config`)),"http"===s.transport)console.log(ee.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(ee.gray(` Command: ${e}`))}console.log(""),console.log(ee.cyan("Next steps:")),console.log(ee.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ee.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(ee.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(ee.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),o=e.substring(n+1).trim();return r||(console.error(ee.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new be("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ee.yellow("\nNo MCP servers configured\n")),console.log(ee.gray("Add a server with:")),console.log(ee.gray(" cmd mcp add --transport http <name> <url>")),console.log(ee.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ee.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ee.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ee.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?ee.green("enabled"):ee.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?ee.green("✓"):ee.red("✗"):o.config.headers||o.config.env?ee.green("✓"):ee.gray("-"),console.log(` ${ee.white(o.name.padEnd(t))} ${ee.cyan(o.config.transport.padEnd(n))} ${ee.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ee.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new be("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(ee.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ee.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ee.dim("Scope:")} ${r}`),console.log(` ${ee.dim("Transport:")} ${n.transport}`),console.log(` ${ee.dim("Status:")} ${n.enabled?ee.green("enabled"):ee.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ee.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ee.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(` ${ee.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ee.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ee.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(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new be("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ce("-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(ee.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ee.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ee.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(ee.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new be("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 Ce("-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 o,s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ee.red(`Error: Invalid server name '${e}'`)),console.error(ee.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{o=JSON.parse(t)}catch{console.error(ee.red("Error: Invalid JSON")),console.error(ee.gray("Make sure to quote the JSON string properly")),console.error(ee.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}o&&"object"==typeof o&&"type"in o&&!("transport"in o)&&(o.transport=o.type,delete o.type),o?.oauth?.callbackPort&&(s=o.oauth.callbackPort,delete o.oauth.callbackPort),n.clientSecret&&o?.oauth&&(o.oauth.clientSecret=n.clientSecret);const a=Yo.safeParse(o);if(!a.success){console.error(ee.red("Error: Invalid server configuration"));for(const e of a.error.issues)console.error(ee.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const i=a.data;let c=!1;if("http"!==i.transport||i.url||(console.error(ee.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==i.transport||i.command||(console.error(ee.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:i,scope:n.scope}),i.oauth){console.log(ee.cyan("Starting OAuth authentication...")),console.log(ee.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:i.oauth.authorizationUrl,tokenUrl:i.oauth.tokenUrl,clientId:i.oauth.clientId,clientSecret:i.oauth.clientSecret,scopes:i.oauth.scopes},n=await performOAuthFlow(e,t,{...s&&{port:s},onStatus:__name(e=>{console.log(ee.gray(` ${e}`))},"onStatus")});n.success?console.log(ee.green(`\n✓ Successfully authenticated with '${e}'`)):(c=!0,console.error(ee.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ee.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ee.gray("Or authenticate via the /mcp menu in a session")))}const l="user"===n.scope?"global":"project"===n.scope?"project":"local";if(c?console.log(ee.yellow(`✓ Added MCP server '${e}' to ${l} config (authentication pending)`)):console.log(ee.green(`✓ Added MCP server '${e}' to ${l} config`)),"http"===i.transport)console.log(ee.gray(` URL: ${i.url}`));else{const e=[i.command,...i.args||[]].join(" ");console.log(ee.gray(` Command: ${e}`))}console.log(""),console.log(ee.cyan("Next steps:")),console.log(ee.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new be("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(ee.yellow("No servers with stored authentication."));console.log(ee.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ee.yellow("expired"):ee.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ee.red("Error: Server name is required")),console.error(ee.gray(`Usage: ${n} mcp auth <server>`)),console.error(ee.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ee.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ee.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ee.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ee.gray(" A refresh token is available for re-authentication"));else{if(console.log(ee.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ee.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ee.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ee.green(`✓ Cleared authentication for '${e}'`)):console.log(ee.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ee.red(`Error: MCP server '${e}' not found`)),console.error(ee.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(ee.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(ee.gray(`Add OAuth config using "${n} mcp add-json" with oauth field`)),process.exit(1));const o={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(ee.cyan(`Authenticating with '${e}'...`)),console.log(ee.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,o,{onStatus:__name(e=>{console.log(ee.gray(` ${e}`))},"onStatus")});if(s.success)return console.log(ee.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ee.gray("Restart the session to connect with the authenticated server."));console.error(ee.red(`\nError: Authentication failed: ${s.error}`)),console.log(ee.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new be("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(p.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")}At(),At(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),At(),__name(listMcpCommand,"listMcpCommand"),At(),__name(getMcpCommand,"getMcpCommand"),At(),__name(removeMcpCommand,"removeMcpCommand"),At(),__name(addJsonMcpCommand,"addJsonMcpCommand"),At(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),At(),Rt(),At(),At(),At(),Rt(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),At(),At();var Od=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||Od.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:Od.test(o)&&!o.startsWith("#")&&!o.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:o}=findLookaheadEnd(e,t),s=o?r+1:r;return{combined:[n,...e.slice(t,s).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:s}}function processRawLine(e,t){const n=e[t],r=t+1,o=n.trim();if(!o.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(Od.test(o))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:s,nextIdx:a}=joinMultiLineLearning(e,t+1,n);return{entry:{text:s,originalLineNum:r},nextIdx:a}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:o}=processRawLine(e,n);t.push(r),n=o}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!Od.test(o))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),a=s.length>0?s[s.length-1]:null;if(!a)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const i=a[1],c=parseFloat(i);if(isNaN(c))return r.push({line:n,severity:"error",message:`Confidence value "${i}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(c<0||c>1)&&r.push({line:n,severity:"error",message:`Confidence value ${c} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),c>=0&&c<=1&&0===c&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const l=void 0!==a.index?o.substring(0,a.index).trim():o.trim();return l&&0!==l.length?(l.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(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),o=r.findIndex(e=>e.trim().startsWith("# "));return(-1===o?r:r.slice(0,o)).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),o=t.filter(e=>"warning"===e.severity),s=0===r.length;if(0===t.length)return{valid:s,issues:[...t],summary:`✓ ${n} is valid`};const a=[];r.length>0&&a.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&a.push(`${o.length} warning${o.length>1?"s":""}`);const i=r.length>0?"✗":"⚠";return{valid:s,issues:[...t],summary:`${i} ${n} has ${a.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ee.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ee.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`${ee.green(e)} ${ee.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?ee.red(t.summary):ee.yellow(t.summary),"",...formatIssueGroup(r,ee.red,ee.bold(ee.red("Errors:"))),...formatIssueGroup(o,ee.yellow,ee.bold(ee.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"),At(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var Fd=new Set(["# 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:o}=e;Fd.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,o),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 Ld=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:o}=e,s=t.trim();s&&(s.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:o}):s.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):Ld.test(s)||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 o=t.split("\n"),s=preprocessLines(o),a={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of s)processLine({line:e,lineNum:t,state:a,rawLines:o});return checkFinalCategory({state:a,rawLines:o}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var _d=__name(e=>"local-global"===e?"global":"project","locationLabel"),Ud=__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 ${_d(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=[],o=getRootTasteFile({target:n});E(o)&&r.push({path:o,displayName:"taste.md"});const s=(await D.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(...s),r}async function lintFile(e){let t=await D.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await D.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),o=r.issues.filter(e=>"error"===e.severity).length,s=r.issues.filter(e=>"warning"===e.severity).length,a=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:o,warnings:s,formatted:a}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:o}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&o.length>0)return{success:!1,filesLinted:[],errors:o,totalErrors:0,totalWarnings:0};if(0===r.length)return Ud({file:"all",error:`No taste files found in ${_d(n)}`});const s=await Promise.all(r.map(lintFile)),a=s.reduce((e,t)=>e+t.errors,0),i=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid)&&0===o.length,filesLinted:s,errors:o,totalErrors:a,totalWarnings:i}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return Ud({file:"all",error:`No taste files found in ${_d(n)}`});const o=await Promise.all(r.map(lintFile)),s=o.reduce((e,t)=>e+t.errors,0),a=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid),filesLinted:o,errors:[],totalErrors:s,totalWarnings:a}}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}):Ud({file:"all",error:`No taste directory found in ${_d(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"),At(),nr(),__name(resolveConflictStrategy,"resolveConflictStrategy");var jd=ee.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(`${ee.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?`${ee.dim(t[1])}${ee.green(t[2])}${ee.white(t[3]??"")}${t[4]?ee.dim(t[4]):""}`:ee.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ee.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 Bd=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return et(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:Bd})}function getProfileLink(e){return et(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:Bd})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return Xe(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(ee.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(`${ee.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),o=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${o} day${o>1?"s":""} ago`}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(ee.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new be("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 ${ee.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(`${ee.green(Se.tick)} All ${ee.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ee.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ee.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(ee.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),o=r[0].trim(),s=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===s.length?null:{category:normalizeCategory({category:o}),learnings:s,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;let n=await D.readFile(t,"utf-8");const r=migrateHeader({content:n});return r===n?n:(await D.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 o=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===o)return{start:r,end:t.length-1};const s=trimTrailingBlanks({lines:t,from:o-1,until:r});return{start:r,end:s}}function ensureHeader(e){return e?e.trim().startsWith(Ti)?e:Ti+"\n\n"+e:Ti+"\n\n"}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"),At(),At(),At(),At(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),At(),__name(formatPackage,"formatPackage"),At(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var zd="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:zd,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 D.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:zd});if(!E(e))return[];const t=await D.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:zd,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:zd});await D.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:zd,category:n.category}),s=e.dirname(o);await D.mkdir(s,{recursive:!0});const a=formatPackage({pkg:n});await D.writeFile(o,a,"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"),At(),At();var Wd="local-project";function prefixHeaderIfNeeded(e){return!e||e.trim().startsWith(Ti)?e:Ti+"\n\n"+e}async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!E(n))return null;const r=migrateHeader({content:await D.readFile(n,"utf-8")}).split("\n"),o=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!o)return null;const s=r.slice(0,o.start),a=o.end<r.length-1?r.slice(o.end+1):[],i={before:s.join("\n").trim(),after:a.join("\n").trim()},c=[...s,...a].join("\n").trim();return""===c&&await D.rm(n,{force:!0}),""!==c&&await D.writeFile(n,c+"\n","utf-8"),i}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:Wd}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:Wd,category:n}),a=e.dirname(s);return E(a)&&await D.rm(a,{recursive:!0,force:!0}),o}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,o=formatPackage({pkg:t});if(r){let e=prefixHeaderIfNeeded(r.before);e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=o.trim()+t,void await D.writeFile(n,e.trim()+"\n","utf-8")}let s="";E(n)&&(s=await D.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await D.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:Wd,category:n.category}),a=e.dirname(s);await D.mkdir(a,{recursive:!0});const i=formatPackage({pkg:n});await D.writeFile(s,i,"utf-8");const c=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=prefixHeaderIfNeeded(migrateHeader({content:o.before}));e=ensureTrailingNewlines(e);const t=o.after?"\n\n"+o.after:"";return e+=c.trim()+t,void await D.writeFile(r,e.trim()+"\n","utf-8")}let l="";E(r)&&(l=await D.readFile(r,"utf-8"),l=migrateHeader({content:l})),l=ensureHeader(l),l=ensureTrailingNewlines(l),l+=c,await D.writeFile(r,l.trim()+"\n","utf-8")}__name(prefixHeaderIfNeeded,"prefixHeaderIfNeeded"),__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var Hd="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:Hd,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:Hd});if(!E(e))return[];const t=[],n=getRootTasteFile({target:Hd});if(E(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await D.readdir(e,{withFileTypes:!0}),o=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...o),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:Hd});await D.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:Hd}),o=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:o}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:o})}function exists(){const e=getTastePath({target:Hd});return E(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!E(n))return;const r=await D.readFile(n,"utf-8"),o=new Blob([r],{type:"text/markdown"}),s=new File([o],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,s)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:o,type:s="category",isPublic:a=!1}=t,i=new FormData;i.append("name",n),o&&i.append("description",o),i.append("type",s),i.append("isPublic",String(a));const c=formatPackage({pkg:r}),l=new Blob([c],{type:"text/markdown"}),d=new File([l],"taste.md",{type:"text/markdown"});if(i.append("files[taste.md]",d),"category"===s)return i;const u=getTastePath({target:"local-project"}),m=e.join(u,r.category);if(!E(m))return i;const g=getCategoryTasteFile({target:"local-project",category:r.category});if(!E(g))return i;const p=await D.readFile(g,"utf-8"),h=new Blob([p],{type:"text/markdown"}),f=new File([h],"taste.md",{type:"text/markdown"});return i.append(`files[${r.category}/taste.md]`,f),i}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:o=!1}=e,s=new FormData;s.append("name",n),r&&s.append("description",r),s.append("type","project"),s.append("isPublic",String(o));const a=getRootTasteFile({target:"local-project"});if(E(a)){const e=await D.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",n)}const i=t.map(e=>appendCategoryFile(s,e));return await Promise.all(i),s}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:o,extra:s}=e,a=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:a,label:n}),context:{component:Yn.TASTE_REMOTE_STORAGE,heading:r,"http.status":o,...s}}),a}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(),o=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(o)return o;const s=await getAuthKey();if(!s)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:s})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,o=`${t}${ht.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let s;try{s=await fetch(o,{method:"GET"})}catch{return null}if(s.ok){const{data:e}=await s.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===s.status)return null;throwTrackedError({message:await parseApiError({response:s,fallback:`Failed to download taste package (${s.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:s.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:o}=e,s=`${t}${ht.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,a=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o}`}});if(a.ok){const{data:e}=await a.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===a.status)return null;throwTrackedError({message:await parseApiError({response:a,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:a.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:Yn.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()}${ht.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(),o=r.packages||[];if(0===o.length)return[];const s=[];for(let e=0;e<o.length;e+=5){const t=o.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));s.push(...n.filter(e=>null!==e))}return s}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:Yn.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 o=r.files||[];if(0===o.length)return null;const s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1}=e,o=await requireAuthKey(),s=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r}),a=`${getApiBaseUrl()}${ht.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,i=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:s});i.ok||throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:i.status}),await i.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:o=!1}=e,s=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:o}),i=`${getApiBaseUrl()}${ht.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,c=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:a});c.ok||throwTrackedError({message:await parseApiError({response:c,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:c.status,extra:{"package.count":t.length}}),await c.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${ht.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 D.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 be("list").alias("ls").option("-g, --global","List global packages").addOption(new Ce("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ce("--staging","Use staging environment").hideHelp()).description(`List available packages ${ee.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(exists,"exists"),At(),At(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),Rt(),At(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),nr(),At(),nr(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),At(),Rt(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),Cn(),__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 Gd={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?Gd.remote:e.global?Gd.global:Gd.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${Se.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${Se.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,o=r?`, updated ${r}`:"";return` ${ee.white(e.category)}${e.isPublic?ee.green(" [public]"):""}${e.isPublic&&e.starCount?ee.yellow(` ${Se.star}${e.starCount}`):""}${e.downloadCount?ee.gray(` ${Se.arrowDown}${e.downloadCount}`):""}${n}${ee.dim.gray(`(${e.learningCount} learnings${o})`)}`}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?Me(`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${jd} Packages`),console.log(`${ee.gray("⎿")} ${ee.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(ee.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(ee.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,o=await D.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const s=o.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return s>=0?s+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 o=r.sourcePath,s=await findCategoryLineNumber({filePath:o,category:t});return await Qe([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),At(),At(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var qd=new Set(["local-project","local-global","remote-project","remote-user"]);async function open7(e){const{package:t,target:n}=e;if(!qd.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=tt.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 be("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 ${ee.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 oe(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ee.green(Se.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(`${ee.green(Se.tick)} Opened ${ee.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"),At(),At(),At(),At();var Vd=null,Kd=!1;function setActiveSpinner(e){Vd=e}function stopActiveSpinner(e){Vd&&(Vd.stop(e),Vd=null)}function setPrompted(e){Kd=e}function wasPrompted(){return Kd}function beginPrompt(e,t){stopActiveSpinner(),Pe.intro(ee.dim(e)),t&&Pe.log.message(ee.dim(t)),setPrompted(!0)}function handleCancel(e){Pe.isCancel(e)&&(Pe.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Pe.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Pe.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:o}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ee.green(`'${t}'`)} from ${n}`,s),Pe.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${ee.dim(`(from ${n})`)}`);const a=await Pe.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${r.learnings.length} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});handleCancel(a);const i=a;return startStrategySpinner(i),i}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e,o="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ee.green(`'${t}'`)} to global`,o),Pe.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await Pe.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(s);const a=s;return startStrategySpinner(a),a}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ee.green(`'${t}'`)} from global`,o),Pe.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await Pe.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(s);const a=s;return startStrategySpinner(a),a}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const a=et(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ee.green(`'${t}'`)} to ${n}`,s),Pe.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),Pe.log.info(`Current package: ${ee.cyan(a)} ${ee.dim("(review)")}`);const i=await Pe.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(i);const c=i;return startStrategySpinner(c),c}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const a=et(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ee.green(`'${t}'`)} to ${n}`,s),Pe.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),Pe.log.info(`Current package: ${ee.cyan(a)} ${ee.dim("(review)")}`);const i=await Pe.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${o} → ${r} learnings)`}],initialValue:"skip"});handleCancel(i);const c=i;return startStrategySpinner(c),c}function mergeSingleLearning(e,t,n,r){const o=t.get(e.text);return o?e.confidence>o.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},o=new Map(n.map(e=>[e.text,e])),s=new Map(o);for(const e of t)mergeSingleLearning(e,o,s,r);const a=new Set(t.map(e=>e.text)),i=n.filter(e=>!a.has(e.text)).length;return r.unchanged+=i,{merged:Array.from(s.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:o,owner:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:o.category,owner:s,localPkg:r,remoteLearningsCount:o.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:o,result:s}=e,a=await getPackage2({category:t.category}),i=await resolveRemotePullStrategy({flagStrategy:o,overwrite:r,existingPkg:a,tastePkg:t,owner:n});if("skip"===i)return void s.skipped?.push(t.category);if("overwrite"===i&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===i){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:a});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const c=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=c}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:o,flagStrategy:s,result:a}=e,i=t.find(e=>"taste.md"===e.file);if(i){const e=parsePackages({content:i.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:o,flagStrategy:s,result:a})}const c=t.filter(e=>"taste.md"!==e.file);for(const e of c){const t=e.file.replace("/taste.md",""),i={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:i,owner:r,overwrite:o,flagStrategy:s,result:a})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,result:a}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return a.success=!1,void a.errors.push({pkg:n,error:"No taste.md file found in category package"});const c={category:n,learnings:parseTasteContent(i.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:c,owner:r,overwrite:o,flagStrategy:s,result:a})}__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"),At(),At(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),At(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var Jd=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),Yd=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),Qd=__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:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPullStrategy({packageName:s.category,localPkg:r,globalLearningsCount:s.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:o,result:s}=e,a=await getPackage2({category:t.category}),i=await resolvePullStrategy({flagStrategy:r,overwrite:o,existingPkg:a,source:n,tastePkg:t});if("skip"===i)return void s.skipped.push(t.category);if("overwrite"===i&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===i){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:a});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const c=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=c}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:o}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return Jd({pkg:"all",error:`Invalid source: ${n}`});const s=Qd(n);let a;try{a="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return Jd({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===a.length)return Jd({pkg:"all",error:`No taste packages found in ${s}`});const i=validatePackages({packages:a,label:s});if(i.length>0)return{success:!1,packagesPulled:[],errors:[...i],mergeDetails:{},overwritten:[],filePaths:{}};const c=t.length>0?a.filter(e=>t.includes(e.category)):a;if(t.length>0&&0===c.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const l=Yd();for(const e of c)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:o,overwrite:r,result:l});return l}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s}=e,a=await downloadPackage({owner:t,packageName:n});if(!a)return Jd({pkg:n,error:"Taste package not found in remote"});const{type:i,files:c}=a,l=validateRemoteFiles({files:c,packageName:n});if(l.length>0)return{success:!1,packagesPulled:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:c,packageName:n,owner:t,overwrite:r,flagStrategy:o,result:s};return"project"===i?(await pullProjectPackage(d),s):(await pullCategoryPackage(d),s)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:o}=e,s=Yd();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return Jd({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Pe.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:o,mergeDetails:s}=e,a=wasPrompted()?"":`${Se.tick} `,i=r?ee.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${ee.green(a)}Replaced ${ee.green(`'${t}'`)} taste package in project`+i;if(s){const e=formatMergeParts(s);return`${ee.green(a)}Pulled ${ee.green(`'${t}'`)} taste package from ${n} ${ee.gray(`(${e.join(", ")})`)}`+i}return`${ee.green(a)}Pulled ${ee.green(`'${t}'`)} taste package from ${n}`+i}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const o=t.packagesPulled[0],s=t.filePaths?.[o],a=t.mergeDetails?.[o];return logResult(buildPullMessage({pkgName:o,sourceName:n,filePath:s,options:r,mergeDetails:a})),!r.overwrite&&!!a&&hasMergeConflictRisk(a)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],o=t.skipped??[],s=t.packagesPulled.filter(e=>!r.includes(e)),a=t.packagesPulled.length+o.length,i=`${a} ${1===a?"package":"packages"}`,c=[];return s.length>0&&c.push(wrapLine(`${ee.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&c.push(wrapLine(`${ee.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&c.push(wrapLine(`${ee.dim("Skipped")} (${o.length}) ${ee.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(c.length>0&&Pe.log.message(c.join("\n")),Pe.outro(`${i} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ee.green(Se.tick)} ${i} from ${n}`),c.length>0&&console.log(c.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,o=t.skipped??[];t.packagesPulled.length+o.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():o.length>0?logResult(ee.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new be("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 Ce("--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 Ce("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ee.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:o}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?o??"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 o=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:o}):pullGlobal({packageName:t,options:r,strategy:o})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,o=parseOwnerPackage(t);o||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner(Me("Pulling taste package").start());const s=await pullRemote({owner:o.owner,packageName:o.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s,owner:o.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner(Me("Pulling taste package").start());const o=n.all||!t?[]:[t],s=await pull({packages:o,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new Co({baseUrl:e}),n=await t.get({endpoint:ht.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 Pe.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()?"":`${Se.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ee.green(t)}Skipped ${n}`)}return!1}const o=n.packagesPushed.length,s=`${o} ${1===o?"package":"packages"}`,a=n.filePaths?.[n.packagesPushed[0]],i=r.global&&a?shortenPath(e.dirname(e.dirname(a))):a,c=wasPrompted()?"":`${Se.tick} `;if(!i)return logResult2(`${ee.green(c)}Pushed ${s} 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?` ${ee.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ee.green(c)}Replaced ${s} in ${i}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ee.green(c)}Pushed ${s} to ${i}`),!1;let l=0,d=0,u=0;for(const e of Object.values(n.mergeDetails))l+=e.added??0,d+=e.updated??0,u+=e.unchanged??0;const m=formatMergeParts({added:l,updated:d,unchanged:u}),g=m.length>0?` ${ee.gray(`(${m.join(", ")})`)}`:"";return logResult2(`${ee.green(c)}Pushed ${s} to ${i}${g}`),(l>0||d>0)&&u>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],o=t.filePaths?.[r],s=n.remote&&o,a=s?o:"global",i=wasPrompted()?"":`${Se.tick} `,c=!s&&o?ee.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${ee.green(i)}Replaced ${ee.green(`'${r}'`)} taste package in ${a}`+c),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ee.green(i)}Pushed ${ee.green(`'${r}'`)} taste package to ${a} ${ee.gray(`(${n.join(", ")})`)}`+c),hasMergeConflictRisk(e)}return logResult2(`${ee.green(i)}Pushed ${ee.green(`'${r}'`)} taste package to ${a}`+c),!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",o=wasPrompted()?"":`${Se.tick} `;return logResult2(wrapLine(`${ee.green(o)}Pushed ${ee.green(t.packagesPushed.length)} taste packages ${ee.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[o,s]=n.split("/");if(!o||!s)continue;const a=getPackageLink({owner:o,packageName:s});r.has(a)||(r.add(a),console.log(ee.gray(` ${a}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],o=t.packagesPushed.filter(e=>!n.includes(e)),s=t.packagesPushed.length+r.length,a=[];o.length>0&&a.push(wrapLine(`${ee.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&a.push(wrapLine(`${ee.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&a.push(wrapLine(`${ee.dim("Skipped")} (${r.length}) ${ee.dim(r.join(", "))}`,4)),a.length>0&&Pe.log.message(a.join("\n"));const i=`${s} ${1===s?"package":"packages"}`;Pe.outro(i)}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)),o=[];r.length>0&&o.push(wrapLine(`${ee.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${ee.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${ee.dim("Skipped")} (${n.length}) ${ee.dim(n.join(", "))}`)),o.length>0&&console.log(o.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"),At(),__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"),At(),Cn(),At(),Rt(),__name(fetchUserNamespaces,"fetchUserNamespaces"),At(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),At(),At();var Zd=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),Xd=__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:o,projectName:s,owner:a}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const i=r.type??"category",c=o.reduce((e,t)=>e+t.learnings.length,0),l=Xd(r.files);return"project"!==i?promptTypeMismatchStrategy({packageName:s,owner:a,localLearningsCount:c,remoteLearningsCount:l}):promptSameTypeStrategy({packageName:s,owner:a,localLearningsCount:c,remoteLearningsCount:l})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,isPublicExplicitlySet:a,flagStrategy:i}=t,c=e.basename(process.cwd()),l={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:c});if("skip"===await resolvePushAllStrategy({flagStrategy:i,overwrite:o,existingProject:d,packagesToPush:n,projectName:c,owner:r}))return l.skipped.push(...n.map(e=>e.category)),l;await writePackages({packages:n,projectName:c,owner:r,isPublic:a?s:d?.isPublic??!1});for(const e of n)l.packagesPushed.push(e.category),l.filePaths[e.category]=`${r}/${c}`,l.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&l.overwritten.push(...n.map(e=>e.category)),l}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return Zd({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var eu=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),tu=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:o}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:o})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var nu=__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:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPushStrategy({packageName:s.category,localLearningsCount:s.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:o,userOwner:s,isPublic:a,result:i}=e,c="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),l=await resolveSinglePushStrategy({flagStrategy:r,overwrite:o,existingPkg:c,target:n,tastePkg:t});if("skip"===l)return void i.skipped.push(t.category);if("overwrite"===l&&(await writePkg({pkg:t,target:n,owner:s,isPublic:a}),i.packagesPushed.push(t.category),i.overwritten.push(t.category),i.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===l){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:c});await writePkg({pkg:e,target:n,owner:s,isPublic:a}),i.packagesPushed.push(t.category),i.mergeDetails[t.category]=r}const d=nu({target:n,category:t.category,owner:s});d&&(i.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:o=!1,isPublic:s=!1,strategy:a}=e;if(!exists())return eu({pkg:"all",error:"No taste directory found in project"});const i=await getAllPackages2();if(0===i.length)return eu({pkg:"all",error:"No taste packages found in project"});const c=validatePackages({packages:i,label:"project"});if(c.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...c],mergeDetails:{},overwritten:[],filePaths:{}};const l=n.length>0?i.filter(e=>n.includes(e.category)):i;if(n.length>0&&0===l.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:l,owner:d,overwrite:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:a}):eu({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return eu({pkg:"all",error:`Invalid target: ${r}`});const u=tu();for(const e of l)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:a,overwrite:o,userOwner:d,isPublic:s,result:u});return u}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:o=!1,isPublic:s=!1,strategy:a}=e,i=await getPackage2({category:r});if(!i)return eu({pkg:r,error:`Taste package '${r}' not found in local project`});const c=validateTasteFile({content:formatPackage({pkg:i}),filePath:`${i.category}/taste.md`});if(!c.valid){const e=formatValidationIssues({result:c,verbose:!0});return eu({pkg:r,error:`Validation failed:\n${e}`})}c.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:c,verbose:!0})+"\n"));const l=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:a,overwrite:o,existingPkg:l,target:"remote-project",tastePkg:i}),u=t?s:l?.isPublic??!1,m=tu();if("skip"===d)return m.skipped.push(r),m;if("overwrite"===d&&(await writePackage3({pkg:i,owner:n,isPublic:u}),m.packagesPushed.push(r),m.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:i,existing:l});await writePackage3({pkg:e,owner:n,isPublic:u}),m.packagesPushed.push(r),m.mergeDetails[r]=t}return m.filePaths[r]=`${n}/${r}`,m}async function pushRemote(e){const{packageName:t}=e;if(!exists())return eu({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return eu({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"}))],o=await Pe.select({message:"Owner",options:r,initialValue:t});return Pe.isCancel(o)&&(Pe.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new be("push").description(`Push taste packages to remote ${ee.dim("(commandcode.ai)")} or global ${ee.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 Ce("--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 Ce("--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"),At(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var ru=__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};Pe.intro(ee.dim(`pushing ${t}`)),setPrompted(!0);const o=Pe.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),Pe.outro(ee.red(`Taste package '${t}' not found in project`)),process.exit(1));const s=await fetchUserNamespaces();return o.stop(s.orgs.length>0?"Select owner to push to":""),{owner:s.orgs.length>0?await promptOwnerSelection(s):s.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 o=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:o}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:o}):pushGlobal({packageName:t,options:r,strategy:o})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const o=(await getAllPackages2()).length,s=`${o} ${1===o?"package":"packages"}`,a=e.basename(process.cwd()),i=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(ee.dim(` Pushing ${s} to ${a} (remote)${i}`)),console.log(""),setActiveSpinner(Me("Pushing taste packages").start());const c=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:ru(n),strategy:r,owner:n.owner});return stopActiveSpinner(),c}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:o,packageName:s}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:o,pkgName:s});const a=await pushRemote({owner:o,packageName:s,overwrite:n.overwrite,isPublic:ru(n),strategy:r});return stopActiveSpinner(`Pushed to ${o}/${s}`),a}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=Pe.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Me("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,o=n.all||!t?[]:[t],s=await getAllPackages2(),a=o.length>0?o.length:s.length,i=`${a} ${1===a?"package":"packages"}`,c=shortenPath(getTastePath({target:"local-global"})),l=resolveStrategyLabel({strategy:r});console.log(ee.dim(` Pushing ${i} to ${c}${l}`)),console.log(""),setActiveSpinner(Me("Pushing taste packages").start());const d=await push({packages:o,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new be(St.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?ne.bold(ne.green(t)):ne.white(t);return`${ne.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${ne.bold(ne.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(ne.dim(`Run ${ne.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(ne.dim("Try updating manually:")),console.log(ne.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(ne.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Me("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(`${ne.green(Se.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${ne.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Me("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} ${Se.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:Yn.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 ${ne.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"),At(),Rt(),nr(),__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 ou=new be("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);At();var su=__name((e,t)=>`${Se.info} ${e}: ${ne.cyan(t)}`,"formatInfoLine"),au=__name(e=>ne.bold(`${e}:`),"formatSectionHeader"),iu=__name(e=>ne.red(e),"formatError"),cu=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),lu=__name(e=>["",au("User Information"),su("Name",e.name),su("Email",e.email),su("Username",e.userName)],"buildUserOutput"),du=__name(e=>["",au("Organization"),su("Name",e.name),su("Login",e.login)],"buildOrgOutput"),uu=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),mu=__name((e,t)=>{uu(lu(e)),t&&uu(du(t)),console.log("")},"displayUserInfo"),gu=__name(e=>null!==e&&e.length>0,"validateApiKey"),pu=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Me("Fetching user information...").start();try{const t=await getAuthKey();gu(t)||(e.fail(iu('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();pu(n)||(e.fail(iu("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),mu(n.user,n.org)}catch(t){e.fail(iu(`Error: ${cu(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var hu=new be("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var fu=createProgram();fu.action(interactiveModeAction),fu.addCommand(Dd),fu.addCommand(Md),fu.addCommand(hu),fu.addCommand(ou),fu.addCommand(Rd),fu.addCommand(createTasteCommand()),fu.addCommand(createMcpCommand()),fu.addCommand(Nd),fu.addCommand(jr),fu.addCommand(Gr),fu.addCommand(Qr),setupCommanderHooks(fu),fu.parse();
|
|
2
|
+
import*as e from"path";import t,{join as n,dirname as r,relative as o,isAbsolute as s,resolve as a,extname as i,basename as c}from"path";import{fileURLToPath as l,URL as d,pathToFileURL as u}from"url";import m,{z as g}from"zod";import*as p from"os";import h,{tmpdir as f}from"os";import*as y from"fs";import w,{existsSync as E,readFileSync as S,promises as k,constants as v,mkdirSync as b,writeFileSync as C,readdirSync as P,statSync as T,createReadStream as A}from"fs";import{spawn as x,execSync as I,exec as $,execFile as R}from"child_process";import*as D from"fs/promises";import M,{mkdir as N,writeFile as O,readFile as F,unlink as L}from"fs/promises";import*as _ from"crypto";import U,{randomUUID as j}from"crypto";import B,{useState as z,useRef as W,useEffect as H,useCallback as G,useMemo as q}from"react";import{Box as V,Text as K,Static as J,render as Y,useStdout as Q,useInput as Z,useApp as X}from"ink";import ee from"chalk";import te from"strip-ansi";import ne from"picocolors";import re from"sharp";import oe from"open";import se from"@opentelemetry/sdk-node";import ae from"@opentelemetry/exporter-trace-otlp-http";import ie from"@opentelemetry/resources";import ce from"@opentelemetry/semantic-conventions";import le from"@opentelemetry/sdk-trace-node";import{trace as de,SpanStatusCode as ue,context as me}from"@opentelemetry/api";import{v4 as ge}from"uuid";import*as pe from"http";import*as he from"net";import fe from"net";import{promisify as ye}from"util";import"dotenv/config";import we from"dedent";import Ee from"log-symbols";import Se,{mainSymbols as ke}from"figures";import ve from"readline/promises";import{Command as be,Option as Ce}from"commander";import*as Pe from"@clack/prompts";import{cancel as Te,select as Ae,isCancel as xe,note as Ie,confirm as $e,password as Re}from"@clack/prompts";import De from"ink-spinner";import Me from"ora";import Ne from"@crosscopy/clipboard";import Oe from"gray-matter";import{EventEmitter as Fe}from"events";import Le from"@sindresorhus/slugify";import{minimatch as _e}from"minimatch";import{glob as Ue}from"glob";import{quote as je}from"shell-quote";import{MessageStream as Be}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import ze from"strip-json-comments";import*as We from"readline";import He from"ink-select-input";import Ge from"semver";import qe from"ignore";import Ve from"ink-gradient";import{Marked as Ke}from"marked";import Je from"marked-terminal";import*as Ye from"diff";import Qe from"open-editor";import Ze from"ink-text-input";import{wrapAnsi as Xe}from"fast-wrap-ansi";import et from"terminal-link";import*as tt from"process";var nt,rt,ot,st,at,it,ct,lt,dt,ut,mt,gt,pt,ht,ft,yt,wt,Et,St,kt,vt,bt,Ct=Object.defineProperty,Pt=Object.getOwnPropertyNames,__name=(e,t)=>Ct(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[Pt(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)Ct(e,n,{get:t[n],enumerable:!0})},Tt=__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"(){}}),At=__esm({"src/utils/telemetry/constants.ts"(){Tt(),nt="https://api.axiom.co/v1/traces",rt="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",ot="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",st="xaat-add69148-8f73-4833-921d-bc843285c95f",at="command-code-cli",it="command_code_cli_tracing",ct=["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"],lt=["content","body"],dt=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 xt,It,$t=__esm({"../shared/src/constants.ts"(){Tt(),mt="--xco",gt={INTERNAL_TEAM_FLAG_HEADER:`x-${(ut="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage"},pt={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"}}}},ht={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(ht.ALPHA.TASTE),Object.values(ht.BETA.TASTE_PACKAGES),pt.ALPHA.GENERATE,pt.ALPHA.AGENT.GENERATE,pt.ALPHA.WHOAMI,pt.ALPHA.NAMESPACES,pt.ALPHA.SHARE.CREATE,pt.ALPHA.SHARE.DELETE,pt.ALPHA.SHARE.APPEND,pt.ALPHA.DEVREL_THREAD.CREATE,pt.ALPHA.DEVREL_THREAD.DELETE,pt.ALPHA.DEVREL_THREAD.UPDATE,pt.ALPHA.TASTE.LEARN,pt.ALPHA.TASTE.DELETE,pt.ALPHA.TASTE.GET,pt.ALPHA.TASTE.UPDATE,Object.values(pt.BETA.TASTE.PACKAGES),pt.INTERNAL.ADMIN.USERS,pt.INTERNAL.ADMIN.ORGS,pt.INTERNAL.ADMIN.ENTITY_TYPE,pt.INTERNAL.USER.AVATAR,pt.INTERNAL.USER.SETTINGS,pt.INTERNAL.API_KEYS.LIST,pt.INTERNAL.API_KEYS.CREATE,pt.INTERNAL.API_KEYS.DELETE,pt.INTERNAL.USAGE.LIST,pt.INTERNAL.USAGE.SUMMARY,pt.INTERNAL.ADMIN.GRANT_CREDITS,pt.INTERNAL.ADMIN.GRANT_ORG_CREDITS,pt.INTERNAL.BILLING.CREDITS.GET,pt.INTERNAL.BILLING.CUSTOMERS.GET,pt.INTERNAL.BILLING.CUSTOMERS.UPSERT,pt.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,pt.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,pt.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,pt.INTERNAL.BILLING.CUSTOMERS.INVOICES,pt.INTERNAL.BILLING.SUBSCRIPTIONS.GET,pt.INTERNAL.ORGS.LIST,pt.INTERNAL.ORGS.GET,pt.INTERNAL.ORGS.CREATE,pt.INTERNAL.ORGS.UPDATE,pt.INTERNAL.ORGS.DELETE,pt.INTERNAL.ORGS.MEMBERS.LIST,pt.INTERNAL.ORGS.MEMBERS.ADD,pt.INTERNAL.ORGS.MEMBERS.UPDATE,pt.INTERNAL.ORGS.MEMBERS.REMOVE,pt.INTERNAL.ORGS.INVITATIONS.LIST,pt.INTERNAL.ORGS.INVITATIONS.SEND,pt.INTERNAL.ORGS.INVITATIONS.ACCEPT,pt.INTERNAL.ORGS.INVITATIONS.CANCEL,pt.INTERNAL.TASTE.PACKAGES.LIST,Object.values(ht.INTERNAL.ORGS),Object.values(ht.INTERNAL.USER),Object.values(ht.INTERNAL.TASTE.PACKAGES),ft={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(ft.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl"),yt={ANTHROPIC:"anthropic"},wt="anthropic:claude-haiku-4-5-20251001",m.enum(["owner","admin","member"]),Et={LEARN_TASTE:"learn-taste",TASTE:"taste",TERMINAL_SETUP:"terminal-setup"},(St={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,St.SONNET_4_5.id,St.OPUS_4_5.id,St.OPUS_4_6.id,kt=St.SONNET_4_6.id,new Set([].map(e=>e.toLowerCase())),vt=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],bt={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}}}),Rt=__esm({"src/utils/env.ts"(){Tt(),xt=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),It=__name(()=>{const e=xt();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag")}});function getAuthDir(){return t.join(h.homedir(),".commandcode")}function getAuthFile(e){const n=e??xt(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??xt(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var Dt,Mt,Nt=__esm({"src/utils/auth/auth-paths.ts"(){Tt(),$t(),Rt(),__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 w.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(;!w.existsSync(n);){const o=t.dirname(n);if(o===n)return t.normalize(e);r.unshift(t.basename(n)),n=o}return t.join(getCanonicalPath(n),...r)}catch{return t.normalize(e)}}function formatDirectoryForDisplay(e){const n=canonicalizeForLookup(t.normalize(e)),r=getCanonicalPath(process.cwd()),o=h.homedir();if(isPathInDirectory(n,r)){const e=t.relative(r,n);return e?`./${e}`:"."}if(o&&isPathInDirectory(n,o)){const e=t.relative(o,n);return e?`~/${e}`:"~"}return n}function isPathInDirectory(e,n){const r=normalizePathForComparison(e),o=normalizePathForComparison(n),s=o.endsWith(t.sep)?o:o+t.sep;return r===o||r.startsWith(s)}function findSensitiveDirectoryConflict(e){const n=[t.normalize(e),getCanonicalPath(e)];for(const e of Dt){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(h.homedir(),n.slice(1))),t.isAbsolute(n)||(n=t.resolve(process.cwd(),n)),t.normalize(n)}function createSkippedResult(e){const{inputPath:t,absolutePath:n,code:r}=e,o=formatDirectoryForDisplay(n);return{status:"skipped",inputPath:t,absolutePath:n,displayPath:o,code:r,message:"ALREADY_IN_WORKSPACE"===r?`${o} is already accessible from the current workspace`:`${o} is already added`}}function createErrorResult(e){const{inputPath:t,code:n,message:r}=e;return{status:"error",inputPath:t,code:n,message:r}}function addDirectory(e){const t=e.trim();if(!t)return createErrorResult({inputPath:e,code:"EMPTY_PATH",message:"Directory path cannot be empty"});const n=resolveDirectoryPath(e);let r,o;try{r=w.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{w.accessSync(n,w.constants.R_OK),o=getCanonicalPath(n)}catch{return createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}const s=findSensitiveDirectoryConflict(o);if(s)return createErrorResult({inputPath:e,code:"SENSITIVE_DIRECTORY",message:`Cannot add ${formatDirectoryForDisplay(o)} because it overlaps sensitive path ${formatDirectoryForDisplay(s)}`});const a=getCanonicalPath(process.cwd());return isPathInDirectory(o,a)?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_IN_WORKSPACE"}):Mt.some(e=>isPathInDirectory(o,e)||isPathInDirectory(e,o))?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_ADDED"}):(Mt.push(o),{status:"added",inputPath:e,absolutePath:o,displayPath:formatDirectoryForDisplay(o)})}function getAdditionalDirectories(){return[...Mt]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Mt.findIndex(e=>areSamePath(t,e));return-1!==n&&(Mt.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Mt.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t)}var Ot=__esm({"src/utils/additional-dirs.ts"(){Tt(),Dt=new Set(["/etc","/root","/proc","/sys","/dev",t.join(h.homedir(),".ssh"),t.join(h.homedir(),".gnupg"),t.join(h.homedir(),".aws")]),Mt=[],__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`${h.platform()}-${h.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 w.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,o=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,a=[];return n>0&&a.push(`M ${n}`),r>0&&a.push(`A ${r}`),o>0&&a.push(`D ${o}`),s>0&&a.push(`?? ${s}`),a.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=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 Ft,Lt,_t,Ut,jt,Bt,zt,Wt,Ht,Gt,qt,Vt=__esm({"src/utils/environment.ts"(){Tt(),Ot(),__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!!Ft.has(e)||!!Gt.test(e)}function isWordRightSequence(e){return!!Lt.has(e)||!!qt.test(e)}function isHomeSequence(e){return _t.has(e)}function isEndSequence(e){return Ut.has(e)}function isForwardDeleteSequence(e){return jt.has(e)}function isDeleteWordSequence(e){return Bt.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===zt.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===zt.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===zt.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===zt.CTRL_U}function isAltP(e){return Ht.has(e)}function isCtrlKey({inputChar:e,key:t,letter:n,ctrlCode:r}){return!(!t.ctrl||e.toLowerCase()!==n.toLowerCase())||void 0!==r&&e.charCodeAt(0)===r}var Kt,Jt,Yt,Qt,Zt,Xt,en=__esm({"src/utils/keyboard-sequences.ts"(){Tt(),Ft=new Set(["[1;3D","b","[1;5D","[1;9D","[5D"]),Lt=new Set(["[1;3C","f","[1;5C","[1;9C","[5C"]),_t=new Set(["[H","[1~","[7~","OH"]),Ut=new Set(["[F","[4~","[8~","OF"]),jt=new Set(["[3~"]),Bt=new Set(["",""]),zt={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},Wt={ALT_P:112,ALT_P_NO_META:960},Ht=new Set([String.fromCharCode(27,Wt.ALT_P),String.fromCharCode(Wt.ALT_P_NO_META),"[112;3u"]),Gt=/^\x1b\[1;[359]D$/,qt=/^\x1b\[1;[359]C$/,__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(isAltP,"isAltP"),__name(isCtrlKey,"isCtrlKey")}}),tn=__esm({"src/auth/index.ts"(){Tt(),$t(),Rt(),(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(h.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=xt(),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 M.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await M.mkdir(o,{recursive:!0});let a={};try{const e=await M.readFile(s,"utf-8");a=JSON.parse(e)}catch{}a[e]=t,await M.writeFile(s,JSON.stringify(a,null,2)),await M.chmod(s,384)}async function remove(e){const t=r();try{const n=await M.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await M.unlink(t):(await M.writeFile(t,JSON.stringify(r,null,2)),await M.chmod(t,384))}catch{}}async function list2(){try{const e=await M.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")})(Kt||(Kt={}))}}),nn=__esm({"src/utils/constants.ts"(){Tt(),$t(),Jt="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing",Yt='OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.',Qt=">"}}),rn=__esm({"src/auth/anthropic.ts"(){Tt(),tn(),nn(),fr(),(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 U.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return U.createHash("sha256").update(e).digest("base64url")}function generateState(){return U.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),o=generateState();return{url:`https://claude.ai/oauth/authorize?${new URLSearchParams({code:"true",client_id:t,response_type:"code",redirect_uri:r,scope:"org:create_api_key user:profile user:inference",code_challenge:n,code_challenge_method:"S256",state:o}).toString()}`,verifier:e,state:o}}async function exchangeCodeForTokens2(e,o,s){const a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:s})});if(!a.ok){const e=await a.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:dr.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const i=await a.json();await Kt.set("anthropic",{type:"oauth",refresh:i.refresh_token,access:i.access_token,expires:Date.now()+1e3*i.expires_in})}async function refreshAccessToken2(){const e=await Kt.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:dr.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await Kt.remove("anthropic");const o=await r.json();return await Kt.set("anthropic",{type:"oauth",refresh:o.refresh_token,access:o.access_token,expires:Date.now()+1e3*o.expires_in}),o.access_token}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:dr.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await Kt.remove("anthropic")}}}async function getValidAccessToken2(){const e=await Kt.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")})(Zt||(Zt={}))}});function isWordBoundary(e){return!e||0===e.length||Xt.test(e)}function findPreviousWordBoundary(e,t){if(!e||t<=0)return 0;let n=Math.min(t,e.length);for(;n>0&&isWordBoundary(e[n-1]||"");)n--;for(;n>0&&!isWordBoundary(e[n-1]||"");)n--;return n}function findNextWordBoundary(e,t){if(!e)return 0;if(t>=e.length)return e.length;let n=Math.max(0,t);for(;n<e.length&&isWordBoundary(e[n]||"");)n++;for(;n<e.length&&!isWordBoundary(e[n]||"");)n++;return n}function deleteWordBackwards(e,t){if(!e||t<=0)return{text:e||"",cursor:0};const n=findPreviousWordBoundary(e,t);return{text:e.slice(0,n)+e.slice(t),cursor:n}}function clampCursor(e,t){return Math.max(0,Math.min(e,t))}function findLineStart(e,t){if(!e||t<=0)return 0;for(let n=Math.min(t,e.length)-1;n>=0;n--)if("\n"===e[n])return n+1;return 0}function findLineEnd(e,t){if(!e)return 0;if(t>=e.length)return e.length;for(let n=Math.max(0,t);n<e.length;n++)if("\n"===e[n])return n;return e.length}function moveCursorUp(e,t){if(!e)return 0;const n=findLineStart(e,t);if(0===n)return t;const r=t-n,o=n-1,s=findLineStart(e,o),a=o-s;return s+Math.min(r,a)}function moveCursorDown(e,t){if(!e)return 0;const n=findLineStart(e,t),r=findLineEnd(e,t);if(r===e.length)return t;const o=t-n,s=r+1,a=findLineEnd(e,s)-s;return s+Math.min(o,a)}function insertTextAt(e,t,n){const r=e||"",o=clampCursor(t,r.length);return{text:r.slice(0,o)+n+r.slice(o),cursor:o+n.length}}function deleteCharBefore(e,t){return!e||t<=0?{text:e||"",cursor:0}:{text:e.slice(0,t-1)+e.slice(t),cursor:t-1}}function deleteCharAt(e,t){return!e||t>=e.length?{text:e||"",cursor:t}:{text:e.slice(0,t)+e.slice(t+1),cursor:t}}var on=__esm({"src/utils/text-navigation.ts"(){Tt(),Xt=/\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 processWordLeft(e,t){return{value:e,cursor:findPreviousWordBoundary(e,t),handled:!0}}function processWordRight(e,t){return{value:e,cursor:findNextWordBoundary(e,t),handled:!0}}function processLineStart(e,t){return{value:e,cursor:findLineStart(e,t),handled:!0}}function processLineEnd(e,t){return{value:e,cursor:findLineEnd(e,t),handled:!0}}function processDeleteWord(e,t){const n=deleteWordBackwards(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processDeleteToEnd(e,t){const n=findLineEnd(e,t);return{value:e.slice(0,t)+e.slice(n),cursor:t,handled:!0}}function processDeleteToStart(e,t){const n=findLineStart(e,t);return{value:e.slice(0,n)+e.slice(t),cursor:n,handled:!0}}function processForwardDelete(e,t){const n=deleteCharAt(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processBackspace(e,t){const n=deleteCharBefore(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processCursorLeft(e,t,n){return n?t<=0?{value:e,cursor:t,handled:!0}:{value:e,cursor:t-1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorRight(e,t,n){return n?t>=e.length?{value:e,cursor:t,handled:!0}:{value:e,cursor:t+1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorUp(e,t,n){return n?{value:e,cursor:moveCursorUp(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorDown(e,t,n){return n?{value:e,cursor:moveCursorDown(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCharacterInput(e,t,n){const r=n.replace(/[\x00-\x1F\x7F]|\x1b.*/g,"");if(0===r.length)return{value:e,cursor:t,handled:!1};const o=insertTextAt(e,t,r);return{value:o.text,cursor:o.cursor,handled:!0}}function processRawInput(e,t,n){return isWordLeftSequence(e)?processWordLeft(t,n):isWordRightSequence(e)?processWordRight(t,n):isHomeSequence(e)?processLineStart(t,n):isEndSequence(e)?processLineEnd(t,n):isCtrlA(e)?processLineStart(t,n):isCtrlE(e)?processLineEnd(t,n):isDeleteWordSequence(e)?processDeleteWord(t,n):isCtrlK(e)?processDeleteToEnd(t,n):isCtrlU(e)?processDeleteToStart(t,n):isForwardDeleteSequence(e)?processForwardDelete(t,n):{value:t,cursor:n,handled:!1}}function isIgnoredKey(e,t){return!(!t.ctrl||"c"!==e)||!!t.tab||!(!t.shift||!t.tab)}function processInkInput(e,t,n,r,o){const s=t;return s.meta&&t.leftArrow?processLineStart(n,r):s.meta&&t.rightArrow?processLineEnd(n,r):s.meta&&"b"===e?processWordLeft(n,r):s.meta&&"f"===e?processWordRight(n,r):t.ctrl&&"a"===e?processLineStart(n,r):t.ctrl&&"e"===e?processLineEnd(n,r):t.ctrl&&"w"===e?processDeleteWord(n,r):t.ctrl&&"k"===e?processDeleteToEnd(n,r):t.ctrl&&"u"===e?processDeleteToStart(n,r):t.leftArrow?processCursorLeft(n,r,o):t.rightArrow?processCursorRight(n,r,o):t.upArrow?processCursorUp(n,r,o):t.downArrow?processCursorDown(n,r,o):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!s.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}var sn,an,cn,ln=__esm({"src/components/text/input-handlers.ts"(){Tt(),on(),en(),__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(){sn||(sn=!0,an=[],cn=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&an.push(t)},"earlyInputHandler"),process.stdin.on("data",cn))}function stopEarlyInputCapture(){sn&&cn&&(process.stdin.off("data",cn),cn=null,sn=!1)}function consumeBufferedInput(){const e=an.join("");return an=[],e}function hasBufferedInput(){return an.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("[I")||e.startsWith("[O"))}var dn=__esm({"src/utils/early-input-buffer.ts"(){Tt(),sn=!1,an=[],cn=null,__name(startEarlyInputCapture,"startEarlyInputCapture"),__name(stopEarlyInputCapture,"stopEarlyInputCapture"),__name(consumeBufferedInput,"consumeBufferedInput"),__name(hasBufferedInput,"hasBufferedInput"),__name(isControlSequenceToSkip,"isControlSequenceToSkip")}});function useCursorState({value:e,focus:t,showCursor:n}){const[r,o]=z((e||"").length),s=W(r),a=W(e);H(()=>{s.current=r},[r]),H(()=>{const i=a.current;if(a.current=e,e===i)return;if(!t)return;if(!n)return;const c=(e||"").length,l=(i||"").length;(Math.abs(c-l)>1||r>c)&&(o(c),s.current=c)},[e,t,n,r]);const i=G(e=>{o(e),s.current=e},[]);return{cursor:r,setCursor:i,cursorRef:s}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o}){const s=W(!1);H(()=>{if(!e)return;const a=process.stdin,i=__name(e=>{const s=processRawInput(e.toString(),t.current,n.current);if(!s.handled)return;o(!0);const a=clampCursor(s.cursor,s.value.length);r(s.value,a),setTimeout(()=>o(!1),0)},"handleRawInput");if(a.on("data",i),!s.current&&hasBufferedInput()){s.current=!0;const e=consumeBufferedInput();e&&i(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",i)}},[e,t,n,r,o])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){Z((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void a?.(n.current);const c=processInkInput(e,i,n.current,r.current,t);if(!c.handled)return;const l=clampCursor(c.cursor,c.value.length);s(c.value,l)},{isActive:e})}function useSyncedRef(e){const t=W(e);return H(()=>{t.current=e},[e]),t}var un=__esm({"src/components/text/hooks.ts"(){Tt(),on(),ln(),dn(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef")}});function renderPlaceholder(e,t){return t?0===e.length?ee.inverse(" "):ee.inverse(e[0])+ee.grey(e.slice(1)):ee.grey(e)}function renderValue(e,t,n){if(!n)return e;if(0===e.length)return ee.inverse(" ");let r="";for(let n=0;n<e.length;n++)n===t?"\n"===e[n]?r+=ee.inverse(" ")+"\n":r+=ee.inverse(e[n]):r+=e[n];return t===e.length&&(r+=ee.inverse(" ")),r}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(te(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",c=0,l=!0;for(const e of a){const t=te(e).length;if(c+t>(l?s:o)&&c>0&&(i+="\n"+r,c=n,l=!1),i+=e,c+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);c=te(t).length,l=!0}}return i}function getDisplayValue(e,t,n,r,o){const s=r&&o;return t&&0===e.length?renderPlaceholder(t,s):renderValue(e,n,s)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}var mn=__esm({"src/components/text/render-utils.ts"(){Tt(),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue")}});function createStdinUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n.current(r),t.current=r)}}function createInkUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n(r),t.current=r)}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:a,onCursorChange:i,prefix:c="",prefixColor:l}){const d=W(!1),u=useSyncedRef(e),m=useSyncedRef(s),{cursor:g,setCursor:p,cursorRef:h}=useCursorState({value:e,focus:n,showCursor:o});B.useEffect(()=>{i?.(g)},[g,i]);const f=G(createStdinUpdateHandler(p,u,m),[p,u,m]),y=G(()=>createInkUpdateHandler(p,u,s),[p,u,s])(),w=G(e=>{d.current=e},[]),E=G(()=>d.current,[]);useRawStdinHandler({focus:n,valueRef:u,cursorRef:h,onUpdate:f,setHandled:w}),useInkInputHandler({focus:n,showCursor:o,valueRef:u,cursorRef:h,isHandledByStdin:E,onUpdate:y,onSubmit:a});const{stdout:S}=Q(),k=S?.columns??80,v=getMaskedValue(e,r),b=wrapWithIndent(__name(()=>{if(!c)return"";if(!l)return c;const e={white:ne.white,green:ne.green,red:ne.red,blue:ne.blue,yellow:ne.yellow,cyan:ne.cyan,magenta:ne.magenta,gray:ne.gray,grey:ne.gray}[l];return e?e(c):c},"getColoredPrefix")()+getDisplayValue(v,t,g,o,n),k,c?.length??0);return B.createElement(K,{wrap:"wrap"},b)}var gn=__esm({"src/components/text/text-input.tsx"(){Tt(),un(),mn(),on(),__name(createStdinUpdateHandler,"createStdinUpdateHandler"),__name(createInkUpdateHandler,"createInkUpdateHandler"),__name(TextInput,"TextInput")}});async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=re(n),s=await o.metadata();if(!s.width||!s.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const a=1200;let i,c,{width:l,height:d}=s;(l>a||d>a)&&(l>d?(d=Math.round(d*a/l),l=a):(l=Math.round(l*a/d),d=a)),t.includes("png")&&s.hasAlpha?(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=i.length;return{compressedBase64:i.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:u,compressionRatio:r/u}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}var pn,hn=__esm({"src/utils/image-compression.ts"(){Tt(),__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=pn[n];if(!r)return null;const o=a(t);if(!E(o))return null;const s=S(o).toString("base64");if(!s||0===s.length)return null;if(s.length>32e6)return null;const c=await compressImageForSharing(s,r);return c?{data:c.compressedBase64,mediaType:c.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 fn=__esm({"src/utils/clipboard-image.ts"(){Tt(),hn(),pn={".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 processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};let r,o,s=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");if(s=s.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){r=e.slice(0,t.index);const s=e.slice(t.index+t[0].length);if(n){const e=s.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(o=s.slice(0,e.index))}else o=s}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:s,textBeforePaste:r,pastedContent:o}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}var yn,wn,En,Sn,kn=__esm({"src/utils/bracketed-paste.ts"(){Tt(),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode")}});function getIcon(e){if(En[e])return En[e];const t=e.split(":")[0];return En[t]?En[t]:En.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(!Sn){Sn=!0;try{y.mkdirSync(yn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${wn}\n════════════════════════════════════════════════════════════════\n\n`;y.appendFileSync(wn,t,"utf-8")}catch{}}}function dlog(e,t){if("true"===process.env.DEBUG){showStartup();try{const n=formatTime(new Date),{category:r,text:o}=parseMessage(e);let s;if(r){s=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${o}`}else s=`${n} ${En.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",y.appendFileSync(wn,s,"utf-8")}catch{}}}function dlogSection(e){if("true"===process.env.DEBUG){showStartup();try{const t=`\n──── ${e} ${"─".repeat(Math.max(0,50-e.length))}\n`;y.appendFileSync(wn,t,"utf-8")}catch{}}}var vn,bn=__esm({"src/utils/dlog.ts"(){Tt(),yn=e.join(p.homedir(),".commandcode","logs"),wn=e.join(yn,"command.log"),En={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"),Sn=!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 D.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();y.writeFileSync(t,JSON.stringify(e,null,2)),y.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!==vn)return vn;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),vn=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),vn=!0,!0;const e=await loadUserConfig();return(vn=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),vn}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error(Yt)}function getConfiguredModel(){try{const e=getConfigFile();return(parseJSON(y.readFileSync(e,"utf-8"))||{}).model??kt}catch{return kt}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}var Cn,Pn,Tn=__esm({"src/utils/user-config.ts"(){Tt(),$t(),Nt(),nn(),bn(),xn(),In(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),vn=null,__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel")}}),An=__esm({"src/components/anthropic-auth.tsx"(){Tt(),gn(),rn(),nn(),fn(),kn(),Tn(),Cn=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=z(""),[s,a]=z(null),[i,c]=z(!1),[l,d]=z(null),[u,m]=z(!0),[g,p]=z(!1),[h,f]=z(!1);H(()=>{const{url:e,verifier:t,state:n}=Zt.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=G(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||h){if(!h||t.isPasteEnd){if(h&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}o(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}},[h]);Z((e,n)=>{if(n.escape&&t(),u&&!g)if("y"!==e&&"Y"!==e)"n"!==e&&"N"!==e||t();else{if(!s)return;oe(s.url).then(()=>{p(!0),m(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),p(!0),m(!1)})}});const w=__name(async()=>{if(r.trim()&&s&&!i){c(!0),d(null);try{const t=r.split("#")[0].trim();await Zt.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),c(!1),n&&n(t)}}},"handleSubmit");return u&&!g?B.createElement(V,{flexDirection:"column"},B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,color:"cyan"},"Anthropic Authentication")),B.createElement(V,{marginBottom:1},B.createElement(K,null,"Open the Anthropic auth page?",B.createElement(K,{dimColor:!0}," (Y/n)")))):B.createElement(V,{flexDirection:"column"},B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,color:"cyan"},"Anthropic Authentication")),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"After authorizing, copy the code and paste it below:")),l&&B.createElement(V,{marginBottom:1},B.createElement(K,{color:"red"},"Error: ",l)),B.createElement(V,null,B.createElement(K,null,"Authorization code: "),B.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:y,onSubmit:w,placeholder:"Paste code here..."})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function getProviderDisplayName(e){if(!e)return"None";const t=Pn[e];return t?.displayName||e}function getProviderConfig(e){return Pn[e]}function isInternalTeamFlagPresent(){return process.argv.includes(ut)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(mt)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(y.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(Pn).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var xn=__esm({"src/utils/provider-config.ts"(){Tt(),$t(),rn(),An(),Nt(),In(),Pn={"command-code":{id:"command-code",displayName:"Command Code",description:"recommended",requiresAuth:!1},anthropic:{id:"anthropic",displayName:"Anthropic",description:"Claude Pro/Max",requiresAuth:!0,hidden:!0,authComponent:Cn,checkAuth:__name(async()=>!!await Zt.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(mt)}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 M.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,s=isInternalTeamFlagPresent();return isInternalTeamDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):s||o?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),"anthropic"):r}catch{return null}}function getIsExpandToolShortcut(e,t){const n=getIsTerminalIterm2();return!(!n||!e.shift||"O"!==t)||!(n||!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 In=__esm({"src/utils/utils.ts"(){Tt(),$t(),Nt(),Vt(),en(),xn(),Tn(),__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=w.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var $n=__esm({"src/utils/is-local-dev.ts"(){Tt(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":xt()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return ot;case"local":return st;default:return rt}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(y.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var Rn=__esm({"src/utils/telemetry/config.ts"(){Tt(),Nt(),In(),Rt(),$n(),At(),At(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}}),Dn={};function getPackageJson(){const e=import.meta.url,t=l(e),o=r(t);return JSON.parse(S(n(o,"./../package.json"),"utf8"))}__export(Dn,{getPackageJson:()=>getPackageJson});var Mn,Nn,On,Fn,Ln,_n,Un=__esm({"src/utils/package.ts"(){Tt(),__name(getPackageJson,"getPackageJson")}});function createAxiomExporter(){return new Nn({url:nt,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":it}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return On({[Fn]:at,[Ln]: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 Mn({resource:t,spanProcessors:[new _n(e)],autoDetectResources:!1})}var jn,Bn,zn,Wn,Hn,Gn=__esm({"src/utils/telemetry/sdk-factory.ts"(){Tt(),At(),Rn(),Un(),({NodeSDK:Mn}=se),({OTLPTraceExporter:Nn}=ae),({resourceFromAttributes:On}=ie),({ATTR_SERVICE_NAME:Fn,ATTR_SERVICE_VERSION:Ln}=ce),({SimpleSpanProcessor:_n}=le),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function generateSessionId(){return`sess_${ge().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return _.createHash("sha256").update(e).digest("hex").substring(0,12)}function getCliVersion(){try{const e=getPackageJson();if("string"==typeof e.version&&""!==e.version.trim())return e.version}catch{}return"unknown"}function buildSessionAttributes(e){const{sessionId:t,projectPath:n,gitBranch:r,cliVersion:o}=e;return{"session.id":t,"session.start_time":(new Date).toISOString(),"session.project_hash":hashPath(n),"session.branch_hash":r?hashPath(r):"unknown","session.cli_version":o,"session.platform":`${p.platform()}-${p.arch()}`,"session.node_version":process.version}}function startSession(){Hn={},Bn=null,zn=null,jn=generateSessionId(),Wn=Date.now();try{const e=de.getTracer(at),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:jn,projectPath:n,gitBranch:r,cliVersion:t});Bn=e.startSpan("session:cli",{attributes:o}),zn=Bn.spanContext(),Bn.end()}catch{Bn=null,zn=null}return jn}function getTraceId(){return zn?zn.traceId:null}function getSessionContext(){return zn?de.setSpanContext(me.active(),zn):me.active()}function endSession(e={}){const{status:t="success"}=e;if(zn&&Wn){const e=de.getTracer(at),n=Date.now()-Wn,r=de.setSpanContext(me.active(),zn),o=e.startSpan("session:end",{attributes:{"session.id":jn||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Hn}},r);"error"===t?o.setStatus({code:ue.ERROR}):o.setStatus({code:ue.OK}),o.end()}Bn=null,zn=null,jn=null,Wn=null,Hn={}}var qn=__esm({"src/utils/telemetry/session.ts"(){Tt(),At(),Un(),Vt(),jn=null,Bn=null,zn=null,Wn=null,Hn={},__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:ue.ERROR}):e.setStatus({code:ue.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=de.getTracer(at),o=getSessionContext();return r.startSpan(t,{attributes:n},o)}function endSpan(e){const{span:t,status:n="success"}=e;setSpanStatus(t,n),t.end()}function recordError(e){const{span:t,error:n,additionalAttributes:r}=e;if(t.recordException(n),t.setStatus({code:ue.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 Vn,Kn,Jn,Yn,Qn,Zn,Xn,er,tr,nr,rr,or,sr,ar,ir=__esm({"src/utils/telemetry/spans.ts"(){Tt(),At(),qn(),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});function getEffectiveWidth({padding:e=Yn}={}){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<=Qn)return t;if(t.includes(" && ")){const e=t.split(" && ")[0].trim();return e.length<=Qn-5?`${e} && ...`:truncateString({text:e,maxChars:Qn})}return truncateString({text:t,maxChars:Qn})}function truncateToVisualLines({output:e,maxVisualLines:t=Vn,padding:n=Yn,maxChars:r}){const o=getEffectiveWidth({padding:n}),s=r??t*o,a=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim().split("\n");let i=0,c=a.length;for(let e=0;e<a.length;e++){const n=a[e];if(0===n.trim().length)continue;const r=Math.max(1,Math.ceil(n.length/o));if(!(i+r<=t)){c=Math.max(1,e);break}i+=r}const l=c<a.length,d=a.slice(c).reduce((e,t)=>e+Math.max(1,Math.ceil(t.length/o)),0),u=a.slice(0,c).join("\n");return u.length>s?{text:`${u.slice(0,s-3)}...`,isTruncated:!0,remainingLines:d}:{text:u,isTruncated:l,remainingLines:d}}var cr=__esm({"src/utils/truncation.ts"(){Tt(),Vn=2,Kn=10,Jn=10,Yn=4,Qn=100,Zn=100,Xn=50,er=100,tr=60,nr=80,rr=1e5,or=5e4,sr=25e3,ar=200,__name(getEffectiveWidth,"getEffectiveWidth"),__name(truncateString,"truncateString"),__name(truncateCommand,"truncateCommand"),__name(truncateToVisualLines,"truncateToVisualLines")}});function isSecretKey(e){const t=e.toLowerCase();return ct.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return lt.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString2(e){return e.length<=ar?e:`${e.substring(0,ar-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>ar?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,o]of Object.entries(t))e[n]=sanitizeValue({value:o,key:n,visited:r});return e}return"[Unsupported]"}function sanitizeParams(e){const t=new WeakSet;t.add(e);const n={};for(const[r,o]of Object.entries(e))n[r]=sanitizeValue({value:o,key:r,visited:t});return n}function sanitizeEndpoint(e){return e.split("?")[0]}var lr=__esm({"src/utils/telemetry/sanitization.ts"(){Tt(),At(),cr(),__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:o}=e;return{span:t,end:__name(e=>{const s=Date.now()-n;if(t.setAttribute(r,s),"status"in e)t.setAttribute(o,e.status),e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r,errorBody:o}=e;if(t.setAttribute("http.status_code",n),o){const e="string"==typeof o?o:safeStringify(o);t.setAttribute("http.response_body",e.substring(0,dt))}r?(recordError({span:t,error:r}),endSpan({span:t,status:"error"})):endSpan({span:t,status:n>=400?"error":"success"})}},"end")}}function trackToolStart(e){const{toolName:t,params:n}=e;return createTrackingHandle({span:createSpan({name:`tool:${t}`,attributes:{"tool.name":t,"tool.params":safeStringify(n?sanitizeParams(n):{})}}),startTime:Date.now(),durationAttr:"tool.duration_ms",statusAttr:"tool.status"})}function trackError(e){const{error:t,context:n}=e,r=normalizeError(t),{component:o,heading:s,code:a,...i}=n,c={"error.type":r.name,"error.message":r.message,"error.component":o,"error.heading":s};void 0!==a&&(c["error.code"]=String(a));for(const[e,t]of Object.entries(i))null!=t&&(c[e]="object"==typeof t?safeStringify(t):String(t));const l=createSpan({name:`error:${r.name}`,attributes:c});recordError({span:l,error:r}),l.end()}function trackAPICallStart(e){const{method:t,endpoint:n}=e,r=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${r}`,attributes:{"http.method":t,"http.url":r}}),startTime:Date.now(),durationAttr:"http.duration_ms",statusAttr:"http.status"})}function getSupportId(){const e=getTraceId();return e?`req_${e}`:"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,nodeVersion:s,platform:a,arch:i}=e,c={"whoami.node_version":s,"whoami.platform":a,"whoami.arch":i,"whoami.os":`${a}-${i}`};t&&(c["whoami.user_name"]=t),n&&(c["whoami.user_id"]=n),r&&(c["whoami.org_login"]=r),o&&(c["whoami.org_id"]=o),endSpan({span:createSpan({name:"whoami",attributes:c}),status:"success"})}var dr,ur,mr,gr=__esm({"src/utils/telemetry/events.ts"(){Tt(),ir(),qn(),At(),lr(),lr(),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(trackError,"trackError"),__name(trackAPICallStart,"trackAPICallStart"),__name(getSupportId,"getSupportId"),__name(systemInfo,"systemInfo")}}),pr=__esm({"src/utils/telemetry/components.ts"(){Tt(),dr={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(mr)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(ur=createTelemetrySDK()).start(),mr=!0,!0}catch{return ur=null,mr=!1,!1}}async function shutdownTelemetry(){if(ur&&mr)try{endSession(),await ur.shutdown()}catch{}finally{ur=null,mr=!1}}function shutdownTelemetrySync(){if(mr)try{endSession()}catch{}}function isTelemetryInitialized(){return mr}var hr,fr=__esm({"src/utils/telemetry/telemetry.ts"(){Tt(),Gn(),Rn(),qn(),ir(),gr(),pr(),ur=null,mr=!1,__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized")}});function getTokenFilePath(){return e.join(h.homedir(),".commandcode",hr)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await D.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 D.mkdir(r,{recursive:!0}),await D.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await D.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 yr,wr=__esm({"src/mcp/auth/token-storage.ts"(){Tt(),$t(),bn(),hr="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")}});function fetchWithTimeout(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),yr);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var Er,Sr,kr=__esm({"src/mcp/fetch.ts"(){Tt(),yr=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),vr={};function generateRandomString(e){return _.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:_.createHash("sha256").update(e).digest("base64url")}}function escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function startCallbackServer(e,t){return new Promise((n,r)=>{let o=null,s=null;const a=new Promise((e,t)=>{o=e,s=t}),i=pe.createServer((n,r)=>{const a=new d(n.url||"/",`http://${Sr}:${e}`);if("/callback"===a.pathname){const e=a.searchParams.get("code"),n=a.searchParams.get("error"),i=a.searchParams.get("error_description");if(a.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'),s?.(new Error("OAuth state parameter mismatch"));else if(n){const e=escapeHtml(i||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`),s?.(new Error(i||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'),o?.(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'),s?.(new Error("No authorization code received")))}else r.writeHead(404),r.end("Not Found")});i.on("error",r),i.listen(e,Sr,()=>{n({server:i,getCode:__name(()=>a,"getCode")})})})}async function exchangeCodeForTokens(e,t,n,r){const o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r,client_id:e.clientId,code_verifier:n});e.clientSecret&&o.set("client_secret",e.clientSecret);const s=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!s.ok){const e=await s.text();throw new Error(`Token exchange failed: ${s.status} ${e}`)}const a=await s.json();return{accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:a.expires_in?Date.now()+1e3*a.expires_in:void 0,tokenType:a.token_type,scope:a.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 o=await r.json();return{accessToken:o.access_token,refreshToken:o.refresh_token||t,expiresAt:o.expires_in?Date.now()+1e3*o.expires_in:void 0,tokenType:o.token_type,scope:o.scope}}async function performOAuthFlow(e,t,n){const r=n?.port||Er,o=n?.timeout||12e4,s=n?.onStatus||(()=>{});let a=null;try{const n=generatePKCE(),i=generateRandomString(32),c=`http://${Sr}:${r}/callback`;s("Starting authentication server...");const{server:l,getCode:u}=await startCallbackServer(r,i);a=l;const m=new d(t.authorizationUrl);if(m.searchParams.set("response_type","code"),m.searchParams.set("client_id",t.clientId),m.searchParams.set("redirect_uri",c),m.searchParams.set("state",i),m.searchParams.set("code_challenge",n.challenge),m.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&m.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))m.searchParams.set(e,n);s("Opening browser for authentication..."),await oe(m.toString()),s("Waiting for authorization...");const g=u();let p;const h=new Promise((e,t)=>{p=setTimeout(()=>t(new Error("Authentication timed out")),o)}),f=await Promise.race([g,h]);clearTimeout(p),s("Exchanging authorization code for tokens...");const y=await exchangeCodeForTokens(t,f,n.verifier,c);return await storeTokens(e,y),s("Authentication successful!"),{success:!0,tokens:y}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{a&&a.close()}}function createRefreshCallback(e){return t=>refreshAccessToken({config:e,refreshToken:t})}__export(vr,{DEFAULT_OAUTH_CALLBACK_PORT:()=>Er,LOCALHOST_IP:()=>Sr,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var br,Cr,Pr,Tr,Ar,xr,Ir,$r,Rr,Dr,Mr,Nr,Or,Fr,Lr,_r=__esm({"src/mcp/auth/oauth-flow.ts"(){Tt(),wr(),kr(),Er=8085,Sr="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")}}),Ur=__esm({"src/components/vscode-context/ipc-client.ts"(){Tt(),bn(),br=t.join(h.homedir(),".commandcode","ide"),Cr=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),Pr=__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"),Tr=__name((e,t,n=Pr)=>{const r=new Map;for(const t of e)r.set(t.session.pid,t);let o=t;for(let e=0;e<10&&null!==o;e++){const e=r.get(o);if(e)return e;o=n(o)}return null},"findAncestorSession"),Ar=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),xr=__name((e,n)=>{try{w.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{w.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),Ir=__name((e,n={})=>{const{sessionDir:r=br,parentPidFn:o=Pr,startPid:s=process.ppid}=n;try{if(!w.existsSync(r))return null;const n=`${e}-`,a=w.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),i=[];for(const e of a)try{const n=t.join(r,e),o=JSON.parse(w.readFileSync(n,"utf-8"));if(!Cr(o.pid)){xr(n,r);continue}i.push({session:o,file:e})}catch{continue}if(0===i.length)return null;const c=Tr(i,s,o);if(c)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:c.session.socketPath,ideName:c.session.ideName}),c.session.socketPath;const l=process.cwd();let d=null,u=0;for(const{session:e}of i)for(const n of e.workspaceFolders)(l===n||l.startsWith(n+t.sep))&&n.length>u&&(d=e,u=n.length);return d&&dlog("[VSCode:IPC] Discovered session via workspace match",{socketPath:d.socketPath,ideName:d.ideName}),d?.socketPath??null}catch{return null}},"discoverSocketPath"),$r=__name(()=>{const e=Ar();return e?Ir(e):null},"resolveSocketPath"),Rr=__name(()=>({type:"request",id:j(),payload:{action:"getContext"}}),"createContextRequest"),Dr=__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"),Mr=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!Dr(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"),Nr=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??$r()}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=fe.connect(t);this.socket=r;const o=__name(()=>{r.off("error",s)},"cleanup"),s=__name(e=>{clearTimeout(a),o(),this.connected=!1,dlog("[VSCode:IPC] Connection error",{error:e.message}),n(!1)},"handleError"),a=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),o(),r.destroy(),n(!1)},e);r.on("connect",()=>{try{if(clearTimeout(a),o(),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",s)}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=Rr();return dlog("[VSCode:IPC] Requesting context",{requestId:n.id}),await new Promise(r=>{const o=__name(()=>{t.off("data",i),t.off("error",c)},"cleanup"),s=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),o(),r(null)},e);let a="";const i=__name(e=>{try{a+=e.toString();const t=a.indexOf("\n");if(-1===t)return;clearTimeout(s),o();const i=a.slice(0,t),c=Mr(Buffer.from(i),n.id);c?dlog("[VSCode:IPC] Context received",{hasActiveFile:!!c.activeFile,hasSelection:!!c.selection,openFilesCount:c.openFiles.length}):dlog("[VSCode:IPC] Invalid response received"),r(c)}catch(e){clearTimeout(s),o(),dlog("[VSCode:IPC] Error processing response",{error:e}),r(null)}},"handleData"),c=__name(e=>{clearTimeout(s),o(),dlog("[VSCode:IPC] Socket error during request",{error:e.message}),r(null)},"handleError");t.on("data",i),t.on("error",c);try{t.write(JSON.stringify(n)+"\n"),dlog("[VSCode:IPC] Request sent")}catch(e){clearTimeout(s),o(),dlog("[VSCode:IPC] Failed to send request",{error:e}),r(null)}})}catch{return 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}}}}}),jr={};function getVsixPath(){try{const e=t.dirname(l(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return w.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),Nr.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await Or(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp(`${Fr}@([\\d.]+)`,"i"));return n?{installed:!0,version:n[1]}:{installed:!1,version:null}}catch{return{installed:!1,version:null}}}async function installExtension(e){if(!e)return{success:!1,error:"No IDE detected"};const t=getVsixPath();if(!t)return{success:!1,error:"VSIX not bundled"};try{return await Or(`${e} --install-extension "${t}" --force`,{timeout:3e4}),dlog(`[IDE] Extension installed for ${e}`),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function installExtensionAsync(e){e&&installExtension(e).catch(()=>{})}async function isAutoInstallEnabled(){try{return!1!==(await loadUserConfig()).autoInstallExtension}catch{return!0}}async function ensureExtensionInstalled(){if(process.env.CI)return;const e=Ar();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:ee.green("✔"),installed:ee.green("✔"),needs_reload:ee.yellow("◌"),failed:ee.red("✖"),not_in_ide:ee.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=>ee.dim(` ${e}`)),""]}async function runIDESetup(){const e=Ar(),t=e?Lr[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new Nr,r=await n.connect(500);if(n.disconnect(),r)return{status:"connected",ide:t};const{installed:o}=await checkInstalled(e);return o?{status:"needs_reload",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:(await installExtension(e)).success?{status:"installed",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:{status:"failed",ide:t,details:[`Make sure "${e}" is available in your PATH.`,"Then run /ide to retry installation."]}}__export(jr,{detectIDE:()=>Ar,ensureExtensionInstalled:()=>ensureExtensionInstalled,formatSetupResult:()=>formatSetupResult,getExtensionStatus:()=>getExtensionStatus,installExtension:()=>installExtension,installExtensionAsync:()=>installExtensionAsync,isAutoInstallEnabled:()=>isAutoInstallEnabled,runIDESetup:()=>runIDESetup});var Br=__esm({"src/utils/ide-installer.ts"(){Tt(),Ur(),bn(),Tn(),Or=ye($),Fr="commandcode.commandcode-vscode",__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled"),Lr={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"},__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup")}});Tt(),Tt();var zr=process.argv.includes("-d")||process.argv.includes("--debug");zr&&(process.env.DEBUG="true"),zr||(process.removeAllListeners("warning"),process.on("warning",()=>{})),Tt(),Tt(),fr();var{red:Wr,yellow:Hr,dim:Gr}=ee,qr=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:o=!0,skipTelemetry:s=!1}=e;if(n){if(s||trackError({error:sanitizeErrorForTelemetry({error:n,label:"cli_error"}),context:{component:dr.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Ee.error} ${Wr(t)}`),console.log(`${Ee.error} ${Wr("ERROR →")} ${n.name}`),console.log(`${Ee.info} ${Wr("REASON →")} ${n.message}`),console.log(`${Ee.info} ${Wr("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Ee.info} ${Gr(`Request ID: ${e}`)}`),console.log(`${Gr(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Ee.warning} ${Hr(t)}\n`);if(!o)return!1;process.exit(0)}},"handleError");function handleUnhandledErrors(){process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:dr.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),qr({heading:we`CRITICAL: Unhandled Promise Rejection!
|
|
3
|
+
This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:t,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})}),process.on("uncaughtException",e=>{trackError({error:sanitizeErrorForTelemetry({error:e,label:"uncaught_exception"}),context:{component:dr.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),qr({heading:we`CRITICAL: Uncaught Exception!
|
|
4
|
+
This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}async function findAvailablePort(e=5959,t=10){for(let n=0;n<t;n++){const t=e+n;if(await checkPortAvailable(t))return t}throw new Error(`No available port found after ${t} attempts starting from port ${e}`)}async function checkPortAvailable(e){return new Promise(t=>{const n=he.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}fr(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Tt(),Tt(),$t(),Tt(),Tt(),$t(),Tt(),Tt(),Tt(),Tt(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable");var Vr=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}};function createAuthServer(e,t){let n,r;const o=new Promise((e,t)=>{n=e,r=t}),s=pe.createServer((e,o)=>{const a=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],i=e.headers.origin||"",c=a.includes(i)?i:a[0];if(o.setHeader("Access-Control-Allow-Origin",c),o.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type"),o.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return o.writeHead(204),void o.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return o.writeHead(404),void o.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return o.writeHead(405),void o.end(JSON.stringify(e))}let l="";e.on("data",t=>{l+=t.toString(),l.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(l);if(e.error){const t=e,n={success:!0};return o.writeHead(200),o.end(JSON.stringify(n)),"access_denied"===t.error?r(new Vr(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void s.close()}const a=e;if(!(a.apiKey&&a.state&&a.userId&&a.userName&&a.keyName)){const e={success:!1,error:"Missing required fields"};return o.writeHead(400),void o.end(JSON.stringify(e))}if(a.state!==t){const e={success:!1,error:"Invalid state token"};return o.writeHead(403),void o.end(JSON.stringify(e))}const i={success:!0};o.writeHead(200),o.end(JSON.stringify(i)),n(a),s.close()}catch{const e={success:!1,error:"Invalid JSON"};o.writeHead(400),o.end(JSON.stringify(e))}}),e.on("error",()=>{o.writeHead(500),o.end(JSON.stringify({success:!1,error:"Request error"}))})});return s.on("error",e=>{r(e)}),s.listen(e,"127.0.0.1"),{server:s,waitForCallback:o}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}function generateStateToken(){return _.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await oe(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:dr.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(xt()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer"),Rt(),Nt(),fr(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl");var Kr=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}};async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await D.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 D.writeFile(n,r,{mode:384}),await D.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await D.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}function getApiBaseUrl(){const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials"),Tt(),__name(getApiBaseUrl,"getApiBaseUrl"),$t(),fr();var Jr=12e4;async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${pt.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:dr.AUTH_FLOW,heading:"API key validation network error"}}),process.env.DEBUG&&console.error("API key validation network error:",e),{valid:!1,error:"network_error"}}}function sanitizeApiKey(e){const t=String.fromCharCode(27),n=e.replaceAll(t+"[200~","").replaceAll(t+"[201~","").replaceAll("[200~","").replaceAll("[201~","");return Array.from(n).filter(e=>{const t=e.charCodeAt(0);return t>31&&127!==t}).join("").trim()}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:o=Jr}=e,[s,a]=z("initializing"),[i,c]=z("Starting authentication..."),[l,d]=z(""),[u,m]=z(null),g=W(null),p=W(!1),h=W(!1),f=W(null),y=W(t),w=W(n),E=W(r);H(()=>{y.current=t,w.current=n,E.current=r});const S=G(()=>{f.current&&(clearTimeout(f.current),f.current=null),g.current&&(stopServer(g.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),g.current=null)},[]),k=G(()=>{h.current||(h.current=!0,p.current=!0,S(),E.current())},[S]),v=G((e,t)=>{h.current||(h.current=!0,S(),y.current(e,t))},[S]),b=G((e,t)=>{h.current||(h.current=!0,S(),w.current(e,t))},[S]),C=G(async e=>{const t=sanitizeApiKey(e);if(!t)return;a("validating"),c("Validating API key...");const n=await validateApiKey(t);if(p.current)return;if(h.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return a("invalid_key"),c(e),void(f.current=setTimeout(()=>{p.current||h.current||(a("manual_entry"),c("Paste a valid API key below.")),f.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(h.current)return;await storeCredentials(e),a("success"),v(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:dr.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),c("Failed to save API key. Please try again."),a("manual_entry")}},[v]);return H(()=>{let e=!0;return __name(async()=>{if(!p.current)try{const t=await findAvailablePort(5959,10);if(!e||p.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);m(r);const{server:s,waitForCallback:i}=createAuthServer(t,n);if(g.current=s,!e||p.current)return void await stopServer(s);a("waiting_browser"),c("Opening browser for authentication...");const l=await openBrowser(r);if(!e||p.current)return;if(!l)return S(),c("Could not open browser. Paste your API key below."),void a("manual_entry");c("Complete login in your browser...");const d=new Promise((e,t)=>{setTimeout(()=>{t(new Kr("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([i,d]);if(!e||p.current)return;if(h.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(h.current)return;if(await storeCredentials(n),!e||p.current||h.current)return;a("browser_success"),v(n,"browser")}catch(t){if(h.current)return;if(!e||p.current)return;if(t instanceof Vr)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:dr.AUTH_FLOW,heading:"Authorization denied by user"}}),a("denied"),void b("denied","Authorization denied by user.");S(),t instanceof Kr&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:dr.AUTH_FLOW,heading:"Browser auth timed out"}}),c("Browser auth timed out. Paste your API key below.")):(trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_failed"}),context:{component:dr.AUTH_FLOW,heading:"Browser auth failed"}}),c("Browser auth failed. Paste your API key below.")),a("manual_entry")}}catch(t){if(h.current)return;if(!e||p.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:dr.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),S(),a("manual_entry"),c("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,S()}},[o,v,b,S]),{authState:s,statusMessage:i,browserUrl:u,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:C,cancel:k,hasCompleted:h.current}}function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){switch(e){case"waiting_browser":return"Authorize in browser, or paste API key here";case"invalid_key":return"That key was invalid. Try again.";default:return"Paste your API key and press Enter"}}function getAuthUrlLabel(e){return"waiting_browser"===e?"Authenticating via:":"Get your API key from:"}__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow"),Tt(),gn(),$t(),Rt(),Tt(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel");var Yr=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const a=__name(()=>{switch(e){case"initializing":case"waiting_browser":case"validating":default:return B.createElement(De,{type:"dots"});case"browser_success":case"success":return B.createElement(K,{color:"green"},Se.tick);case"denied":case"invalid_key":return B.createElement(K,{color:"red"},Se.cross);case"manual_entry":return B.createElement(K,{color:"yellow"},Se.arrowDown);case"error":return B.createElement(K,{color:"red"},Se.warning)}},"getStatusIcon"),i=__name(()=>getAuthStatusColor(e),"getStatusColor");if("browser_success"===e||"success"===e||"denied"===e)return null;const c="initializing"===e||"waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,l=n&&("waiting_browser"===e||"manual_entry"===e);return B.createElement(V,{flexDirection:"column",paddingY:1},B.createElement(V,{marginBottom:1},B.createElement(V,{marginRight:1},a()),B.createElement(K,{color:i()},t)),c&&B.createElement(V,{flexDirection:"column"},B.createElement(V,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?"yellow":"gray",paddingX:1},B.createElement(K,{dimColor:!0},"API Key: "),B.createElement(V,{flexGrow:1},B.createElement(TextInput,{value:r,onChange:o,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},getAuthHelpText(e))),l&&B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,{dimColor:!0},getAuthUrlLabel(e)),B.createElement(K,{color:"cyan",dimColor:!0},n||getStudioAuthUrl(xt())))),"validating"===e&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"initializing"===e||"invalid_key"===e)&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Ctrl+C to cancel")))},"AuthFlowUI"),Qr=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a,cancel:i}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return Z((e,t)=>{t.ctrl&&"c"===e&&i()}),B.createElement(Yr,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey");function heading({text:e,sub:t,dim:n,green:r}){const o=t?` ${t}`:"";return r?`${ne.bgGreen(ne.black(` ${e} `))}${o}`:n?`${ne.bgBlack(ne.white(` ${e} `))}${o}`:`${ne.bold(ne.bgCyan(ne.black(` ${e} `)))}${o}`}async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=Zt.createAuthorizationUrl(),r=await $e({message:"Open the Anthropic auth page?"});if(xe(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await oe(e),console.log(),console.log(ne.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(ne.dim(" Open this URL in your browser:")),console.log(),console.log(ne.cyan(` ${e}`)),console.log(),console.log(ne.yellow(" Copy your authorization code and paste it below.")),console.log());const o=await Re({message:"Paste your authorization code:",mask:"*"});if(xe(o))return{success:!1,error:"No API key provided"};if(!o.trim())return{success:!1,error:"No authorization code provided"};const s=o.split("#")[0].trim();return await Zt.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}nn(),Rt(),Tt(),__name(heading,"heading"),xn(),Tn(),Tt(),rn(),__name(performAnthropicAuth,"performAnthropicAuth"),Tt();var Zr=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},Xr=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 M.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=Me("Checking authentication status...").start();try{const t=xt(),n=await checkAuthStatus(t);n.error&&(e.fail(ne.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(ne.red("Not authenticated")),console.log(""),console.log(`${ne.dim("Run")} ${ne.cyan("cmd auth login")} ${ne.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${ne.green(Se.tick)} ${ne.bold("Authenticated")} with ${ne.cyan("Command Code")}`),n.userName&&console.log(`${ne.dim("Logged in as")} ${ne.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(ne.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}Tt(),$t(),Nt(),Rt(),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(getUserName,"getUserName"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction");var eo=new be("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction),to=__name(({message:e})=>B.createElement(B.Fragment,null,B.createElement(K,{color:"cyan"},B.createElement(De,{type:"dots"})),B.createElement(K,null," ",e)),"LoadingIndicator"),no=__name(({message:e})=>B.createElement(B.Fragment,null,B.createElement(K,{color:"green"},Se.tick),B.createElement(K,null," ",e)),"SuccessIndicator"),ro=__name(({children:e})=>B.createElement(V,{flexDirection:"column"},B.createElement(K,null," "),B.createElement(V,null,e)),"StatusContainer");function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,a]=z("loading"),[i,c]=z(null);return H(()=>{n().then(e=>{c(e),a(o?"success":"done")})},[n,o]),H(()=>{if("done"===s&&null!==i&&r(i),"success"===s&&null!==i){const e=setTimeout(()=>r(i),100);return()=>clearTimeout(e)}},[s,i,r]),"done"===s?null:B.createElement(ro,null,"loading"===s?B.createElement(to,{message:e}):B.createElement(no,{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 ${ne.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${ne.green(Se.tick)} ${ne.bold("Already logged in")}${t}`,"",`${ne.dim("Run")} ${ne.cyan("cmd")} ${ne.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${ne.green(Se.tick)} ${ne.bold("Logged in")}${n}`,"",`${ne.dim("API key stored in")} ${ne.cyan(`~/.commandcode/${t}`)}`,`${ne.dim("Run")} ${ne.cyan("cmd")} ${ne.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 Xr(e.message):isLoginCancelled(e)?new Zr(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 Zr||e instanceof Xr}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),Pe.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await Ae({message:"Select provider",options:e});if(xe(t))throw Te(`${Se.cross} No provider selected.`),new Zr("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){Te(`${Se.cross} ${e}`)}function showAnthropicAuthNote(){Ie("Command Code authentication complete. Now authenticating with Anthropic...")}function printMessage(e){console.log(""),console.log(e),console.log("")}function renderTaskWithSpinner(e,t,n,r=!0){return new Promise(o=>{const s=__name(e=>{a(),o(e)},"handleComplete"),{unmount:a}=Y(B.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:s,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=Y(B.createElement(Qr,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__name(isGenericUserName,"isGenericUserName"),__name(isGenericUserNameForOutro,"isGenericUserNameForOutro"),__name(formatUserDisplay,"formatUserDisplay"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(isLoginSuccess,"isLoginSuccess"),__name(isLoginDenied,"isLoginDenied"),__name(isLoginCancelled,"isLoginCancelled"),__name(createLoginError,"createLoginError"),__name(processLoginResult,"processLoginResult"),__name(needsProviderSelection,"needsProviderSelection"),__name(getDefaultProvider,"getDefaultProvider"),__name(isAnthropicProvider,"isAnthropicProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage,"getErrorMessage"),__name(showAuthIntro,"showAuthIntro"),__name(promptProviderSelection,"promptProviderSelection"),__name(selectProvider,"selectProvider"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(showAnthropicAuthNote,"showAnthropicAuthNote"),__name(printMessage,"printMessage"),__name(renderTaskWithSpinner,"renderTaskWithSpinner"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow");var oo=__name(({env:e,onComplete:t})=>{const[n,r]=z("checking"),[o,s]=z(null);return H(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),H(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),B.createElement(ro,null,"checking"===n&&B.createElement(to,{message:"Checking authentication status..."}),"logged_in"===n&&B.createElement(no,{message:"Authenticated"}),"not_logged_in"===n&&B.createElement(no,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=Y(B.createElement(oo,{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=xt(),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(`${Se.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleAnthropicAuth,"handleAnthropicAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var so=new be("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction);async function safeRemoveFile(e,t){try{return await M.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"}}}Tt(),Tt(),Nt(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout");var ao=__name(()=>B.createElement(B.Fragment,null,B.createElement(K,{color:"cyan"},B.createElement(De,{type:"dots"})),B.createElement(K,null," Logging out...")),"LoadingIndicator"),io=__name(()=>B.createElement(B.Fragment,null,B.createElement(K,{color:"green"},Se.tick),B.createElement(K,null," Logged out")),"SuccessIndicator"),co=__name(({errorMessage:e})=>B.createElement(B.Fragment,null,B.createElement(K,{color:"red"},Se.cross),B.createElement(K,{color:"red"}," Logout failed: ",e)),"ErrorIndicator"),lo=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return B.createElement(ao,null);case"success":return B.createElement(io,null);case"error":return B.createElement(co,{errorMessage:t})}},"StatusDisplay"),uo=__name(({onComplete:e})=>{const[t,n]=z("loading"),[r,o]=z(""),[s,a]=z(null);return H(()=>{performLogout().then(e=>{a(e),e.success?n("success"):(o(e.error||"Unknown error"),n("error"))})},[]),H(()=>{if(("success"===t||"error"===t)&&s){const t=setTimeout(()=>e(s),100);return()=>clearTimeout(t)}},[t,s,e]),B.createElement(V,{flexDirection:"column"},B.createElement(K,null," "),B.createElement(V,null,B.createElement(lo,{status:t,errorMessage:r})))},"LogoutSpinner");function printWarnings(e){e.length>0&&(console.warn(ne.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(ne.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=Y(B.createElement(uo,{onComplete:n=>{t(),e(n)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction");var mo=new be("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction);Rt(),Nt(),new be("auth").description("Manage authentication with Command Code").addCommand(so).addCommand(mo).addCommand(eo),Tt(),$t();var go="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",po="\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 ho=getMaxLineWidth(go),fo=getMaxLineWidth(po),yo=ho+1,wo=fo+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var Eo=__name(e=>{const t=e??getTerminalWidth();return t>=yo?go:t>=wo?po:So},"getResponsiveCommandLogo"),So="⌘ CMD\n",ko=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),vo=__name(e=>{console.log(ee.white(Eo())),console.log(""),console.log(`${Se.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),bo=__name(async e=>{const t=ve.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"),Co=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.log(""),console.log(`${Se.cross} Authentication failed. Please try again with: cmd login`),!1)}catch{return!1}},"attemptLogin"),Po=__name(()=>{console.log(""),console.log(`${Se.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),To=__name(()=>{console.log(""),console.log(`${Se.info} Authentication cancelled. You can authenticate later with: cmd login`)},"showCancelledMessage");async function checkAuthAndPromptLogin(){try{if(await getAuthKey())return!0;vo(It());const{answer:e,cancelled:t}=await bo(`Would you like to sign in now? ${ee.dim("(y/n)")}: `);return t?(To(),!1):ko(e)?(console.log(""),Co()):(Po(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin"),Tt(),Tt(),$t(),Tt();var Ao=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))}};Tt(),Tt();var xo=class _APIError extends Error{static{__name(this,"APIError")}status;headers;error;code;param;type;request_id;constructor(e,t,n,r){super(_APIError.makeMessage(e,t,n)),this.status=e,this.headers=r,this.request_id=r?.["lb-request-id"];const o=t;this.error=o,this.code=o?.code,this.status=o?.status}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e)return new Io({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new $o(e,o,n,r);case 401:return new Ro(e,o,n,r);case 403:return new Do(e,o,n,r);case 404:return new Mo(e,o,n,r);case 409:return new No(e,o,n,r);case 422:return new Oo(e,o,n,r);case 429:return new Fo(e,o,n,r);default:return e>=500?new Lo(e,o,n,r):new _APIError(e,o,n,r)}}},Io=class extends xo{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)}},$o=class extends xo{static{__name(this,"BadRequestError")}status=400},Ro=class extends xo{static{__name(this,"AuthenticationError")}status=401},Do=class extends xo{static{__name(this,"PermissionDeniedError")}status=403},Mo=class extends xo{static{__name(this,"NotFoundError")}status=404},No=class extends xo{static{__name(this,"ConflictError")}status=409},Oo=class extends xo{static{__name(this,"UnprocessableEntityError")}status=422},Fo=class extends xo{static{__name(this,"RateLimitError")}status=429},Lo=class extends xo{static{__name(this,"InternalServerError")}};fr();var _o=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=await this.buildHeaders({headers:e.headers}),o=trackAPICallStart({method:e.method,endpoint:t});let s;try{s=await this.makeRequest({url:n,options:e,headers:r})}catch(e){const t=new Io({cause:e instanceof Error?e:void 0});throw o.end({statusCode:0,error:t}),t}if(!s.ok){const{error:e}=await this.handleErrorResponse({response:s});throw o.end({statusCode:s.status,error:e}),e}return o.end({statusCode:s.status}),e.stream?s.body:s.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const s=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return o&&clearTimeout(o),s}catch(e){throw o&&clearTimeout(o),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};return e.headers.forEach((e,t)=>{n[t]=e}),{error:xo.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"})}};rn(),Tt(),rn(),Tt(),Tt(),Tt(),Tt();var Uo=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()});function getPersonalSkillsDir(){return t.join(h.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return t.join(process.cwd(),".commandcode","skills")}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await M.access(n);const e=await M.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await M.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=t.join(n,e.name,"SKILL.md");await M.access(r);const o=await M.readFile(r,"utf-8"),{data:s}=Oe(o),a=Uo.parse(s);return a.name!==e.name?null:{name:a.name,description:a.description,filePath:r}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}async function loadAllSkillSummaries(){const[e,t]=await Promise.all([loadSkillSummariesFromDirectory({dir:getPersonalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir()})]);return{personal:e,project:t}}function escapeXML(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function generateSkillsXML(e){const{personal:n,project:r}=e,o=[...n,...r];return 0===o.length?"":`<available_skills>\n${o.map(e=>{const n=t.normalize(e.filePath);return`<skill>\n<name>\n${escapeXML(e.name)}\n</name>\n<description>\n${escapeXML(e.description)}\n</description>\n<location>\n${escapeXML(n)}\n</location>\n</skill>`}).join("\n")}\n</available_skills>`}function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}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()}),$t(),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),Tt(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),Tt(),Tt(),Tt(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath"),Tt();var jo=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()});var Bo=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};async function readFileContent(t){const{absolutePath:n,offset:r,limit:o}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new Bo("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=e.normalize(n);try{await D.access(s,y.constants.F_OK|y.constants.R_OK)}catch{throw new Bo(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await D.stat(s)).isFile())throw new Bo("Path does not point to a file","NOT_A_FILE");const a=getFileType(s),i=isBinaryFile(a);if(void 0!==r&&void 0===o||void 0===r&&void 0!==o)throw new Bo("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new Bo("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new Bo("Limit must be > 0","INVALID_LIMIT");try{if(i){const e=await D.readFile(s);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==r&&void 0!==o){const e=await readTextFileLines(s,r,o);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await D.readFile(s,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof Bo)throw e;throw new Bo(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var zo={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".pdf":"application/pdf",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf"};function getFileType(t){const n=e.extname(t).toLowerCase();return{".txt":"text",".md":"markdown",".csv":"csv",".log":"log",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".env":"env",".js":"javascript",".ts":"typescript",".jsx":"jsx",".tsx":"tsx",".py":"python",".java":"java",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c-header",".hpp":"cpp-header",".cs":"csharp",".go":"go",".rb":"ruby",".php":"php",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".clj":"clojure",".elm":"elm",".erl":"erlang",".ex":"elixir",".exs":"elixir",".hs":"haskell",".lua":"lua",".pl":"perl",".r":"r",".dart":"dart",".f":"fortran",".f90":"fortran",".groovy":"groovy",".jl":"julia",".m":"matlab",".sh":"shell",".bash":"bash",".zsh":"zsh",".ps1":"powershell",".sql":"sql",".vue":"vue",".svelte":"svelte",".astro":"astro",".component.ts":"angular",".module.ts":"angular",".service.ts":"angular",".razor":"razor",".cshtml":"razor",".erb":"ruby-template",".mustache":"mustache",".handlebars":"handlebars",".hbs":"handlebars",".ejs":"ejs",".pug":"pug",".liquid":"liquid",".twig":"twig",...zo}[n]||"unknown"}function isBinaryFile(e){return Object.values(zo).includes(e)}async function readTextFileLines(e,t,n){const r=(await D.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),a=r.slice(o,s);return{content:a.join("\n"),linesRead:a.length}}async function processFileReferences(t){const n=[];let r=t;const o=[...t.matchAll(/@([^\s@]+)/g)];for(const t of o){const o=t[0],s=t[1];try{const t=e.isAbsolute(s)?s:e.resolve(process.cwd(),s),a=await readFileContent({absolutePath:t});if("binary"===a.contentType)continue;const i=String(a.content),c=e.relative(process.cwd(),t),l=1e5;if(i.length>l){n.push({token:o,resolvedPath:t,content:"",tooLarge:!0});const e=`${c}`;r=r.replace(o,e);continue}n.push({token:o,resolvedPath:t,content:i});const d=`{${c}: ${i}}`;r=r.replace(o,d)}catch(e){continue}}return{displayContent:t,processedContent:r,fileReferences:n}}function reconstructContent(t,n){let r=t;for(const t of n){const n=`{${e.relative(process.cwd(),t.resolvedPath)}: ${t.content}}`;r=r.replace(t.token,n)}return r}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),Tt(),Tt();var Wo="read_file",Ho="edit_file",Go="write_file",qo="read_directory",Vo="read_multiple_files",Ko="grep",Jo="shell_command",Yo="think",Qo="todo_write",Zo="ask_user_question",Xo="kill_shell",es="web_search",ts="web_fetch",ns=__name(e=>e===es,"isWebSearchTool"),rs=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],os=__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 rs.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:ns(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),ss=["create_file","delete_file",Ho,Go,Jo],as=[Jo];function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",o=e.relative(n,t);return o.startsWith("..")?r&&t.startsWith(r)?t.replace(r,"~"):t:""===o?e.basename(t):o}function replacePathsInText(t){if(!t||"string"!=typeof t)return t;let n=t;return n=n.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,t=>e.isAbsolute(t)?toRelativePath(t):t),n=n.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),n}Tt(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText"),Tt(),Tt(),Tt();var is="2025-03-26",cs={name:"command-code",version:"1.0.0"};Promise.resolve().then(()=>(Un(),Dn)).then(({getPackageJson:e})=>{cs.version=e().version??"1.0.0"}).catch(()=>{}),Tt(),Tt();var ls=g.object({authorizationUrl:g.string(),tokenUrl:g.string(),clientId:g.string(),clientSecret:g.string().optional(),scopes:g.array(g.string()).optional()}),ds=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:ls.optional(),env:g.record(g.string(),g.string()).optional()}),us=g.object({mcpServers:g.record(g.string(),ds)});Tt(),$t();var ms="mcp.json";function getUserMcpConfigPath(){return e.join(h.homedir(),".commandcode",ms)}function getLocalMcpConfigPath(t=process.cwd()){const n=Le(t);return e.join(h.homedir(),".commandcode","projects",n,ms)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,".mcp.json")}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)}]}async function loadMcpConfig({scope:e,projectPath:t=process.cwd()}){try{const n=getMcpConfigPath({scope:e,projectPath:t}),r=await D.readFile(n,"utf-8"),o=JSON.parse(r),s=us.safeParse(o);return s.success?s.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 o=getMcpConfigPath({scope:n,projectPath:r}),s=e.dirname(o);await D.mkdir(s,{recursive:!0}),await D.writeFile(o,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:o}of t){const t=await loadMcpConfig({scope:o,projectPath:e});if(t?.mcpServers)for(const[e,s]of Object.entries(t.mcpServers))n[e]=s,r.set(e,o)}return{config:{mcpServers:n},serverScopes:r}}async function addMcpServer({name:e,serverConfig:t,scope:n,projectPath:r=process.cwd()}){let o=await loadMcpConfig({scope:n,projectPath:r});o||(o={mcpServers:{}});let s=t;if("project"===n&&t.oauth?.clientSecret){await storeClientSecret(e,t.oauth.clientSecret);const{clientSecret:n,...r}=t.oauth;s={...t,oauth:r}}o.mcpServers[e]=s,await saveMcpConfig({config:o,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),o=n.mcpServers[e],s=r.get(e);return o&&s?{config:o,scope:s}: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)}))}__name(getUserMcpConfigPath,"getUserMcpConfigPath"),__name(getLocalMcpConfigPath,"getLocalMcpConfigPath"),__name(getProjectMcpConfigPath,"getProjectMcpConfigPath"),__name(getMcpConfigPath,"getMcpConfigPath"),__name(getAllMcpConfigPaths,"getAllMcpConfigPaths"),bn(),wr(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers"),Tt();var gs=class _StdioTransport extends Fe{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=x(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 o=setTimeout(()=>{this.pendingRequests.delete(n),t(new Error("Request timed out"))},_StdioTransport.REQUEST_TIMEOUT_MS);this.pendingRequests.set(n,{resolve:__name(t=>{clearTimeout(o),e(t)},"resolve"),reject:__name(e=>{clearTimeout(o),t(e)},"reject")});const s=JSON.stringify(r)+"\n";this.process.stdin.write(s,e=>{e&&(clearTimeout(o),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)}};Tt(),wr(),kr();var ps=class _HttpTransport extends Fe{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":`${cs.name}/${cs.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(()=>(_r(),vr));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,o=setTimeout(()=>r.abort(),yr);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 o=t.headers.get("mcp-session-id");o&&(this.sessionId=o);const s=t.headers.get("content-type")||"",a=await t.text();if(s.includes("text/event-stream")||a.startsWith("event:")||a.startsWith("data:")){const e=this.parseSSEResponse(a);if(e)return e;throw new Error("Failed to parse SSE response")}return JSON.parse(a)}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw new Error("Request timed out");throw e}finally{clearTimeout(o)}}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,o=setTimeout(()=>r.abort(),yr);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(o)}}async close(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.isConnected=!1,this.emit("close")}get connected(){return this.isConnected}},hs=class extends Fe{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,o]of Object.entries(t.mcpServers)){if(!o.enabled)continue;const t=n.get(e);r.push(this.connectServer(e,o,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 gs?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?gs.fromConfig(e):ps.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:is,capabilities:{roots:{}},clientInfo:cs});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 o=await r.transport.request("tools/call",{name:t,arguments:n});if(o.error)throw new Error(`Tool call failed: ${o.error.message}`);return o.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}},fs=null;function getMcpConnectionManager(){return fs||(fs=new hs),fs}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),o=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:o,...r.isError&&{error:o}}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}__name(getMcpConnectionManager,"getMcpConnectionManager"),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool"),cr();var ys=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()})}),ws=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(ys).optional().default([])}),Es=ws.extend({role:g.literal("user")}),Ss=ws.extend({role:g.literal("assistant")}),ks=ws.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'"}),vs=ws.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'"}),bs=ws.extend({role:g.literal("system")}),Cs=ws.extend({role:g.literal("error")}),Ps=ws.extend({role:g.literal("info")}),Ts=ws.extend({role:g.literal("taste-onboarding")}),As=ws.extend({role:g.literal("command-result"),hasError:g.boolean().optional(),details:g.string().optional()}),xs=ws.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()}),Is=g.discriminatedUnion("role",[Es,Ss,ks,vs,bs,Cs,Ps,Ts,As,xs]),$s=__name((e,t)=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),Rs=__name((e,t)=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),Ds=__name(e=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),Ms=__name((e,t,n)=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Ns=__name(e=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),Os=__name(e=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Fs=__name(e=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),Ls=__name(()=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),_s=__name((e,t=!1,n)=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),Us=__name((e,t,n)=>Is.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),js=__name(({name:e,input:t})=>{const n=Date.now();return Is.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"),Bs=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return Is.parse(n)},"updateEntryWithOutput"),zs=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),Ws=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),Hs=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),Gs=["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…"],qs=__name(()=>Gs[Math.floor(Math.random()*Gs.length)],"getRandomLLMStatus"),Vs=__name(e=>{switch(e){case Wo:return"Read";case Ho:return"Edit";case Go:return"Write";case qo:return"List";case Vo:return"Read Multiple";case Ko:return"Search";case Jo:return"Shell";case Qo:return"Todos";case Yo:return"Thinking…";case es:return"Web Search";case ts:return"Web Fetch";case Zo:return"Question";case"explore":return"Explore";case Xo:return"Kill Shell";default:if(isMcpTool(e)){const t=parseMcpToolName(e);if(t){const e=t.toolName.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase());return`${t.serverName}: ${e} (MCP)`}}return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),Ks=__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:tr})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),Js=__name((e,t)=>{try{switch(e){case Wo:case Go:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case Ho:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case qo:return toRelativePath(t.path||"directory");case Ko:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Jo: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 Qo:let o;try{o="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=Ys(o);return`${e?e.length:0} items`}catch{return"items"}case Yo:return t.content||"planning";case Vo:const s=t.include||[];return Array.isArray(s)?s.join(", "):"multiple files";case es:return t.query||"search";case ts:return t.url||"fetch";case Zo:return"User answered questions";case Xo:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case"enter_plan_mode":case"exit_plan_mode":return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return Ks(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:nr})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),Ys=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput");function formatOutput(e){const t=[];if(void 0!==e.linesRead)t.push(`Read ${e.linesRead} lines`);else if("binary"===e.contentType)t.push(`Binary file: ${e.size} bytes`);else{const n=e.content?String(e.content).split("\n").length:0;t.push(`Read ${n} lines`)}return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}Tt(),Tt(),Tt(),__name(formatOutput,"formatOutput");var Qs={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=jo.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while reading file`}},"execute")};Tt(),Tt();var Zs=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()}),Tt(),Tt(),Tt();var Xs=g.object({backupFileName:g.string().nullable(),version:g.number().int().positive(),backupTime:g.string().datetime()}),ea=g.object({messageId:g.string().uuid(),trackedFileBackups:g.record(g.string(),Xs),timestamp:g.string().datetime()});g.object({type:g.literal("file-history-snapshot"),messageId:g.string().uuid(),snapshot:ea,isSnapshotUpdate:g.boolean()}),g.object({maxFileSize:g.number().int().positive().default(10485760),retentionDays:g.number().int().positive().default(30)});var ta=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`${U.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(h.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 M.statfs(t);return e.bavail*e.bsize}catch{return-1}}async function hasEnoughDiskSpace(e){const{fileSizeBytes:t,targetPath:n}=e,r=2*t,o=await getAvailableDiskSpace({targetPath:n});return-1===o||o>=r}async function ensureDirectoryExists(e){const{dirPath:t}=e;await M.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await M.writeFile(r,n);const e=await M.stat(r),o="string"==typeof n?Buffer.byteLength(n,"utf-8"):n.length;if(e.size!==o)throw new Error(`Write verification failed: expected ${o} bytes, got ${e.size}`);await M.rename(r,t)}catch(e){try{await M.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await M.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await M.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),o=Math.floor(r/60),s=Math.floor(o/60),a=Math.floor(s/24);return a>0?`${a}d ago`:s>0?`${s}h ago`:o>0?`${o}m ago`:"just now"}function getFileName(e){const{filePath:n}=e;return t.basename(n)}function isWithinRetentionPeriod(e){const{timestamp:t,retentionDays:n}=e,r=new Date(t).getTime();return Date.now()-r<=24*n*60*60*1e3}Tt(),Tt(),$t(),__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"),fr();var na={maxFileSize:10485760,retentionDays:30},ra=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...na,...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 M.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,o=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const s=getBackupFilePath({sessionId:this.sessionId,backupFileName:o});await atomicWriteFile({filePath:s,content:e});const a={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,a),this.trackedState.versions.set(t,n),{success:!0,backup:a,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:dr.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 M.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new ta(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:dr.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await M.readFile(r);await atomicWriteFile({filePath:t,content:o})}async verifyRestoreOperation(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName){if(!await fileExists({filePath:t}))return{canRestore:!0};try{return await M.access(t,M.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 M.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await M.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await M.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}};Tt(),cr(),fr();var oa=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new ra({sessionId:t,config:r}),this.sessionStore=n||null,this.snapshots=[],this.config={maxFileSize:r?.maxFileSize||10485760,retentionDays:r?.retentionDays||30}}getFileHistoryManager(){return this.fileHistoryManager}setSessionStore(e){const{sessionStore:t}=e;this.sessionStore=t}async backupFile(e){const{filePath:t}=e,n=await this.fileHistoryManager.backupFile({filePath:t,sessionId:this.fileHistoryManager.getSessionId()});if(n.success&&this.snapshots.length>0){const e=this.snapshots[this.snapshots.length-1];e.trackedFileBackups=this.fileHistoryManager.getTrackedFileBackups(),this.sessionStore&&this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0}).catch(()=>{})}return{success:n.success,backup:n.backup}}async createSnapshot(e){const{messageId:t}=e,n={messageId:t,trackedFileBackups:{},timestamp:getCurrentTimestamp()};return this.snapshots.push(n),this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:n,isUpdate:!1}),n}async updateCurrentSnapshot(){if(0===this.snapshots.length)return;const e=this.snapshots[this.snapshots.length-1],t=this.fileHistoryManager.getTrackedFileBackups(),n=this.snapshots.length>1?this.snapshots[this.snapshots.length-2]:null,r=n?.trackedFileBackups||{},o={};for(const[e,n]of Object.entries(t)){const t=r[e];(!t||t.version!==n.version||t.backupFileName!==n.backupFileName)&&(o[e]=n)}e.trackedFileBackups=o,this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0})}listCheckpoints(){const e=[];for(let t=0;t<this.snapshots.length;t++){const n=this.snapshots[t];t>0&&this.snapshots[t-1];let r="";if(this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:n.messageId}),t=this.sessionStore.getMessageAtIndex({index:e});t&&(r=truncateString({text:t.content,maxChars:100}))}const o=Object.keys(n.trackedFileBackups);let s=null;if(o.length>0){const e=o[0];n.trackedFileBackups[e]&&(s={additions:0,deletions:0,fileName:getFileName({filePath:e})})}e.push({messageId:n.messageId,timestamp:n.timestamp,userPrompt:r,fileCount:Object.keys(n.trackedFileBackups).length,filesModified:o,codeChanges:s})}return e.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime())}getSnapshot(e){const{messageId:t}=e;return this.snapshots.find(e=>e.messageId===t)||null}async restore(e){const{messageId:t,mode:n}=e;if(!this.getSnapshot({messageId:t}))return{success:!1,error:"Snapshot not found",filesRestored:0,filesDeleted:0,messagesRemoved:0};const r=this.snapshots.findIndex(e=>e.messageId===t);let o=0,s=0,a=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return trackError({error:sanitizeErrorForTelemetry({error:new Error(`Restore verification failed:\n${t.join("\n")}`),label:"restore_verification_failed"}),context:{component:dr.CHECKPOINT_MANAGER,heading:"Checkpoint restore verification failed","checkpoint.failures":t.length}}),{success:!1,error:`Restore verification failed:\n${t.join("\n")}`,filesRestored:0,filesDeleted:0,messagesRemoved:0};for(const t of e)await this.fileHistoryManager.restoreFile({filePath:t.filePath,backup:t.backup}),null===t.backup.backupFileName?s++:o++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(a=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const i=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&i.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&i.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:i}),{success:!0,filesRestored:o,filesDeleted:s,messagesRemoved:a}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}};Tt();var sa=null;function initializeCheckpointService(e){const{sessionId:t}=e;return sa=new oa({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return sa?sa.backupFile({filePath:t}):{success:!0,backup:null}}function createFileEditError(e,t){const n=new Error(e);return n.name="FileEditError",n.code=t,n}async function editFile(t){const{filePath:n,oldValue:r,newValue:o,replaceAll:s=!1,replacementCount:a=1}=t;if(!n)throw createFileEditError("filePath is required","INVALID_PATH");if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!r)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==o)throw createFileEditError("newValue is required","INVALID_INPUT");if(!s&&a<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await k.access(n,v.F_OK|v.R_OK|v.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${n}`,"FILE_ACCESS_ERROR")}let i;try{const e=await readFileContent({absolutePath:n});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");i=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const c=(i.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===c)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let l,d;if(s)l=c;else if(l=a,l>c)throw createFileEditError(`Expected ${l} replacements, but only found ${c} occurrences`,"INSUFFICIENT_MATCHES");let u=0;if(s||l===c)d=i.split(r).join(o),u=c;else{d=i;for(let e=0;e<l;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+o+d.substring(e+r.length),u++)}}if(0===u)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await k.writeFile(n,d,"utf-8"),{path:n,replacementsCount:u,oldContent:i,newContent:d}}catch(e){throw createFileEditError(`Failed to write file: ${e instanceof Error?e.message:"Unknown error"}`,"WRITE_ERROR")}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function formatOutput2(e){const t=1!==e.replacementsCount?"s":"",n=`Edited ${e.path} (${e.replacementsCount} replacement${t})`;return e.newContent.length<500?`${n}\n\n${e.newContent}`:n}__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit"),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp"),Tt(),__name(formatOutput2,"formatOutput");var aa={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=Zs.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while editing file`}},"execute")};Tt(),Tt();var ia=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())});var ca=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}};async function readDirectory(t){const{path:n,exclude:r=[],respectGitIgnore:o=!1}=t;if(!e.isAbsolute(n))throw new ca("Path must be absolute, not relative","INVALID_PATH");try{if(!(await D.stat(n)).isDirectory())throw new ca("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof ca)throw e;throw new ca(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await D.readdir(n);let s=[];o&&(s=await loadGitIgnorePatterns(n));const a=[...r,...s],i=[],c=[];for(const r of t){if(shouldIgnoreEntry(r,a))continue;const t=e.join(n,r);try{const e=await D.stat(t);e.isDirectory()?c.push(r):e.isFile()&&i.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:i.sort(),directories:c.sort()}}catch(e){if(e instanceof ca)throw e;throw new ca(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(t){const n=[];try{if(!await isInGitRepository(t))return n;let r=e.resolve(t);const o=await findGitRoot(t);for(;r&&isWithinGitRoot(r,o);){const t=e.join(r,".gitignore");try{const e=(await D.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch(e){}const o=e.dirname(r);if(o===r)break;r=o}}catch(e){}return n}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await D.stat(t)).isDirectory())return n}catch{}const t=e.dirname(n);if(t===n)throw new Error("Not in a git repository");n=t}}function isWithinGitRoot(t,n){const r=e.resolve(t),o=e.resolve(n);return"win32"===process.platform?r.toLowerCase().startsWith(o.toLowerCase()):r.startsWith(o)}function shouldIgnoreEntry(e,t){for(const n of t)if(_e(e,n))return!0;return!1}function formatOutput3(e){const t=e.directories.length+e.files.length,n=[];return n.push(`Found ${t} items (${e.directories.length} dirs, ${e.files.length} files)`),e.directories.length>0&&(n.push("Directories:"),e.directories.forEach(e=>n.push(` ${e}/`))),e.files.length>0&&(n.push("Files:"),e.files.forEach(e=>n.push(` ${e}`))),0===t&&n.push("(empty directory)"),n.join("\n")}Tt(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),Tt(),__name(formatOutput3,"formatOutput");var la={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=ia.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while reading directory`}},"execute")};Tt(),Tt();var da=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")});async function writeFile4({filePath:e,content:n}){const o=e.startsWith("~/")?t.join(h.homedir(),e.slice(2)):e;if(!s(o))throw new Error(`Invalid file path: '${o}'. Only absolute paths are supported.`);try{const e=r(o);return E(e)||await N(e,{recursive:!0}),await backupFileBeforeEdit({filePath:o}),await O(o,n,"utf-8"),{path:o,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 '${o}': ${t}`)}}function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}g.object({success:g.boolean(),message:g.string(),path:g.string().optional()}),Tt(),__name(writeFile4,"writeFile"),Tt(),__name(formatOutput4,"formatOutput");var ua={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=da.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")};Tt(),Tt();var ma=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")}),ga=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(ga)});var pa=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}};Tt();var ha=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const o=new Set;for(const s of e)try{(await Ue(s,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>o.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${s}": ${e}`)}return Array.from(o).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:n,exclude:r=[],gitIgnore:o=!0,defaultExclude:s=!0,targetDirectory:a=process.cwd()}=e;if(!n||0===n.length)throw new pa("At least one include pattern must be provided","NO_PATTERNS");const i=t.resolve(a),c={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];s&&e.push(...ha);const a=await findMatchingFiles({include:n,exclude:e,gitIgnore:o,targetDirectory:i});for(const e of a)try{const n=t.resolve(i,e),r=await readFileContent({absolutePath:n}),o=processFileResult({content:r,filePath:e});c.fileDetails.push(o),c.content+=`\n// File: ${e} (${r.fileType})\n`,c.content+=o.content,c.content+="\n",c.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);c.errors.push({file:e,error:n}),c.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return c}catch(e){if(e instanceof pa)throw e;throw new pa(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getReadSummary(e){return{totalFiles:e.fileDetails.length,successfulReads:e.filesRead.length,failedReads:e.errors.length,totalSize:e.fileDetails.reduce((e,t)=>e+t.size,0),fileTypesCounts:e.fileDetails.reduce((e,t)=>(e[t.fileType]=(e[t.fileType]||0)+1,e),{}),contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];return n.push(`Read ${t.successfulReads}/${t.totalFiles} files (${t.totalSize} bytes)`),e.errors.length>0&&(n.push("\nErrors:"),e.errors.forEach(e=>n.push(` - ${e.file}: ${e.error}`))),n.push("\n--- File Contents ---"),n.push(e.content),n.join("\n")}__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles"),Tt(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var fa={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=ma.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while reading multiple files`}},"execute")};Tt(),Tt();var ya=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 o=x(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",a="";o.stdout?.on("data",e=>{try{const t=e.toString();if(s.length+t.length>rr)return a="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",void o.kill("SIGTERM");s+=t}catch(e){a+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,o.kill("SIGTERM")}}),o.stderr?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>or)return void(a+="\n[Error output truncated: too large]");a+=t}catch(e){a+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),o.on("close",e=>{0===e?n(s):1!==e||a?r(new Error(a||`Command failed with exit code ${e}`)):n("")}),o.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,o]=t;return{file:n,line:parseInt(r,10),column:1,content:o.trim(),match:o.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",o=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)o.splice(-1,0,"--glob",e);o.splice(-1,0,"--glob","!node_modules/**"),o.splice(-1,0,"--glob","!.git/**"),o.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:o,command:"rg"})}catch(s){if(!(s instanceof Error&&s.message.includes("ENOENT")))throw s;if(r="grep",o=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)o.splice(-1,0,"--include",e);o.splice(-1,0,"--exclude-dir=node_modules"),o.splice(-1,0,"--exclude-dir=.git"),o.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:o,command:"grep"})}if(!e.trim())return[];const s=e.trim().split("\n"),a=[];for(const e of s){const t=parseGrepLine(e);t&&a.push(t)}return a}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}Tt(),cr(),__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),Tt(),__name(formatGrepResults,"formatGrepResults");var wa={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=ya.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while searching files`}},"execute")};Tt(),Tt();var Ea=g.object({pattern:g.string().min(1,"Pattern is required"),path:g.string().optional()}),Sa=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 Sa("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new Sa("Search path must be within the current working directory or an added directory","INVALID_PATH");const o=await Ue(n,{cwd:e,ignore:vt,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),s=await Promise.all(o.map(async n=>{const r=t.join(e,n);try{return{file:n,mtime:(await M.stat(r)).mtimeMs}}catch{return{file:n,mtime:0}}}));return s.sort((e,t)=>t.mtime-e.mtime),{files:s.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof Sa)throw e;if(e instanceof Error)throw new Sa(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new Sa("Unknown error occurred during file search","UNKNOWN_ERROR")}}function formatGlobResults(e){if(0===e.files.length)return"No files found matching pattern";const t=[],n=e.files.length;t.push(`Found ${n} file${1!==n?"s":""}`);for(const n of e.files)t.push(` ${n}`);return t.join("\n")}Tt(),$t(),Ot(),__name(globSearch,"globSearch"),Tt(),__name(formatGlobResults,"formatGlobResults");var ka={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=Ea.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while finding files`}},"execute")};Tt(),Tt();var va=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())}),ba=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,a){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=a}};async function executeShellCommand(t){const{command:n,args:r=[],directory:o,timeout:s=3e4}=t,a=Date.now();if(!n.trim())throw new ba("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(e.isAbsolute(o))throw new ba("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=e.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await M.stat(i)).isDirectory())throw new ba(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof ba)throw e;throw new ba(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:i,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((t,o)=>{let i="",c="",l=!1;const d=r.length>0?je([n,...r]):n,u=setTimeout(()=>{if(!l){m.kill("SIGTERM");const e=Date.now()-a;o(new ba(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",i,c,e))}},s),m=x(d,[],e);m.stdout?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>rr)return c="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void m.kill("SIGTERM");i+=t}catch(e){c+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,m.kill("SIGTERM")}}),m.stderr?.on("data",e=>{try{const t=e.toString();if(c.length+t.length>or)return void(c+="\n[Error output truncated: too large]");c+=t}catch(e){c+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),m.on("close",(e,n)=>{l=!0,clearTimeout(u);const r=Date.now()-a;0===e?t({stdout:i.trim(),stderr:c.trim(),exitCode:e,signal:n,duration:r}):o(new ba(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,i.trim(),c.trim(),r))}),m.on("error",e=>{l=!0,clearTimeout(u);const t=Date.now()-a;o(new ba(`Failed to start command: ${e.message}`,"START_FAILED",null,null,i.trim(),c.trim(),t))})})}catch(e){if(e instanceof ba)throw e;throw new ba(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}function formatShellCommandResult(e){const t=[];return 0===e.exitCode||null===e.exitCode||t.push(`Exit code: ${e.exitCode}`),e.signal&&t.push(`Signal: ${e.signal}`),e.stdout&&t.push(e.stdout),e.stderr&&t.push(e.stderr),t.join("\n")}Tt(),cr(),__name(executeShellCommand,"executeShellCommand"),Tt(),__name(formatShellCommandResult,"formatShellCommandResult");var Ca={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=va.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${Se.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${Se.cross} Error: ${e.message}`}return`${Se.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}Tt(),Tt(),__name(think,"think");var Pa={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)}Tt(),Tt(),__name(todoWrite,"todoWrite");var Ta={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"})}}function isErrorResponse(e){return"error"in e&&"string"==typeof e.error}function formatOutput6(e){const{result:t,params:n}=e;if(isErrorResponse(t))return`Error: ${t.error}`;if(!t.answers||0===t.answers.length)return"User declined to answer questions";const r=t.answers.filter(e=>e.selectedOptions&&Array.isArray(e.selectedOptions)&&e.selectedOptions.length>0);if(0===r.length)return"User declined to answer questions";const o=[];return r.forEach(e=>{let t=`Question ${e.questionIndex+1}`;n?.questions?.[e.questionIndex]&&(t=n.questions[e.questionIndex].question||t);const r=e.selectedOptions.join(", ");o.push(`${t} → ${r}`)}),o.join("\n")}Tt(),Tt(),__name(askUserQuestion,"askUserQuestion"),Tt(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var Aa={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")};Tt(),Tt();var xa=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"}),Ia=class extends Error{static{__name(this,"KillshellError")}code;pid;port;constructor(e,t,n,r){super(e),this.name="KillshellError",this.code=t,this.pid=n,this.port=r}};function isUnixLike(){const e=process.platform;return"darwin"===e||"linux"===e}function isWindows(){return"win32"===process.platform}async function executeCommand(e,t){return new Promise((n,r)=>{const o=x(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let s="",a="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{a+=e.toString()}),o.on("close",e=>{0===e?n(s.trim()):r(new Error(a.trim()||s.trim()))}),o.on("error",e=>{r(e)})})}async function findPidByPort(e){try{if(isUnixLike()){const t=(await executeCommand("lsof",["-ti",`:${e}`,"-sTCP:LISTEN"])).trim().split("\n")[0];if(!t||!/^\d+$/.test(t))return null;const n=parseInt(t,10);return isNaN(n)?null:n}if(isWindows()){const t=(await executeCommand("netstat",["-ano"])).split("\n");for(const n of t){const t=n.trim();if(!t)continue;const r=t.split(/\s+/);if(r.length<5)continue;if("LISTENING"!==r[3])continue;const o=r[1].match(/:(\d+)$/);if(!o)continue;const s=parseInt(o[1],10);if(isNaN(s)||s!==e)continue;const a=parseInt(r[r.length-1],10);if(!isNaN(a))return a}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new Ia(`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 Ia("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 Ia(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}function formatKillshellResult(e){const t=[];return t.push(`${Se.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}Tt(),__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"),Tt(),__name(formatKillshellResult,"formatKillshellResult");var $a={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=xa.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?`${Se.cross} Permission denied: Process termination was not approved`:formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`${Se.cross} Error: ${e.message}`:`${Se.cross} Error: Unknown error occurred while killing process`}},"execute")};Tt();var Ra={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")};Tt();var Da={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")};Tt(),Tt(),Tt(),Tt(),Tt(),$t(),Tt(),Tt();var Ma=["explore","plan","review","general"],Na=[{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&&Ma.includes(e.toLowerCase())}function getRootAgentDir(){return t.join(h.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await M.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await M.readFile(o,"utf-8"),{data:a,content:i}=Oe(s),c=a.name||r.replace(".md","");if(isReservedAgentName(c))return null;let l=a.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:c,description:a.description||"",tools:l,systemPrompt:i.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}}async function loadAllAgents(){const[e,t]=await Promise.all([loadAgentsFromDirectory(getRootAgentDir(),"personal"),loadAgentsFromDirectory(getLocalAgentDir(),"project")]);return{personal:e,project:t}}__name(isReservedAgentName,"isReservedAgentName"),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents"),Tt(),$t(),rn(),In(),Vt(),Tt(),$t(),rn(),Tt(),$t(),fr(),bn(),Tt();var Oa=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext"),Fa=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(h.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Le(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const n=_SessionManager.getCurrentProjectDirName();this.projectPath=t.join(_SessionManager.getProjectsBasePath(),n),this.sessionFilePath=t.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=I("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await M.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:dr.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await M.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{if(0===e.length)return;const n=JSON.stringify(e);if(n===this.lastSavedMessagesHash)return;await this.initializeProject();const r=[];for(const n of e){const e=crypto.randomUUID(),o={id:e,timestamp:n.meta.timestamp,sessionId:this.sessionId,parentId:this.lastMessageId,role:n.message.role,content:n.message.content,gitBranch:this.gitBranch,metadata:{...n.meta,...t?.metadata||{}}};r.push(JSON.stringify(o)),this.lastMessageId=e}await M.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 M.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let n=0;for(const r of e)try{const e=JSON.parse(r);"user"!==e.role&&"assistant"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}})}catch(e){n++,console.error("Error parsing session line:",e)}return{messages:t,corruptedLines:n,totalLines:e.length}}catch(e){return console.error("Error loading messages:",e),{messages:[],corruptedLines:0,totalLines:0}}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),o=crypto.randomUUID();if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n=Oa(n),n&&t.push({id:o,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)t.push({id:o,timestamp:r,role:"assistant",input:e.content,images:[]});else if(Array.isArray(e.content)){for(const r of e.content)if("text"===r.type)n+=r.text;else if("tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=Js(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=Js(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 M.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 M.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await M.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 M.access(n)}catch{return[]}const e=(await M.readdir(n)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),r=[];for(const o of e){const e=o.replace(".jsonl",""),s=t.join(n,o);try{const t=await M.stat(s),o=(await M.readFile(s,"utf-8")).trim().split("\n").filter(e=>e.trim());if(o.length>0){let s="",a="";const i=JSON.parse(o[0]);i.gitBranch&&(a=i.gitBranch);for(const e of o){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)s=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){s=e.text;break}}else t.content?.input&&(s=t.content.input);if(s)break}}s=Oa(s);const c=await _SessionManager.loadSessionMetaForId(e,n),l=c?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:s||"No messages",title:l||void 0,messageCount:o.length,projectPath:n,gitBranch:a||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return r.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const n=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await M.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 M.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 M.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await M.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 M.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 M.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 M.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const o=n.findIndex(e=>e.messageId===t.messageId);-1!==o?n[o]=e:n.push(e);const s=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await M.writeFile(r,s)}else await M.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 M.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 M.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),o=e.findIndex(e=>e.messageId===t);if(-1===o)return;const s=(n?e.slice(0,o):e.slice(0,o+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await M.writeFile(r,s)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let o="";if("string"==typeof r.message.content)o=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(o+=e.text);return o=Oa(o),{messageId:r.meta.messageId||crypto.randomUUID(),content:o}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return r.length>0&&await this.saveMessages(r),r}};Vt(),Tn(),In(),bn();var La=new Map,_a=null;function getRequest(){return _a||(_a=new _o({baseUrl:getApiBaseUrl()})),_a}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:wt,max_tokens:80,temperature:.3,stream:!0},threadId:crypto.randomUUID()}}async function getAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced();let n;e===yt.ANTHROPIC&&(n=await Zt.getValidAccessToken(),validateOAuthToken({token:n,provider:e}));const r={[gt.PROJECT_SLUG]:Fa.getCurrentProjectDirName(),[gt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(r[gt.OAUTH_TOKEN]=`Bearer ${n}`),r}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=La.get(n);if(r)return La.delete(n),La.set(n,r),dlog(`[ToolDescription] cache hit for ${e}: "${r}"`),r;dlog(`[ToolDescription] generating for ${e}`);try{const e=getRequest(),r=await getAuthHeaders(),o=buildRequestBody(createPrompt(t));dlog(`[ToolDescription] calling ${pt.ALPHA.GENERATE} with model: ${wt}`);const s=e.post({endpoint:pt.ALPHA.GENERATE,body:o,headers:r,stream:!0}),a=await Promise.race([s,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),5e3))]);if(!a)return dlog("[ToolDescription] no response stream"),null;dlog("[ToolDescription] got response stream");const i=Be.fromReadableStream(a);let c="",l=null;if(i.on("text",e=>{c+=e}),i.on("error",e=>{l=e}),await i.finalMessage(),l)throw l;dlog(`[ToolDescription] raw response: "${c}"`);const d=cleanDescription(c);if(d){if(La.size>=100){const e=La.keys().next().value;void 0!==e&&La.delete(e)}La.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,200)}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.\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();t.length>0&&(t=t.charAt(0).toUpperCase()+t.slice(1));const n=t.split(/\s+/);return n.length<3?null:(n.length>12&&(t=n.slice(0,12).join(" ")),t.length>50&&(t=`${t.slice(0,47).trimEnd()}...`),t)}function buildFallbackDescription(e){const t=`${e.command||""} ${Array.isArray(e.args)?e.args.join(" "):e.args||""}`.trim();return t?t.length>50?`${t.slice(0,47)}...`:t:"Run shell command"}function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=h.homedir(),o=n.startsWith("~/")?t.join(r,n.slice(2)):n,s=t.resolve(o),a=t.join(r,".commandcode","plans");return s.startsWith(a+t.sep)||s===a}__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"),__name(buildFallbackDescription,"buildFallbackDescription"),Tt(),Tt(),$t(),__name(isPlanPath,"isPlanPath");var Ua=["edit_file","delete_file","shell_command","todo_write","kill_shell"],ja=["exit_plan_mode"],Ba=["enter_plan_mode"];function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!ja.includes(e.name)):"plan"===n?t.filter(e=>!Ua.includes(e.name)&&!Ba.includes(e.name)):t.filter(e=>!ja.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 Ua.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.`}}__name(getToolsForMode,"getToolsForMode"),__name(isToolAllowedInMode,"isToolAllowedInMode"),Tt(),cr();var za=sr,Wa=2e5;function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(1.1*t));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=1.1*estimateTextTokens(JSON.stringify(n.input)));else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/3.5;const n=.1*e.split(/\s+/).length;return Math.max(0,Math.ceil(t-n))}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>za}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?(estimateTokens(e),"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."):e}function calculateUsageFromResponse(e){return(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.output_tokens||0)}function sleep(e){const{delay:t,signal:n}=e;return new Promise((e,r)=>{if(n?.aborted)return r(new Error("Interrupted by user"));const o=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(o),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(function getOversizedOutputError(e,t){return"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."},"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),Tt(),__name(sleep,"sleep"),Tt(),bn();var Ha=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${Se.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${Se.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${Se.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${Se.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}};function getEnterpriseMemoryPath(){switch(p.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=p.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 o=getUserMemoryPath();return t.push({type:"user",path:o,exists:E(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return E(e)&&T(e).isFile()?await D.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}async function processImports(t,n,r=0,o=5){if(r>=o)return t;const s=[],a=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(s.push(e),`__CODE_BLOCK_${s.length-1}__`)),i=Array.from(a.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let c=a;for(const t of i){const s=t[1];let a=s;s.startsWith("~/")?a=e.join(p.homedir(),s.slice(2)):e.isAbsolute(s)||(a=e.resolve(e.dirname(n),s));const i=await loadMemoryFile(a);if(i){const e=await processImports(i,a,r+1,o);c=c.replace(t[0],`\n# Imported from ${s}\n${e}\n`)}}return c=c.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>s[parseInt(t)]),c}async function loadAllMemories(t,n){const r=new Map,o=getEnterpriseMemoryPath();if(E(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const s=getUserMemoryPath();if(E(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const a=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of a)if(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 o of n){const n=e.isAbsolute(o)?e.dirname(o):e.dirname(e.resolve(t,o));if(n.startsWith(t)&&n!==t){const o=[];let s=n;for(;s.startsWith(t)&&s!==t;)o.push(s),s=e.dirname(s);for(const t of o.reverse()){const n=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of n)if(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 D.mkdir(r,{recursive:!0}),E(t)||await D.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const o=x(n,[t],{stdio:"inherit",shell:!0});o.on("exit",t=>{0===t?e():r(new Error(`Editor exited with code ${t}`))}),o.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),r(e)})})}async function initProjectMemory(t){const n=e.join(t,"AGENTS.md");return E(n)||await D.writeFile(n,"# Memory\n\n## Project Overview\nSee @README.md for project overview and @package.json for available npm/pnpm commands for this project.\n\n## Code Style Guidelines\n- Use descriptive variable names\n- Follow existing patterns in the codebase\n- Extract complex conditions into meaningful boolean variables\n\n## Architecture Notes\nAdd important architectural decisions and patterns here.\n\n## Common Workflows\nDocument frequently used workflows and commands here.\n","utf-8"),n}async function getMemoryContent(t){try{const n=process.cwd(),r=await loadAllMemories(n,t);if(0===r.size)return null;const o=[],s=getEnterpriseMemoryPath(),a=getUserMemoryPath(),i=[e.join(n,"AGENTS.md"),e.join(n,".commandcode","AGENTS.md")];r.has(s)&&o.push(`# Memory from: ${s}\n\n${r.get(s)}`),r.has(a)&&o.push(`# Memory from: ${a}\n\n${r.get(a)}`);for(const e of i)if(r.has(e)){o.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===s||e===a||i.includes(e)||o.push(`# Memory from: ${e}\n\n${t}`);return o.join("\n\n---\n\n")}catch(e){return null}}Tt(),$t(),__name(getEnterpriseMemoryPath,"getEnterpriseMemoryPath"),__name(getUserMemoryPath,"getUserMemoryPath"),__name(getProjectMemoryPaths,"getProjectMemoryPaths"),__name(discoverMemoryFiles,"discoverMemoryFiles"),__name(loadMemoryFile,"loadMemoryFile"),__name(function getCodeBlockRegex(){return/```[\s\S]*?```|`[^`]+`/g},"getCodeBlockRegex"),__name(function getImportRegex(){return/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm},"getImportRegex"),__name(processImports,"processImports"),__name(loadAllMemories,"loadAllMemories"),__name(openInEditor,"openInEditor"),__name(initProjectMemory,"initProjectMemory"),__name(getMemoryContent,"getMemoryContent"),Tn();var Ga=new Ha("AgentExecutor");function agentToTool(t,n){const{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}=n;return{name:t.name,description:t.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object"}}},required:["messages"]},execute:__name(async(n,i)=>{let c=null;const l=Date.now();let d=null;try{const u=i?.permissionMode||"standard",m=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}),clientTools:r,serverTools:o,mode:u});let g=Date.now();const p=10,h=[];if(i?.onFeedUpdate){const e=Js(t.name,n);c=js({name:t.name,input:e}),i.onFeedUpdate(c)}d=setInterval(()=>{if(i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{...c.metadata,elapsedSeconds:t}},i.onFeedUpdate(c)}},1e3);const f=await getConfiguredProvider(),y=await isOAuthEnforced();let w;f===yt.ANTHROPIC&&(w=await Zt.getValidAccessToken(),validateOAuthToken({token:w,provider:f}));const E=getApiBaseUrl(),S=new _o({baseUrl:E});let k=0;const v=[];let b=n?.messages;if("string"==typeof b)try{b=JSON.parse(b)}catch(e){b=[]}if(Array.isArray(b)&&b.length>0)for(const e of b)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&v.push({role:"user",content:t})}const C={stream:!0,messages:v,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:m,model:`anthropic:${getConfiguredModel()}`},P=await isTasteLearningEnabled(),T={[gt.PROJECT_SLUG]:Fa.getCurrentProjectDirName(),[gt.TASTE_LEARNING]:P.toString(),[gt.INTERNAL_TEAM_FLAG_HEADER]:y.toString()};w&&(T[gt.OAUTH_TOKEN]=`Bearer ${w}`);const A=getEnvironmentContext(),x=await getMemoryContent([]),I=crypto.randomUUID();let $="",R=!0;const D=__name(()=>{Ga.debug("[Agent] Abort signal triggered, stopping immediately"),R=!1,d&&(clearInterval(d),d=null)},"abortHandler");i?.abortSignal&&i.abortSignal.addEventListener("abort",D);try{for(;R;){if(i?.abortSignal?.aborted)throw Ga.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:S,body:{mode:"custom-agent",config:A,memory:x,threadId:I,params:{...C,messages:v}},headers:T,abortSignal:i?.abortSignal,onTextDelta:__name(e=>{k+=estimateTokens(e);const t=Date.now();if(i?.onFeedUpdate&&c&&t-g>=p){const e=Math.floor((t-l)/1e3);c={...c,metadata:{...c.metadata,tokensUsed:k,elapsedSeconds:e}},i.onFeedUpdate(c),g=t}},"onTextDelta")});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(k=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if($=t.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(t,i):t.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===n.length){const e=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);e.length>0&&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 o=[],s=new Set;let a=!1;for(const t of n){if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{const r=ss.includes(t.name),m=as.includes(t.name)?generateToolDescription(t.name,n).catch(()=>null):Promise.resolve(null);if(r&&i?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await m;if(!await i.onPermissionRequest(t.name,n,e)){Ga.debug(`Permission denied for tool: ${t.name}`),a=!0;break}d=setInterval(()=>{if(i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{...c.metadata,elapsedSeconds:t}},i.onFeedUpdate(c)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let o=!1;const s=["path","file_path","absolutePath","filePath","directory","folder"];for(const t of s)if(t in r&&"string"==typeof r[t]){const n=r[t];if(!e.isAbsolute(n)){const s=e.resolve(process.cwd(),n);r[t]=s,o=!0,Ga.debug(`Converted '${t}': '${n}' -> '${s}'`)}}"paths"in r&&Array.isArray(r.paths)&&(r.paths=r.paths.map(t=>"string"!=typeof t||e.isAbsolute(t)?t:(o=!0,e.resolve(process.cwd(),t)))),o?(n=r,Ga.debug(`Resolved input for ${t.name}: ${Js(t.name,n)}`)):Ga.debug(`No path resolution needed for ${t.name}: ${Js(t.name,n)}`)}if(i?.onFeedUpdate&&c){const e=Js(t.name,n);h.push({name:t.name,input:e}),h.length>3&&h.shift();const r=Date.now(),o=Math.floor((r-l)/1e3);c={...c,metadata:{isAgent:!0,status:"running",startTime:l,tokensUsed:k,elapsedSeconds:o,recentTools:[...h]}},Ga.debug(`Updating agent with recentTools (${h.length} tools): ${JSON.stringify(h)}`),i.onFeedUpdate(c)}const g=await executeTool(t.name,n,{abortSignal:i?.abortSignal,permissionMode:u});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");const p=checkToolOutputTokensLimit(g,t.name);if(o.push({type:"tool_result",tool_use_id:t.id,content:p}),s.add(t.id),i?.onFeedUpdate&&c){const e=Date.now(),t=Math.floor((e-l)/1e3);c={...c,metadata:{isAgent:!0,status:"running",startTime:l,tokensUsed:k,elapsedSeconds:t,recentTools:[...h]}},i.onFeedUpdate(c)}Ga.debug(`Tool executed successfully: ${t.name}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";o.push({type:"tool_result",tool_use_id:t.id,content:`Error: ${n}`,is_error:!0}),s.add(t.id),Ga.error(`Tool execution failed: ${t.name} - ${n}`)}}if(a){const e=v[v.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?s.has(e.id):"text"===e.type);t.length>0?e.content=t:v.pop()}R=!1;break}const m=[...o];v.push({role:"user",content:m})}}finally{i?.abortSignal&&i.abortSignal.removeEventListener("abort",D)}if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&c){const e=Date.now(),t=(e-l)/1e3;c={...c,output:$||"DONE",metadata:{isAgent:!0,status:"done",startTime:l,endTime:e,tokensUsed:k,elapsedSeconds:t}},i.onFeedUpdate(c)}return $||"DONE"}catch(e){if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&c){const t=Date.now(),n=(t-l)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||i?.abortSignal?.aborted;c={...c,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:l,endTime:t,tokensUsed:c?.metadata?.tokensUsed||0,elapsedSeconds:n}},i.onFeedUpdate(c)}throw e}},"execute")}}function filterToolsForMode(e){const{tools:t,clientTools:n,serverTools:r,mode:o}=e;if("standard"===o||"auto-accept"===o)return t;const s=t.filter(e=>n.includes(e)),a=t.filter(e=>r.includes(e));return[...getToolsForMode({allTools:s,mode:o}),...a]}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=t;let a=[];if("*"===e.tools)a=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=s[e];if(!t&&o.has(e)&&(t=e),t){const e=o.get(t);if(e)a.push(e);else{const e=r.find(e=>e.name===t);e&&a.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=s[t];if(!e&&o.has(t)&&(e=t),e){const t=o.get(e);if(t)a.push(t);else{const t=r.find(t=>t.name===e);t&&a.push(t)}}}return a}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:s}=e;let a=null;for(let e=0;e<5;e++){if(o?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:pt.ALPHA.GENERATE,signal:o,headers:r}),a=Be.fromReadableStream(e);s&&a.on("text",s);let i=null;a.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await a.finalMessage();if(i)throw i;return c}catch(t){if(a=t,o?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Ga.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:o})}}throw a||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof $o&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof Do||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 $o&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof Do||403===e?.status)return e;if(e?.message?.startsWith("Error:"))return e;let n="Error: ";return e.message?n+="Something went wrong. Please try again or contact support if the issue persists.":e.toString?n+=e.toString():n+="Unknown error occurred",new Error(n)}function processServerToolBlocks(e,t){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let n="";const r=e.content;for(const e of r)if("text"===e.type)n+=e.text;else if("server_tool_use"===e.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const{message:n,isError:o}=os({serverToolBlock:e,contentBlocks:r}),s=Js(e.name,e.input),a={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:s,output:o?zs(n):n};t.onFeedUpdate(a)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}__name(agentToTool,"agentToTool"),__name(filterToolsForMode,"filterToolsForMode"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks");var qa=new Map,Va=null;function initializeAgentManager(e){Va=e}async function loadAgentTools(){if(!Va)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");qa.clear();for(const e of Na){const t=agentToTool(e,Va);qa.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Va);qa.set(t.name,t)}}async function getAgentTools(){return 0===qa.size&&await loadAgentTools(),Array.from(qa.values())}async function getAgentTool(e){return 0===qa.size&&await loadAgentTools(),qa.get(e)}function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,o=e.join(r,".commandcode","taste"),s=e.normalize(e.resolve(r,n)),a=e.normalize(o);return s.startsWith(a)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),o=e.normalize(e.join(p.homedir(),".commandcode","taste"));let s=null;if(n.startsWith(r)?s=r:n.startsWith(o)&&(s=o),!s)return{isTaste:!1};if(!n.endsWith("taste.md"))return{isTaste:!1};const a=e.relative(s,n).split(e.sep);return 1===a.length?{isTaste:!0}:2===a.length?{isTaste:!0,category:a[0]}:{isTaste:!1}}__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool"),Tt(),$t(),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(function getTasteAccessError(){return"Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system."},"getTasteAccessError"),fr();var Ka=[Qs,aa,la,ua,fa,wa,ka,Ca,Pa,Ta,Aa,$a,Ra,Da],Ja=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],Ya=new Map(Ka.map(e=>[e.name,e])),Qa=new Set([...Ka.map(e=>e.name),...Ja.map(e=>e.name)]);function isAgentTool(e){return!Qa.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",o=isToolAllowedInMode({toolName:e,mode:r,toolParams:t});if(!o.allowed)throw new Error(o.reason||`Tool "${e}" not allowed in ${r} mode`);let s=Ya.get(e);if(s||(s=await getAgentTool(e)),!s){const t=await getAgentTools(),n=[...Array.from(Ya.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 a=trackToolStart({toolName:e});try{let r;return r=(!Ya.has(e)||!0===s.acceptsCallbacks)&&n?await s.execute(t,n):await s.execute(t),a.end({status:"success"}),r}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message){const t=sanitizeErrorForTelemetry({error:e,label:"tool_interrupted"});throw a.end({status:"error",error:t}),e}if(e instanceof Error){const t=sanitizeErrorForTelemetry({error:e,label:"tool_error"});return a.end({status:"error",error:t}),`Error: ${e.message}`}return a.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(e){const t=e?.mode||"standard",n=[...Ka],r=await getAgentTools(),o=getToolsForMode({allTools:n,mode:t}).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),s=r.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}));let a=[];return"plan"!==t&&getMcpConnectionManager().isInitialized&&(a=getAllMcpToolSchemas()),[...o,...s,...a,...Ja]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var Za={};Ka.forEach(e=>{Za[e.name]=toPascalCase(e.name)}),Ja.forEach(e=>{Za[e.name]=toPascalCase(e.name)});var Xa={};function parseEmbeddedErrorJSON(e){const t=e.indexOf("{");if(-1===t)return null;try{const n=JSON.parse(e.slice(t));if(n?.error?.message){const r=e.slice(0,t).trim();return{status:/^\d+$/.test(r)?Number(r):null,type:n.error.type||null,message:n.error.message}}}catch{}return null}function parseErrorLine(e){try{const t=JSON.parse(e);if("error"===t?.type&&t?.error?.type&&t?.error?.message)return{type:t.error.type,message:t.error.message}}catch{}return null}function interceptStreamErrors(e){const{responseStream:t}=e;let n=null,r="";const o=new TextDecoder,s=new TransformStream({transform(e,t){const s=o.decode(e,{stream:!0});r+=s;const a=r.split("\n");r=a.pop()??"";for(const e of a){const r=e.trim();if(!r){t.enqueue((new TextEncoder).encode(e+"\n"));continue}const o=parseErrorLine(r);if(o)return n=o,void t.error(new Error(`Error: Stream error: ${o.type} - ${o.message}`));t.enqueue((new TextEncoder).encode(e+"\n"))}},flush(e){const t=r.trim();if(t){const o=parseErrorLine(t);if(o)return n=o,void e.error(new Error(`Error: Stream error: ${o.type} - ${o.message}`));e.enqueue((new TextEncoder).encode(r))}}});return{stream:t.pipeThrough(s),getStreamError:__name(()=>n,"getStreamError")}}Object.entries(Za).forEach(([e,t])=>{Xa[t]=e}),initializeAgentManager({clientTools:Ka,serverTools:Ja,toolsMap:Ya,displayNameToToolName:Xa}),Tt(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors"),fr(),$t(),Vt(),Tn(),In(),Tt(),$t(),rn(),bn(),Tt();var ei=new class extends Fe{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;get observerHasRun(){return this._observerHasRun}markObserverRun(){this._observerHasRun=!0}get importHasStarted(){return this._importHasStarted}markImportStarted(){this._importHasStarted=!0}get learningComplete(){return this._learningComplete}markLearningComplete(){this._learningComplete=!0,this.emit("learning-complete")}addEvent(e){const{type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d}=e,u={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d};this.events.unshift(u),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",u)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}};function extractLearningWithConfidence(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)\.\s+Confidence:\s*(\d+\.?\d*)/);return n?{text:n[1].trim(),confidence:parseFloat(n[2])}:null}function extractLearnings(e){const{text:t}=e;return t.split("\n").filter(e=>e.trim().startsWith("-")).map(e=>extractLearningWithConfidence({line:e})).filter(Boolean)}function compareLearnings(e){const{oldText:t,newText:n}=e,r=extractLearnings({text:t}),o=extractLearnings({text:n}),s=new Map(r.map(e=>[e.text,e.confidence])),a=[],i=[],c=[];return o.forEach(e=>{const t=s.get(e.text);void 0===t?a.push(e):e.confidence>t?i.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&c.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:a,upgraded:i,downgraded:c}}Tt(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings"),Tn(),In(),fr();var ti=new Ha("LearningAgent"),ni=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:dr.LEARNING_AGENT,heading:"Learning pass failed"}}),ei.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)];ei.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),s=t.length-this.lastProcessedMessageIndex-1,a=Math.max(20,s),i=Math.max(0,t.length-a),c=t.slice(i);let l=0,d=!1;dlog(`[LearningAgent] analyzing ${s} new messages for patterns`);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){const e=await this.callLearningAPI({conversation:u}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.name).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&ti.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||ei.addEvent({type:"no_learnings",message:"no changes to taste"}),ei.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",s="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(s=String(e.filePath||e.file_path||""),s)try{o=await y.promises.readFile(s,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const a=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&s)try{i=await y.promises.readFile(s,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=s.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:o,newText:i});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{ei.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{ei.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{ei.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:a})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:t instanceof Error?t.message:String(t)})}return{results:n,learningsFound:r}}validateTastePath(t){const{toolName:n,input:r}=t,o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(!o||!r[o])return;const s=String(r[o]);if(e.isAbsolute(s))throw new Error(`Security: ${n} received absolute path. Only taste-relative paths are allowed (e.g., ".commandcode/taste/cli/taste.md" or ".commandcode/taste/taste.md"). Attempted: ${s}`);const a=e.normalize(s);if(a.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${s}`);const i=e.join(this.tasteDir,a);if(!e.normalize(i).startsWith(this.tasteDir))throw new Error(`Security: ${n} can only access files within .commandcode/taste/. Attempted: ${s}`)}adjustPathsForTaste(t){const{toolName:n,input:r}=t,o={...r},s={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(s&&o[s]){const t=String(o[s]);let r;const a="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)&&t.startsWith(this.tasteDir))if(a){if(!this.isValidTasteFilePath(t))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${t}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);r=t}else r=t;else{if(e.isAbsolute(t))throw new Error(`Invalid path: Absolute path outside taste directory: ${t}`);const n=e.normalize(t);if(n.startsWith(".."))throw new Error(`Security: Path traversal attempt detected: ${t}`);if(r=n.startsWith(".commandcode/taste")||n.startsWith(".commandcode"+e.sep+"taste")?n.replace(/^\.commandcode[/\\]taste/,this.tasteDir):e.join(this.tasteDir,n),r=e.normalize(r),!r.startsWith(this.tasteDir))throw new Error(`Security: Resolved path escapes taste directory: ${t} -> ${r}`);if(a&&!this.isValidTasteFilePath(r))throw new Error(`Invalid adjusted path: ${r}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}o[s]=r}return o}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isValidTasteFilePath(e))throw new Error(`Security: Invalid taste file path. Only allowed:\n - {project}/.commandcode/taste/taste.md\n - {project}/.commandcode/taste/{category}/taste.md\nAttempted: ${e}`)}async initializeTasteDirectory(){if(!y.existsSync(this.tasteDir)){y.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");y.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!y.existsSync(t))return!1;const n=y.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let o=n;for(const t of r){const n=t.name.toLowerCase().replace(/\s+/g,"-"),r=e.join(this.tasteDir,n),s=e.join(r,"taste.md");y.mkdirSync(r,{recursive:!0}),ei.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const a=`# ${t.name}\n${t.learnings.join("\n")}\n`;y.writeFileSync(s,a,"utf-8");const i=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;o=o.replace(t.fullSection,i)}return y.writeFileSync(t,o,"utf-8"),!0}parseCategories(e){const{content:t}=e,n=[],r=t.split(/^# /gm).filter(e=>e.trim());for(const e of r){const t=e.split("\n"),r=t[0].trim();if(e.includes("See ["))continue;const o=t.filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:"));o.length>0&&n.push({name:r,learningCount:o.length,learnings:o,fullSection:`# ${e}`})}return n}async getTasteStructure(){return y.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(t){const{dir:n,prefix:r}=t,o=y.readdirSync(n,{withFileTypes:!0});let s="";for(let t=0;t<o.length;t++){const a=o[t],i=t===o.length-1,c=i?"└── ":"├── ";if(a.isDirectory()){s+=`${r}${c}${a.name}/\n`;const t=r+(i?" ":"│ ");s+=await this.buildTree({dir:e.join(n,a.name),prefix:t})}else if("taste.md"===a.name){const t=(y.readFileSync(e.join(n,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;s+=`${r}${c}${a.name} (${t} learnings)\n`}else s+=`${r}${c}${a.name}\n`}return s}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===yt.ANTHROPIC&&(o=await Zt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[gt.PROJECT_SLUG]:Fa.getCurrentProjectDirName(),[gt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[gt.OAUTH_TOKEN]=`Bearer ${o}`);const a=await this.getTasteTools(),i=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${i})`);const c={conversation:t,tools:a,model:i,threadId:this.sessionId};let l=0,d=null;for(;l<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:pt.ALPHA.TASTE.LEARN,body:c,headers:s,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),l++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${d.message}`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_client_error"}),context:{component:dr.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(l>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:dr.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":l}}),d;const n=1e3*Math.pow(2,l);dlog(`[LearningAgent] retrying API call (${l}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw d||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return y.existsSync(r)}};Tt(),$t(),rn(),Vt(),Tn(),In(),bn();var ri="claude-haiku-4-5-20251001",oi=class{static{__name(this,"CompactAgent")}request;sessionId;maxApiRetries=3;constructor(e){this.request=e.request,this.sessionId=e.sessionId}updateRequest(e){this.request=e}async compactMessages(e){const{messages:t}=e;dlog(`[CompactAgent] compacting ${t.length} messages`);try{const e=await this.callCompactAPI({messages:t});return dlog(`[CompactAgent] compaction complete: ${e.summary.length} chars`),e}catch(e){throw dlog(`[CompactAgent] ERROR: ${e instanceof Error?e.message:String(e)}`),e}}async callCompactAPI(e){const{messages:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===yt.ANTHROPIC&&(o=await Zt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[gt.PROJECT_SLUG]:Fa.getCurrentProjectDirName(),[gt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[gt.OAUTH_TOKEN]=`Bearer ${o}`);const a=t.map(e=>{const t=e.role;let n="";return"string"==typeof e.content?n=e.content:Array.isArray(e.content)&&(n=e.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("\n")),`[${t}]: ${n}`}).join("\n\n"),i={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],system:"Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\nThis summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.\n\nBefore providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:\n\n1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:\n - The user's explicit requests and intents\n - Your approach to addressing the user's requests\n - Key decisions, technical concepts and code patterns\n - Specific details like:\n - file names\n - full code snippets\n - function signatures\n - file edits\n - Errors that you ran into and how you fixed them\n - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.\n\nYour summary should include the following sections:\n\n1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail\n2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.\n3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.\n4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.\n6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.\n7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.\n8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.\n9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.\n If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.\n\nHere's an example of how your output should be structured:\n\n<example>\n<analysis>\n[Your thought process, ensuring all points are covered thoroughly and accurately]\n</analysis>\n\n<summary>\n1. Primary Request and Intent:\n [Detailed description]\n\n2. Key Technical Concepts:\n - [Concept 1]\n - [Concept 2]\n - [...]\n\n3. Files and Code Sections:\n - [File Name 1]\n - [Summary of why this file is important]\n - [Summary of the changes made to this file, if any]\n - [Important Code Snippet]\n - [File Name 2]\n - [Important Code Snippet]\n - [...]\n\n4. Errors and fixes:\n - [Detailed description of error 1]:\n - [How you fixed the error]\n - [User feedback on the error if any]\n - [...]\n\n5. Problem Solving:\n [Description of solved problems and ongoing troubleshooting]\n\n6. All user messages:\n - [Detailed non tool use user message]\n - [...]\n\n7. Pending Tasks:\n - [Task 1]\n - [Task 2]\n - [...]\n\n8. Current Work:\n [Precise description of current work]\n\n9. Optional Next Step:\n [Optional Next step to take]\n\n</summary>\n</example>\n\nPlease provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.\n\nThere may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:\n<example>\n## Compact Instructions\nWhen summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.\n</example>\n\n<example>\n# Summary instructions\nWhen you are using compact - please focus on test output and code changes. Include file reads verbatim.\n</example>",messages:[{role:"user",content:`Please summarize the following conversation.\n\n${a}`}],model:`anthropic:${ri}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let c=0,l=null;for(;c<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${pt.ALPHA.GENERATE} with model: ${ri}`);const e=await this.request.post({endpoint:pt.ALPHA.GENERATE,body:i,headers:s,stream:!0});if(!e)throw new Error("No response stream received");const t=Be.fromReadableStream(e);let n="",r=null;t.on("text",e=>{n+=e}),t.on("error",e=>{r=e});const o=await t.finalMessage();if(r)throw r;return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:o.usage.input_tokens,output:o.usage.output_tokens}}}catch(e){l=e instanceof Error?e:new Error(String(e)),c++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${l.message}`),l;if(c>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),l;const n=1e3*Math.pow(2,c);dlog(`[CompactAgent] retrying API call (${c}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}throw l||new Error("Compact API call failed")}};async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!E(n))return null;const r=await D.readFile(n,"utf-8"),o=r.trim();return o&&"# Taste (Continuously Learned by CommandCode.ai)"!==o&&"# Taste (Continuously Learned by CommandCode)"!==o?r:null}catch(e){return null}}function extractMessageText(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t="";for(const n of e)"text"===n.type&&(t+=n.text);return t}async function buildAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced(),n={[gt.PROJECT_SLUG]:Fa.getCurrentProjectDirName(),[gt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};if(e===yt.ANTHROPIC){const e=await Zt.getValidAccessToken();e&&(n[gt.OAUTH_TOKEN]=`Bearer ${e}`)}return n}function hasUserAndAssistantMessage(e){let t=!1,n=!1;for(const r of e)if("user"===r.message.role&&(t=!0),"assistant"===r.message.role&&(n=!0),t&&n)return!0;return!1}async function generateSessionTitle(e){const{messages:t,sessionManager:n,request:r}=e;if(!hasUserAndAssistantMessage(t))return;if(await n.loadSessionTitle())return;let o="",s="";for(const e of t)if(o||"user"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,1e3)),s||"assistant"!==e.message.role||(s=extractMessageText(e.message.content).slice(0,1e3)),o&&s)break;if(!o||!s)return;const a=`You are generating a succinct session title for a coding session based on the provided description.\n\nThe title should be:\n- Clear, concise, and accurately reflect the task\n- No more than 6 words\n- Easy to understand by a general audience\n- Free of unnecessary jargon (use technical terms only if essential)\n- Written in sentence case (capitalize only the first word and proper nouns)\n\nReturn only the title as a plain string, not JSON.\n\nExample titles:\nAdd retry logic to API\nSimplify error handling flow\nClean up unused components\n\nSession description:\n<description>User: ${o}\n\n---\n\nAssistant: ${s}</description>\n\nGenerate the session title now.`,i={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:a}],model:wt,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},c=await buildAuthHeaders(),l=await r.post({endpoint:pt.ALPHA.GENERATE,body:i,headers:c,stream:!0}),d=Be.fromReadableStream(l);let u="";d.on("text",e=>{u+=e}),await d.finalMessage(),u=u.trim(),u&&(await n.saveSessionTitle(u),dlog("Session",`Title generated: ${u}`))}Tt(),$t(),__name(getTasteContent,"getTasteContent"),bn(),Tt(),rn(),Vt(),Tn(),In(),bn(),$t(),__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle");var si=new Ha("ContextEngine"),ai=200,ii=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 _o({baseUrl:n}),this.callbacks=e,this.sessionManager=new Fa(t),this.learningAgent=new ni({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new oi({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new _o({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,si.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),si.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=$s("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>si.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n){let r=e,o=[];try{const t=await processFileReferences(e);if(r=t.processedContent,o=t.fileReferences,o.length>0){const e=o.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(r=`${n}\n\n${r}`);const s=$s(e);t&&t.length>0&&(s.metadata={...s.metadata,images:t}),o&&o.length>0&&(s.metadata={...s.metadata,fileReferences:o}),this.callbacks.onFeedUpdate(s);const a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),r.trim()&&a.push({type:"text",text:r});const i={role:"user",content:a},c=crypto.randomUUID(),l=this.createMessageWithMeta(i,{messageId:c});this.addMessageAndSync(l),this.checkpointManager.createSnapshot({messageId:c}).catch(e=>si.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,s).catch(e=>si.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const d=await this.processMessages();return this.triggerTitleGeneration(),d}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){si.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}triggerTitleGeneration(){this.titleGenerationInFlight||(this.titleGenerationInFlight=!0,generateSessionTitle({messages:this.messages,sessionManager:this.sessionManager,request:this.request}).catch(e=>{dlog("Session",`Title generation failed: ${e instanceof Error?e.message:String(e)}`)}).finally(()=>{this.titleGenerationInFlight=!1}))}async processMessages(){let e="";this.requestInterrupted=!1,this.abortController=new AbortController,this.learningAgent.setAbortSignal(this.abortController.signal);let t=!1;for(;;)try{this.checkIfInterrupted(),t||(this.initializeInteractionTokens(),t=!0);const{body:n,headers:r}=await this.prepareAPICall(),o=await this.callAPIWithRetry({body:n,headers:r});this.checkIfInterrupted(),this.updateContextUsage(o),await this.checkAndCompactIfNeeded();const s=o.content.filter(e=>"tool_use"===e.type),a=o.content.filter(e=>"server_tool_use"===e.type);if(e=a.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===s.length){const t=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===a.length){const t=Ds(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>si.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>si.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=$s(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>si.error(`Failed to save messages: ${e}`)),this.triggerLearningAgent();continue}}break}const i=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(i.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:i})),e.trim()){const t=Ds(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:s}),{toolResults:l,executedToolIds:d,permissionDenied:u}=c;if(u){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const m=[...l];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){m.push({type:"text",text:t});const e=$s(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>si.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&si.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){si.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return si.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.messages.map(e=>e.message)}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};si.debug(`Manual compact: ${this.messages.length} messages`);const e=this.contextTokensUsed;return await this.summarizeAndCompact(),{tokensSaved:Math.max(0,e-this.contextTokensUsed),didCompact:!0}}async compactConversation({preserveCurrentInteraction:e=!1}={preserveCurrentInteraction:!1}){const t=this.messages.length,n=this.contextTokensUsed;let r=-1;if(e)for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if("user"===t.message.role){const n=t.message.content;if(!Array.isArray(n)){r=e;break}if(!n.some(e=>"tool_result"===e.type)){r=e;break}}}let o=0;const s=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],a=n.message.role;if(e&&t>=r&&-1!==r)s.push(n);else{if("user"===a){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){o+=estimateTokens(n.message);continue}s.push(n)}else s.push(n)}else if("assistant"===a){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)o+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?s.push({...n,message:{...n.message,content:r}}):o+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&s.push(n)}"user"!==a&&"assistant"!==a&&(o+=estimateTokens(n.message))}}this.messages=s,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,n-o);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:Wa}),{messagesRemoved:t-s.length,tokensSaved:o}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){}}))}async syncMessageToShare(e,t){try{const n=Ao.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:pt.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 o;n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n),n===yt.ANTHROPIC&&(o=await Zt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={tools:t,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},a={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:s,threadId:this.sessionManager.getSessionId(),permissionMode:e};si.debug(`calling API (${s.model}, ${this.messages.length} msgs, ${t.length} tools)`);const i=await isTasteLearningEnabled(),c={[gt.PROJECT_SLUG]:Fa.getCurrentProjectDirName(),[gt.TASTE_LEARNING]:i.toString(),[gt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(c[gt.OAUTH_TOKEN]=`Bearer ${o}`),{body:a,headers:c}}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:pt.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const o=Be.fromReadableStream(n);o.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let s=null;o.on("error",e=>{s="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const a=await o.finalMessage();if(s)throw s;return this.callbacks.onRetryUpdate?.(null),a}catch(e){const o=r?.(),s=o?Object.assign(new Error(o.message),{type:o.type,error:{type:o.type,message:o.message}}):e;if(t=s,this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(s))throw trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"non_retryable_api_error"}),context:{component:dr.CONTEXT_ENGINE,heading:"Non-retryable API error",code:s?.status||s?.statusCode}}),this.formatAPIError(s);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:dr.CONTEXT_ENGINE,code:s?.status||s?.statusCode,"retry.attempts":10}}),this.formatAPIError(s);trackError({error:sanitizeErrorForTelemetry({error:s instanceof Error?s:new Error(String(s)),label:"generate_retry_attempt"}),context:{heading:"Generate API retry",component:dr.CONTEXT_ENGINE,code:s?.status||s?.statusCode,"retry.attempt":n+1,"retry.max":10}});const a=Math.min(n,10),i=100*Math.pow(2,a),c=Math.max(i,1e3),l=Math.min(c,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:l,signal:this.abortController?.signal})}}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){const{message:t}=this.extractErrorMessage(e),n=t?.toLowerCase()||"",r="Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")||this.requestInterrupted||this.abortController?.signal.aborted,o="Insufficient credits"===t||n.includes("insufficient credits"),s=e instanceof Ro||401===e?.status||e instanceof Do||403===e?.status,a=e?.type||e?.error?.type,i="rate_limit_error"===a||429===e?.status||n.includes("rate limit"),c="overloaded_error"===a||529===e?.status||n.includes("overloaded");return r||o||s||i||c}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.error?.message){const n=parseEmbeddedErrorJSON(e.error.message);return n?{...n,status:n.status||t}:{status:t,type:e.error.type||null,message:e.error.message}}const n=e?.message;if("string"==typeof n){const e=parseEmbeddedErrorJSON(n);if(e)return{...e,status:e.status||t}}return{status:t,type:e?.type||null,message:e?.message||null}}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.requestInterrupted||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=this.extractErrorMessage(e),n=t.status,r=t.type,o=t.message;dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",o);const s=o?.toLowerCase().includes("insufficient credits");if(s)return new Error("Insufficient credits");const a=o?.toLowerCase().includes("oauth authentication required");if(a)return e;if(e instanceof Do||403===e?.status)return e;if(e instanceof Ro||401===e?.status)return new Error('Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.');const i=getSupportId();let c="";if(o)if(o.includes("Invalid 'Authorization' header"))c='Error: Authentication failed. Run "cmd login" to sign in again.';else{let e=o;for(;e.startsWith("Error: ");)e=e.substring(7);e.includes("Unexpected event order")&&(e="The API returned an error. This may be due to high traffic or a temporary issue.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>ai&&(t=t.substring(0,ai)+"..."),c=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const s=o.toLowerCase(),a="overloaded_error"===r||s.includes("overloaded"),l="rate_limit_error"===r||s.includes("rate limit");c+=a?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":l?'\n\nYou can wait a moment and try again, or type "continue" to retry.':'\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==i&&(c+=`\nRequest ID: ${i}`)}else if(e.toString){const t=e.toString();c=t.length>ai?t.substring(0,ai)+"...":t}else c="Error: Unknown error occurred";return new Error(c)}async executeToolBlocks(e){const t=new Set;let n=!1;const r=[],o=[];for(const s of e.toolBlocks){this.checkIfInterrupted();const e=crypto.randomUUID(),a=ss.includes(s.name),i=as.includes(s.name)?this.getToolDescription(s):Promise.resolve(null);let c=null;try{a&&this.callbacks.onPermissionRequest&&(c=await i);const t=await this.checkToolPermission(s,c);if(t.needsPermission&&!t.allowed){this.handlePermissionDenied(s,e),n=!0;break}}catch(n){const r=n instanceof Error?n.message:"Permission check failed";this.showToolError(s,r,e,c),o.push({toolBlock:s,toolResult:{type:"tool_result",tool_use_id:s.id,content:`Error: ${r}`,is_error:!0}}),t.add(s.id);continue}null===c&&(c=await i),r.push({toolBlock:s,entryId:e,description:c})}const s=[];for(const{toolBlock:e,toolResult:n}of o)s.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=await this.executeSingleTool(e);return isAgentTool(e.name)||this.showToolSuccess(e,r,t,n),{toolBlock:e,toolResult:{type:"tool_result",tool_use_id:e.id,content:r}}}));for(let n=0;n<e.length;n++){const o=e[n],{toolBlock:a,entryId:i,description:c}=r[n];if("fulfilled"===o.status)s.push(o.value.toolResult),t.add(a.id);else{const e=o.reason instanceof Error?o.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(a.name)?t.add(a.id):(s.push({type:"tool_result",tool_use_id:a.id,content:`Error: ${e}`,is_error:!0}),t.add(a.id),this.showToolError(a,e,i,c))}}}return{toolResults:s,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 si.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 ss.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),o=estimateTokens(r);return this.currentInteractionTokens+=o,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),r}handlePermissionDenied(e,t){const n=Js(e.name,e.input),r={..."edit_file"===e.name?e.input:{},permissionDenied:!0},o={...Ms(e.name,n,r),id:t},s=Bs(o,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(s)}showToolSuccess(e,t,n,r){let o="edit_file"===e.name?e.input:void 0;if("read_file"===e.name){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(o={...o||{},isTasteFile:!0,tasteCategory:e.category})}}const s={...e.input,...o?.isTasteFile?{isTasteFile:o.isTasteFile}:{},...o?.tasteCategory?{tasteCategory:o.tasteCategory}:{}},a=Js(e.name,s),i={...Ms(e.name,a,o),id:n,...r?{description:r}:{}},c=Bs(i,t);this.callbacks.onFeedUpdate(c)}showToolError(e,t,n,r){const o=Js(e.name,e.input),s="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,a={...Ms(e.name,o,s),id:n,...r?{description:r}:{}},i=Bs(a,zs(t));this.callbacks.onFeedUpdate(i)}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=Ds(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:o}=os({serverToolBlock:e,contentBlocks:n}),s=Js(e.name,e.input),a=Ms(e.name,s),i=Bs(a,o?zs(r):r);this.callbacks.onFeedUpdate(i)}if(t.trim()){const e=Ds(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:Wa})}async checkAndCompactIfNeeded(){const e=Math.floor(Wa*bt.TIER_1_THRESHOLD),t=Math.floor(Wa*bt.TIER_2_THRESHOLD),n=Math.floor(Wa*bt.TIER_3_THRESHOLD);try{if(this.contextTokensUsed>n){si.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){si.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${bt.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(bt.TIER_2_KEEP_COUNT);return si.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=bt.TIER_1_KEEP_COUNT;if(t>n){si.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);si.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){si.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){e>0&&this.callbacks.onFeedUpdate(Rs(`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 o=new Set(r.slice(-e).map(e=>e.id)),s=new Set(r.filter(e=>!o.has(e.id)).map(e=>e.id)),a=[];for(const e of this.messages){const t=e.message.role,r=e.message.content;if("user"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_result"!==e.type||!s.has(e.tool_use_id)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;a.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_use"!==e.type||!s.has(e.id)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;a.push({...e,message:{...e.message,content:t}});continue}a.push(e)}this.messages=a,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,t-n);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:Wa}),{toolsRemoved:s.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return si.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(bt.TIER_2_KEEP_COUNT);si.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});si.debug(`Summarization complete: ${r.summary.length} chars, used ${r.tokensUsed.input}/${r.tokensUsed.output} tokens`);const o=this.createMessageWithMeta({role:"user",content:[{type:"text",text:`This is an auto-compacted summary of the earlier conversation that ran out of context.\n\n${r.summary}`}]},{isSummary:!0}),s=this.contextTokensUsed,a=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[o,...t],await this.sessionManager.saveMessages(this.messages);const i=estimateTokens(o.message),c=Math.max(0,s-a+i);this.contextTokensUsed=c,this.callbacks.onContextUsageUpdate?.({current:c,limit:Wa}),si.debug(`Tier 3 summarization complete: reduced from ${s} to ~${c} tokens`)}catch(e){si.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(bt.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=bt.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const o=this.messages[r],s=estimateTokens(o.message);if(t+s>e){n=r+1;break}t+=s;const a=o.message.content;Array.isArray(a)&&a.some(e=>"tool_result"===e.type)}n=Math.min(n,this.messages.length-3),n=Math.max(0,n);let r=0;this.messages[0]?.meta?.isSummary&&(r=1);for(let e=r;e<n;e++){const t=this.messages[e].message.content;if(Array.isArray(t)&&t.some(e=>"image"===e.type)){n=e;break}}for(;n>r&&"user"===this.messages[n].message.role;)n--;return{messagesToSummarize:this.messages.slice(r,n),messagesToKeep:this.messages.slice(n),keepStartIndex:n}}getCheckpointManager(){return this.checkpointManager}listCheckpoints(){return this.checkpointManager.listCheckpoints()}hasCheckpoints(){return this.checkpointManager.hasCheckpoints()}async restoreToCheckpoint(e){const{messageId:t,mode:n}=e;this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()});const r=this.sessionManager.getMessageIndexById({messageId:t,messages:this.messages});let o=0;if(-1!==r&&("conversation"===n||"both"===n))for(let e=r;e<this.messages.length;e++)o+=estimateTokens(this.messages[e].message);const s=await this.checkpointManager.restore({messageId:t,mode:n});return!s.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-o),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:Wa})),s}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}};function getShellPathAndName(){const e=process.env.SHELL||"/bin/bash",t=e.split("/").pop()?.toLowerCase()||"bash";return{path:e,name:t}}function getShellType(e){return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":"unknown"}function detectUserShell(){const{path:e,name:t}=getShellPathAndName();return"win32"===process.platform?{type:"unknown",path:e}:{type:getShellType(t),path:e}}Tt(),Tt(),cr(),Tt(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var ci=["no job control","cannot set terminal process group"],li=null;function getShellInfo(){return li||(li=detectUserShell()),li}__name(getShellInfo,"getShellInfo");var di=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{let s=!1;const a=__name(e=>{s||(s=!0,t(e))},"doResolve"),i=getShellInfo(),c="bash"===i.type||"zsh"===i.type,l=c?i.path:"/bin/bash",d=x(l,c?["-i","-c",e]:["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let u="",m="",g=null;n>0&&(g=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),a({stdout:u,stderr:m+(m?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(u.length+n.length>rr){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void a({stdout:u,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}u+=n}catch(e){m+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,d.kill("SIGTERM")}}),d.stderr?.on("data",e=>{try{const t=e.toString();if(m.length+t.length>or)return void(m+="\n[Error output truncated: too large]");m+=t}catch(e){m+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{g&&clearTimeout(g);const n=c?m.split("\n").filter(e=>!ci.some(t=>e.includes(t))).join("\n"):m;a({stdout:u.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{g&&clearTimeout(g),a({stdout:u,stderr:m+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),ui=__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"),mi=__name(()=>{const[e,t]=z({isExecuting:!1,currentCommand:null});return{executeBash:G(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await di(e,{timeout:3e4,cwd:process.cwd()}),o=ui(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]=Bs(r,o);break}}return n}),r()}catch(t){const o=t instanceof Error?t.message:"Unknown error occurred";n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const r=n[t];if("bash"===r.role&&"command"in r&&r.command===e&&!r.output){n[t]=Bs(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");Tt(),Tt(),$t();var gi=class extends Fe{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 M.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 M.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await M.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 M.writeFile(n,JSON.stringify(t,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const n=t.join(this.projectRoot,".commandcode"),r=t.join(n,"settings.local.json"),o=`Bash(${e.split(" ")[0]}:*)`;try{let e;await M.mkdir(n,{recursive:!0});try{const t=await M.readFile(r,"utf-8");e=JSON.parse(t)}catch(t){e={permissions:{allow:[],deny:[],defaultMode:"ask"}}}e.permissions||(e.permissions={allow:[],deny:[],defaultMode:"ask"}),e.permissions.allow||(e.permissions.allow=[]),e.permissions.allow.includes(o)||e.permissions.allow.push(o),await M.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},pi=__name((e={})=>{const[t,n]=z(null),[r,o]=z(null),[s,a]=z(!1);return H(()=>{const t=e.projectRoot||process.cwd(),r=new gi(t);return r.on("permission-request",(t,n)=>{o(t),a(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),a(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:G(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:G(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:G(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),a(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),a(!1)}},[t]),clearSessionPermissions:G(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:G(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:G((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:G(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r="auto-accept"===("boolean"==typeof t?t?"auto-accept":"standard":t),o=["create","edit","delete","execute","shellCommands"];for(const e of o)n.setAutoApprove(e,r)}Tt(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),Tt();var hi=__name(()=>process.stdout.write("win32"===process.platform?"[2J[0f":"[2J[3J[H"),"clearConsole");function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",o=!1,s="";for(let e=0;e<t.length;e++){const a=t[e];'"'!==a&&"'"!==a||o?a===s&&o?(o=!1,s=""):" "!==a||o?r+=a:(r.trim()&&n.push(r.trim()),r=""):(o=!0,s=a)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const o=n.substring(0,r),s=n.substring(r+1).trim();return{commandName:o,rawArguments:s,positionalArgs:parsePositionalArguments({input:s})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let o=t;return o=o.replace(/\$ARGUMENTS/g,n),o=o.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:o}}function loadCustomCommands(){const e=[],n=t.join(process.cwd(),".commandcode","commands"),r=t.join(h.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,o=""){if(w.existsSync(n))try{const s=w.readdirSync(n,{withFileTypes:!0});for(const a of s){const s=t.join(n,a.name);if(a.isDirectory())loadCommandsFromDirectory(s,r,o?`${o}/${a.name}`:a.name);else if(a.isFile()&&a.name.endsWith(".md")){const n=t.basename(a.name,".md"),i=w.readFileSync(s,"utf-8").trim();e.push({name:n,source:r,content:i,subdirectory:o})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(r,"user"),loadCommandsFromDirectory(n,"project"),e}function customCommandsToMenuItems(e){return e.map(e=>{const t=`/${e.name}`;let n;return n=e.subdirectory?"project"===e.source?`(project: ${e.subdirectory})`:`(user: ${e.subdirectory})`:"project"===e.source?"(project)":"(user)",{command:t,description:`${e.content.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim()} ${n}`}})}function getCustomCommandContent(e){const t=loadCustomCommands(),n=e.startsWith("/")?e.substring(1):e,r=t.find(e=>e.name===n);return r?r.content:null}function isDirectoryEmpty(){try{return 0===P(process.cwd()).length}catch{return!1}}async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new _o({baseUrl:e});return await t.get({endpoint:pt.ALPHA.WHOAMI})}Tt(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),nn(),Tt(),$t(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),Tt(),__name(isDirectoryEmpty,"isDirectoryEmpty"),Tt(),$t(),__name(getAuthenticatedEntity,"getAuthenticatedEntity"),xn(),Tt();var fi=["Code","Code - Insiders","VSCodium","Cursor"],yi="Code",wi={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},Ei=__name(e=>u(e).href,"formatPathForTerminal"),Si=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),ki=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),vi=__name(({home:t,configSegments:n,variants:r})=>{for(const o of r){const r=ki({home:t,configSegments:n,variant:o});if(y.existsSync(e.dirname(r)))return o}return null},"findExistingVariant"),bi=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Ci(t.when)},"isTerminalShiftEnterBinding"),Ci=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),Pi=__name(e=>{const t=ze(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),Ti=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),Ai=__name(({error:e,content:t})=>{const n=e.message;return Ti(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"),xi=__name(e=>{let t="",n=!1,r=!1;for(let o=0;o<e.length;o++){const s=e[o];if(n)t+=s,r?r=!1:"\\"===s?r=!0:'"'===s&&(n=!1);else if('"'!==s){if(","===s){let t=o+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=s}else n=!0,t+=s}return t},"removeTrailingCommas"),Ii=__name(e=>{try{const t=ze(e),n=xi(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:Ai({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),$i=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:Ei(t)}),"createSuccessResult"),Ri=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:Ei(t)}),"createErrorResult"),Di=__name(()=>{const t=p.homedir(),n=p.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=Si(n);if(!r)return ki({home:t,configSegments:[".config"],variant:yi});const o=vi({home:t,configSegments:r,variants:fi});return ki({home:t,configSegments:r,variant:o??yi})},"getVSCodeKeybindingsPath"),Mi=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)bi(n)&&(n.command===wi.command&&n.args?.text===wi.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),Ni=__name(t=>{try{if(!y.existsSync(t)){const n=e.dirname(t);return y.existsSync(n)||y.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=y.readFileSync(t,"utf-8");if(Pi(n))return{rawContent:n,keybindings:[]};const r=Ii(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:Ri({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):Ri({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return Ri({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),Oi=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(wi,null,2);if(Pi(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return Ri({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?Ri({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,o+1)+",\n"+n+e.substring(o+1)},"generateNewContent");function setupVSCodeTerminal(){const e=Di();try{const t=Ni(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=Mi(r);if(o.hasConflicting)return Ri({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return $i({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=Oi({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(y.writeFileSync(e,s,"utf-8"),$i({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return Ri({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"),Tt(),$t(),bn(),Tt();var Fi={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return Fi[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Le(t);return e.join(h.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 D.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(t,n=process.cwd()){try{const r=getGlobalProjectSettingsPath(n),o=e.dirname(r);await D.mkdir(o,{recursive:!0}),await D.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),ei.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 D.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"),Tt(),bn(),$t(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),Tt(),bn();var Li=e.join(p.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=A(e,{encoding:"utf8"}),n=We.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 D.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const o=await D.readdir(t);for(const s of o){if(!/^\d{4}$/.test(s))continue;const o=e.join(t,s);if(!(await D.stat(o)).isDirectory())continue;const a=await D.readdir(o);for(const t of a){if(!/^\d{2}$/.test(t))continue;const a=e.join(o,t);if(!(await D.stat(a)).isDirectory())continue;const i=await D.readdir(a);for(const o of i){if(!/^\d{2}$/.test(o))continue;const i=e.join(a,o);if(!(await D.stat(i)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${s}/${t}/${o}`});const c=(await D.readdir(i)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(i,t));r.push(...c)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const o=[];for(let s=0;s<e.length;s+=n){const a=e.slice(s,s+n),i=await Promise.all(a.map(t));for(const e of i)null!==e&&o.push(e);r?.(Math.min(s+n,e.length),e.length)}return o}async function findCodexSessions(t,n,r=0){const o=t||process.cwd(),s=[];dlog(`[Codex] scanning for project: ${o}`);const a=await findAllSessionFiles(Li,n);if(0===a.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${a.length} session files to scan`),n?.({phase:"reading",totalFiles:a.length,processedFiles:0,matchedSessions:0});let i=0;const c=await processFilesInBatches(a,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===o)try{const r=await D.stat(t),o=e.basename(t,".jsonl");return{id:n.id||o,filePath:t,createdAt:new Date(n.timestamp||r.birthtime),lastModified:r.mtime,messageCount:0,agent:"codex",projectDir:n.cwd}}catch{return null}return null},10,(e,t)=>{i=s.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:i})});s.push(...c);const l=r>0?s.slice(0,r):s;return dlog(`[Codex] matched ${l.length} sessions for project`),n?.({phase:"complete",totalFiles:a.length,processedFiles:a.length,matchedSessions:l.length}),l.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("event_msg"===n.type&&"user_message"===n.payload?.type&&n.payload?.message){const e=n.payload.message;"string"==typeof e&&e.trim()&&t.push(e.trim())}}catch{continue}t.length>0&&dlog(`[Codex] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Codex] failed to extract prompts: ${e}`,t)}return t}async function loadProjectSettings(){return loadMergedProjectSettings()}async function saveProjectSettings(e){await saveGlobalProjectSettings(e)}function isOnboardingDone(e){return!0===e?.skipped||!0===e?.completed}function buildAgentSessionsList(e){return Object.entries(e).filter(([e,t])=>t&&t.length>0).map(([e,t])=>({agent:e,sessionIds:t,displayName:getAgentDisplayName(e)}))}async function checkOnboardingConditions(){try{const e=(await loadProjectSettings()).tasteOnboarding,t=!0===e?.demoShown;if(isOnboardingDone(e))return dlog("[Onboarding] "+(e?.skipped?"user skipped":"already completed")),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!0,agentSessions:[],demoShown:t};const n=await findNewSessions(e?.learnedSessions||{}),r=(n["claude-code"]?.length||0)+(n.codex?.length||0);return r>0?(dlog(`[Onboarding] found ${r} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:r,hasTasteContent:!0,agentSessions:buildAgentSessionsList(n),demoShown:t}):t?(dlog("[Onboarding] no new sessions to learn from"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t}):(dlog("[Onboarding] first time user, will show demo"),{shouldTrigger:!0,reason:"no_sessions",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:!1}}}async function getSessionFilesFromDir(e){try{return(await D.readdir(e)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints")).map(e=>e.replace(".jsonl",""))}catch{return[]}}async function findNewSessions(t){const n={},r=t["claude-code"]||[],o=t.codex||[];try{const t=e.join(p.homedir(),".claude","projects");await D.access(t);const o=getProjectDirName(process.cwd()),s=(await D.readdir(t)).filter(e=>e===o);for(const o of s){const s=e.join(t,o);if((await D.stat(s)).isDirectory()){const e=await getSessionFilesFromDir(s);e.length>0&&(n["claude-code"]=e.filter(e=>!r.includes(e)))}}dlog(`[Sessions] claude-code: ${n["claude-code"]?.length||0} new, ${r.length} learned`)}catch{dlog("[Sessions] claude projects dir not found")}try{const e=await findCodexSessionIds();e.length>0&&(n.codex=e.filter(e=>!o.includes(e)));dlog(`[Sessions] codex: ${n.codex?.length||0} new, ${o.length} learned`)}catch{dlog("[Sessions] codex sessions not found")}return n}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0,await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function markDemoShown(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.demoShown=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:o}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions();e.shouldTrigger?(dlog(`[Onboarding] starting taste learning (${e.reason})`),o(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),__name(loadProjectSettings,"loadProjectSettings"),__name(saveProjectSettings,"saveProjectSettings"),__name(isOnboardingDone,"isOnboardingDone"),__name(buildAgentSessionsList,"buildAgentSessionsList"),__name(checkOnboardingConditions,"checkOnboardingConditions"),__name(getSessionFilesFromDir,"getSessionFilesFromDir"),__name(findNewSessions,"findNewSessions"),__name(markSessionsAsLearned,"markSessionsAsLearned"),__name(markOnboardingSkipped,"markOnboardingSkipped"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markDemoShown,"markDemoShown"),__name(triggerTasteOnboarding,"triggerTasteOnboarding"),Tt(),$t(),Tt();var _i="# Taste (Continuously Learned by CommandCode.ai)",Ui=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return Ui.test(t)?t.replace(Ui,`$1${_i}`):t}__name(migrateHeader,"migrateHeader");var ji=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await D.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await D.access(r);const e=await D.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await D.writeFile(r,t,"utf-8")}catch{await D.writeFile(r,_i+"\n\n")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await D.access(n),!0}catch{return!1}}};Tn(),In(),en(),Tt(),Tt(),$t(),Tt(),Tt(),$t();var Bi=__name(()=>t.join(h.homedir(),".commandcode","agents"),"getRootAgentDir"),zi=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Wi=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=z("idle"),[a,i]=z(""),c=[...Ka.map(e=>e.name),...Ja.map(e=>e.name)],l=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void i("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?Bi():zi();await M.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),a=Array.from(e.selectedTools).map(e=>Za[e]||e).join(", "),i=0===e.selectedTools.size?"none":e.selectedTools.size===c.length?'"*"':JSON.stringify(a),l=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${i}\n---\n\n${e.sysPrompt}\n`;await M.writeFile(s,l,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),i(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");Z((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||l()});const d=Array.from(e.selectedTools).map(e=>Za[e]||e).join(", "),u="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return B.createElement(V,{flexDirection:"column",gap:1},B.createElement(V,{flexDirection:"column"},B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"Name:"),B.createElement(K,{color:"gray"},e.agentType)),B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"Location:"),B.createElement(K,{color:"gray"},u)),B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"Tools:"),B.createElement(K,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===c.length?"*":d))),B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"Description"),B.createElement(K,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),B.createElement(K,{color:"gray"},e.ccToolDefinition),B.createElement(V,{gap:1},B.createElement(K,{color:"white",bold:!0},"System Prompt:")),B.createElement(K,{color:"gray"},e.sysPrompt),!r&&B.createElement(V,{marginTop:1},"idle"===o&&B.createElement(V,{gap:1},B.createElement(K,{color:"green",dimColor:!0},"Press"),B.createElement(K,{color:"green",bold:!0},"Enter"),B.createElement(K,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===o&&B.createElement(K,{color:"yellow"},"Saving agent..."),"saved"===o&&B.createElement(K,{color:"green"},"✓ ",a),"error"===o&&B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"red"},"✗ Error: ",a),B.createElement(K,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),Hi=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=z("menu"),a=[...Ka.map(e=>e.name),...Ja.map(e=>e.name)];let i=new Set;if("*"===e.tools||'"*"'===e.tools)i=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>Xa[e]||e);i=new Set(t)}const c={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(Z((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return B.createElement(V,{flexDirection:"column"},B.createElement(Wi,{config:c,onSaveComplete:()=>s("menu"),viewOnly:!0}),B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray"},"Press Enter to go back")));if("edit"===o)return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"yellow"},"Edit functionality coming soon..."),B.createElement(K,{color:"gray"},"Press Esc to go back"));if("delete"===o){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],o=__name(async r=>{if("confirm-delete"===r.value)try{await M.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return B.createElement(V,{flexDirection:"column",gap:1},B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"red"},"Delete agent"),B.createElement(K,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),B.createElement(V,null,B.createElement(He,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"},` ${t}`)})))}return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"white",bold:!0},e.name),B.createElement(V,{marginTop:1},B.createElement(He,{items:l,onSelect:d,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"},` ${t}`)})),B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Gi=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=z([]),[s,a]=z([]),[i,c]=z([]),[l,d]=z(!0),[u,m]=z(!1),[g,p]=z(null),[f,y]=z(!1),w=__name(()=>t.join(h.homedir(),".commandcode","agents"),"getRootAgentDir"),E=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),S=__name(async(e,n)=>{try{m(!1);const r=(await M.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await M.readFile(o,"utf-8"),{data:a,content:i}=Oe(s);let c=a.tools||"";return"*"!==c&&'"*"'!==c||(c="*"),{name:a.name||r.replace(".md",""),description:a.description||"",tools:c,sysPrompt:i.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");H(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([S(w(),"personal"),S(E(),"project")]),n=Na.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));o(e),a(t),c(n),d(!1)},"loadAgents")()},[u]);const k=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{k.push({label:e.name,value:e.filePath})}),s.forEach(e=>{k.push({label:e.name,value:e.filePath})});const v=r.length+s.length,b=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(p(e),y(!0))}},"handleAgentSelect");if(l)return B.createElement(K,{color:"gray"},"Loading agents...");if(f&&g){const e=g.filePath.startsWith("__builtin__:");return B.createElement(Hi,{agent:g,onBack:()=>{y(!1),p(null)},setRevalidateAgent:m,isReadOnly:e})}const C=__name(({isSelected:e,label:t})=>{const n=k.find(e=>e.label===t),o=n?.value||"",a=r[0]?.filePath===o,i=s[0]?.filePath===o;return B.createElement(V,{flexDirection:"column"},a&&r.length>0&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray",bold:!0},"User agents")),i&&s.length>0&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray",bold:!0},"Project agents")),B.createElement(V,null,B.createElement(K,{color:"white"},e?">":" "),B.createElement(K,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return B.createElement(V,{flexDirection:"column"},B.createElement(V,{marginBottom:1},B.createElement(K,{color:"white",bold:!0},"Agents"),v>0?B.createElement(K,{color:"gray"}," ","(",v," agent",v>1?"s":"",")"):B.createElement(K,{color:"gray"}," (No custom agents)")),n&&B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{color:"green",dimColor:!0},"Created agent: ",n)),B.createElement(He,{items:k,onSelect:b,indicatorComponent:()=>null,itemComponent:C}),i.length>0&&B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(K,{color:"gray",bold:!0},"Default agents"),i.map(e=>B.createElement(K,{key:e.filePath,color:"gray"}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(K,{color:"gray"},"Create specialized subagents that Command Code can delegate to."),B.createElement(K,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Tt(),$t(),Tt(),Tt(),$t();var qi=__name(({onSelect:e})=>B.createElement(He,{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(K,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector");Tt(),gn(),$t(),fn(),kn();var Vi=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=z(!1),[m,g]=z(!1),p=G(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),h=G(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||m){if(!m||t.isPasteEnd){if(m&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[m,a]);return"agentType"===e?B.createElement(B.Fragment,null,B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(Za).some(e=>Le(e)===Le(t))||Object.keys(Za).some(e=>Le(e)===Le(t)))&&B.createElement(K,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Le(t))&&B.createElement(K,{color:"red"},"⚠ This name is reserved. Reserved names:"," ",Ma.join(", "))),B.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Le(t);Object.values(Za).some(t=>Le(t)===e)||Object.keys(Za).some(t=>Le(t)===e)||isReservedAgentName(e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?B.createElement(B.Fragment,null,B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"white"},"Enter the system prompt for your agent:"),B.createElement(K,{color:"gray"},"Be comprehensive for best results.")),B.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?B.createElement(B.Fragment,null,B.createElement(K,{color:"white"},"When should ","Command Code"," use this agent?"),B.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&l()},onChange:h,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Tt();var Ki=__name(({onSelect:e})=>B.createElement(He,{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(K,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector");Tt(),gn(),Tt();var Ji=["·","○","◇","☆","✧","☆","◇","○","⌘"],Yi=[8,5,4,4,4,4,4,5,20],Qi=[5,4,4,4,4,4,5],Zi=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Yi.length;e++)if(n+=Yi[e],t<n)return Ji[e];const r=t-58;n=0;for(let e=0;e<Qi.length;e++)if(n+=Qi[e],r<n)return Ji[7-e];return Ji[0]},"getWaveSymbol"),Xi=["#8A6BA3","#B799E6","#E4CCFF","#FFFFFF","#E4CCFF","#B799E6","#8A6BA3"];function ShimmerText({text:e}){const[t,n]=z(0);H(()=>{const t=setInterval(()=>{n(t=>(t+1)%(e.length+10))},50);return()=>clearInterval(t)},[e.length]);const r=__name(e=>{const n=e-(t-5);return n>=0&&n<Xi.length?Xi[n]:"#B799E6"},"getCharColor");return B.createElement(K,null,e.split("").map((e,t)=>B.createElement(K,{key:t,color:r(t)},e)))}function CMDIcon(){const[e,t]=z(0);return H(()=>{const e=setInterval(()=>{t(e=>(e+1)%88)},15);return()=>clearInterval(e)},[]),B.createElement(K,{color:"#E4CCFF",bold:!0},Zi(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var ec=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=z(0),s=getTerminalWidth();function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}H(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),s=e>0?t:-t,a=setInterval(()=>{o(e=>{const t=e+s;return s>0&&t>=n||s<0&&t<=n?n:t})},30);return()=>clearInterval(a)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");const a=s>70,i=s>40&&s<=70;return B.createElement(V,{width:s,height:1,paddingLeft:0,marginLeft:0},B.createElement(CMDIcon,null),B.createElement(V,{marginRight:1},B.createElement(ShimmerText,{text:e})),a?B.createElement(B.Fragment,null,B.createElement(V,{columnGap:1},B.createElement(K,{dimColor:!0},`(${formatTime3(t)}`),B.createElement(K,{dimColor:!0},"•"),B.createElement(K,{color:"gray"},Se.arrowDown),B.createElement(K,{dimColor:!0},`${formatToken(Math.round(r))}`),B.createElement(K,{dimColor:!0},"•"),B.createElement(V,{columnGap:1},B.createElement(K,{bold:!0,color:"gray"},"esc"),B.createElement(K,{dimColor:!0},"to interrupt)")))):i?B.createElement(V,{columnGap:1},B.createElement(K,{dimColor:!0},`(${formatToken(Math.round(r))})`)):B.createElement(B.Fragment,null))},"Status");kn(),fn();var tc=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,a]=z(!1),[i,c]=z(0),l=G(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(a(!0),n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}},[s,t]);return B.createElement(V,{flexDirection:"column"},r?B.createElement(V,null,B.createElement(CMDIcon,null),B.createElement(K,{color:"white"},"Generating agent from description...")):B.createElement(TextInput,{key:i,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:l,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"red"},`${ke.warning} ${o}`)))},"RecommendedFlow");Tt();var nc=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=z(!1),[a,i]=z(0),c=q(()=>[...Ka.map(e=>e.name),...Ja.map(e=>e.name)],[]),l=q(()=>[{name:"All tools",tools:c},{name:"Read-only tools",tools:c.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:c.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:c.filter(e=>"shell_command"===e)},{name:"Search tools",tools:c.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:c.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[c]),d=q(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),c.forEach(t=>{e.push({type:"tool",value:t})})):(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,l,e,c]),u=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=l.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${o?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${Za[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),m=u.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return Z((e,c)=>{if(c.upArrow)i(e=>{const t=e-1;return t<0?m.length-1:t});else if(c.downArrow)i(e=>{const t=e+1;return t>=m.length?0:t});else if(c.return||" "===e){const e=m[a];if(e){const a=d[e.value];if(!a)return;"continue"===a.type?r():"toggle"===a.type?(s(!o),i(0)):"category"===a.type?n(a.value):"tool"===a.type&&t(a.value)}}}),B.createElement(V,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===a;if("divider"===e.type)return B.createElement(V,{key:`divider-${t}`},B.createElement(K,{color:"gray"}," ",e.label));if("spacer"===e.type)return B.createElement(V,{key:`spacer-${t}`,height:1});if("label"===e.type)return B.createElement(V,{key:`label-${t}`},B.createElement(K,{color:"gray"}," ",e.label));const o="continue"===e.type;return B.createElement(V,{key:`item-${t}`},B.createElement(K,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),B.createElement(V,{marginTop:1},e.size===c.length&&B.createElement(K,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&B.createElement(K,{color:"gray"},e.size," tools selected"),0===e.size&&B.createElement(K,{color:"gray"},"No tools selected")))},"ToolsSelector");In(),rn(),nn(),Tn();var rc=__name(({onComplete:e})=>{const[t,n]=z("location"),[r,o]=z(!1),[s,a]=z(null),[i,c]=z("agentType"),l=q(()=>[...Ka.map(e=>e.name),...Ja.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=z(d()),g=__name(t=>{n("location"),c("agentType"),m(d()),e(t)},"resetToDefaults"),p=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===u.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===i)return"Agent type (identifier)";if("sysPrompt"===i)return"System prompt";if("ccToolDefinition"===i)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),h=__name(e=>{m({...u,location:e}),n("method")},"handleLocationSelect"),f=__name(e=>{m({...u,method:e}),n("configuration")},"handleMethodSelect"),y=__name(async()=>{try{a(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===yt.ANTHROPIC&&(r=await Zt.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const s={[gt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(s[gt.OAUTH_TOKEN]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new _o({baseUrl:i}),l=await c.post({headers:s,endpoint:pt.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});m({...u,agentType:Le(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof $o&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?a(Jt):a("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),w=__name(()=>{m({...u,agentType:Le(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),S=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),v=__name(e=>{const t=new Set(u.selectedTools);t.has(e)?t.delete(e):t.add(e),m({...u,selectedTools:t})},"handleToggleTool"),b=__name(e=>{const t=[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(u.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),m({...u,selectedTools:n})},"handleToggleCategory");return B.createElement(V,{flexDirection:"column",gap:1},B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"white",bold:!0},"Create new agent"),B.createElement(K,{color:"gray"},p())),B.createElement(V,null,"location"===t&&B.createElement(qi,{onSelect:h}),"method"===t&&B.createElement(Ki,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&B.createElement(tc,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:y}),"configuration"===t&&"manual"===u.method&&B.createElement(V,{flexDirection:"column",gap:1},B.createElement(Vi,{step:i,agentType:u.agentType,sysPrompt:u.sysPrompt,ccToolDefinition:u.ccToolDefinition,onAgentTypeChange:e=>m({...u,agentType:e}),onSysPromptChange:e=>m({...u,sysPrompt:e}),onCCToolDefinitionChange:e=>m({...u,ccToolDefinition:e}),onAgentTypeSubmit:w,onSysPromptSubmit:E,onCCToolDefinitionSubmit:S})),"tools"===t&&B.createElement(nc,{selectedTools:u.selectedTools,onToggleTool:v,onToggleCategory:b,onComplete:k}),"summary"===t&&B.createElement(Wi,{config:u,onSaveComplete:g})))},"AgentNew"),oc=__name(({onCancel:e})=>{const[t,n]=z(null),[r,o]=z(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return Z((t,n)=>{n.escape&&e()}),B.createElement(V,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"single",flexDirection:"column"},null===t&&B.createElement(Gi,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&B.createElement(rc,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");Tt(),Tt(),cr();var sc=__name(({messages:e})=>0===e.length?null:B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(V,{marginBottom:0},B.createElement(K,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>B.createElement(V,{key:t},B.createElement(K,{dimColor:!0},ke.pointerSmall," "),B.createElement(K,{dimColor:!0},truncateString({text:e,maxChars:80}))))),"QueuedMessages");Tt(),gn(),$t(),fn(),en(),Tt();var ac=n(f(),"commandcode-images"),ic={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{E(ac)||b(ac,{recursive:!0});const r=ic[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(ac,o),a=Buffer.from(e.data,"base64");return C(s,a),s}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:o,setDetectedContent:s,incrementInputKey:a}=e,i=G((e,t)=>{o(t=>[...t,e]),r(t),a()},[o,r,a]),c=W(!1),l=W(""),d=W(null),u=W(""),m=G(async(e,t)=>{let o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const c=await detectDroppedImageFile(o);if(c)return void i(c,t);const l=await detectClipboardImage();if(l)return void i(l,t);let d=o;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}]`;s(e=>[...e,d]),r(t+e)}else r(t+d);a()}},[i,n.length,s,r,a]),g=G(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(c.current){const e=l.current,t=u.current;l.current="",u.current="",c.current=!1,d.current=null,e&&await m(e,t)}},500)},[m]);return{handlePaste:G(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return c.current&&(c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)),await m(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!c.current)return c.current=!0,u.current=n.textBeforePaste??t,l.current=n.pastedContent??n.cleanedContent,g(),!0;if(c.current&&!n.isPasteEnd)return void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current)),g(),!0;if(c.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current));const e=l.current,t=u.current;return l.current="",u.current="",c.current=!1,await m(e,t),!0}if(n.isPasteEnd&&!n.isPasteStart&&!c.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return i(e,t),!0}return!1},[t,m,g,i]),resetPasteState:G(()=>{c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:G(()=>c.current,[])}}__name(saveTempImage,"saveTempImage"),In(),Tt(),kn(),fn(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),Tt(),Tt();var cc=["code --wait","cursor --wait","nano"],lc=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return lc.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 cc)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var dc=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 dc;t=ensureWaitFlag(t);const r=n(f(),`commandcode-${Date.now()}.md`);return await O(r,e),new Promise((e,n)=>{const o=t.split(" ").filter(e=>e.length>0),s=o[0],a=o.slice(1),i=x(s,[...a,r],{stdio:"inherit"});i.on("close",async()=>{try{const t=await F(r,"utf-8");await L(r),e(t.trimEnd())}catch(e){n(e)}}),i.on("error",async e=>{try{await L(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[o,s]=z(!1),[a,i]=z(null),c=G(async()=>{if(!o){s(!0),i(null);try{const n=e.replace(/\n+$/,""),o=await openInEditor2(n);t(o),r?.()}catch(e){i(e instanceof dc?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{s(!1)}}},[e,t,r,o]),l=G(()=>{i(null)},[]);return{isEditorOpen:o,editorError:a,handleOpenInEditor:c,clearEditorError:l}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),Tt(),Tt(),Tt(),Tt(),$t(),bn(),$n(),Un(),Tt(),$t();var uc=t.join(h.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(uc);w.existsSync(e)||w.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!w.existsSync(uc))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=w.readFileSync(uc,"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(),w.writeFileSync(uc,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"),$n();var mc=ye($),gc=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 gc.version}function isAlphaVersion(e){return e.includes("alpha")}function filterVersions(e){return{stable:e.filter(e=>!e.includes("alpha")),alpha:e.filter(e=>e.includes("alpha"))}}function getLatestVersion(e){return 0===e.length?null:e.sort(Ge.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Ge.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Ge.gt(t,e))return{latestVersion:t,updateAvailable:!0}}return{latestVersion:e,updateAvailable:!1}}async function checkForUpdateAvailable(){const e=fetchVersions();if(!e)return null;const t=getCurrentVersion(),{stable:n,alpha:r}=filterVersions(e),{latestVersion:o,updateAvailable:s}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:o,updateAvailable:s}}async function executeUpdate(e){try{return await mc(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;if(!Ge.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=Me(`Updating ${e} → ${t.targetVersion}`).start(),r=await executeUpdate(t.targetVersion);if(clearPendingUpdate(),!r)return n.fail("Update failed"),void console.log("Run `cmd update` to try again.");n.succeed(`Updated to v${t.targetVersion}`)}async function performAutoUpdate(e){const{silent:t,updateInfo:n,onStart:r}=e||{};if(isLocalDevelopmentBuild())return{success:!1};const o=n||await checkForUpdateAvailable();return o?.updateAvailable?(r?.(o.latestVersion),await executeUpdate(o.latestVersion)?{success:!0,updateInfo:o}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:o})):{success:!1}}function getCurrentGitBranch(){try{return 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 pc=new Set(["OPEN","MERGED","CLOSED"]),hc=null;function getCachedPRInfo(e){if(hc&&hc.branch===e){if(!(Date.now()-hc.timestamp>3e5))return hc.result;hc=null}}function setPRCache(e,t){hc={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((o,s)=>{R(e,[...t],{encoding:n,timeout:r},(e,t)=>{e?s(e):o(t.trim())})})}function parsePRResponse(e){try{const t=JSON.parse(e);return t.number&&t.url&&t.state&&pc.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 fc=__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"),yc=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=z(null),o=W(!1);return H(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,fc().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");Tt(),$t(),xn(),cr();var wc=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear (reset, new)",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.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))(wc||{}),Ec=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{command:"/clear (reset, new)",description:"Clear the conversation history"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/agents",description:"Manage agent configurations"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/model",description:"Switch between Command Code models"},{command:"/compact",description:"Compact the conversation history"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/add-dir",description:"Add directory to workspace context"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/ide",description:"Install extension to fetch IDE context"},{command:"/help",description:"Show available shortcuts"},{command:"/exit",description:"Exit the REPL"}],Sc=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=z(0),[s,a]=z(0),{stdout:i}=Q(),c=i?.columns??80,l=Math.max(20,c-22-2-1-2),d=q(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...Ec.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!n)return e;const t=n.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let o=0;return n.startsWith("/"+t)?o+=100:n.includes(t)&&(o+=50),r.includes(t)&&(o+=25),{...e,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]),u=q(()=>{const e=s,t=Math.min(e+8,d.length);return d.slice(e,t)},[d,s]);return H(()=>{o(0),a(0)},[n]),Z((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>{const t=Math.max(0,e-1);return t<s&&a(t),t});else if(i.downArrow)o(e=>{const t=Math.min(d.length-1,e+1);return t>=s+8&&a(Math.max(0,t-8+1)),t});else if(i.return){const t=d[r];return void(t&&e(t.command))}}),0===d.length?B.createElement(V,{flexDirection:"column",paddingLeft:2},B.createElement(K,{color:"dim"},"No commands found")):(d.length,B.createElement(V,{flexDirection:"column",paddingLeft:1},B.createElement(V,{columnGap:2},B.createElement(V,{flexDirection:"column",width:22},u.map((e,t)=>{const n=s+t;return B.createElement(K,{key:n,color:r===n?"white":"dim",wrap:"truncate"},e.command)})),B.createElement(V,{flexDirection:"column"},u.map((e,t)=>{const n=s+t;return B.createElement(K,{key:n,color:r===n?"white":"dim",wrap:"truncate"},truncateString({text:e.description,maxChars:l}))})))))},"CommandMenu");function loadGitignore(e){const t=qe(),r=n(e,".gitignore");if(E(r))try{const e=S(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}Tt(),__name(loadGitignore,"loadGitignore");var kc=__name(({onSelectFile:e,onClose:t,searchQuery:s=""})=>{const[i,c]=z(process.cwd()),[l,d]=z([]),[u,m]=z(0),[g,p]=z(0),h=s.trim()?15:10,f=G((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const s=n(t,e);try{const e=P(s),a=[];return e.forEach(e=>{const i=n(s,e);try{const e=T(i),n=o(t,i);if(r.ignores(n))return;a.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}),a.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),a.slice(0,50)}catch{}}if(e.includes("/")){const s=e.split("/"),a=s.pop()||"",i=n(t,s.join("/"));try{const e=P(i),s=[],c=a.toLowerCase();return e.forEach(e=>{const l=e.toLowerCase();if(!a||l.includes(c)){const a=n(i,e);try{const e=T(a),n=o(t,a);if(r.ignores(n))return;s.push({name:n,path:a,isDirectory:e.isDirectory()})}catch{}}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),s.slice(0,50)}catch{}}const s=[],a=e.toLowerCase(),i=__name((e,c=0)=>{if(!(c>8))try{P(e).forEach(l=>{const d=n(e,l);try{const e=T(d),n=o(t,d);if(r.ignores(n))return;const u=n.toLowerCase();(l.toLowerCase().includes(a)||u.includes(a))&&s.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==l&&i(d,c+1)}catch(e){}})}catch(e){}},"searchRecursively");return i(t),s.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),o=n===a,s=r===a;if(o&&!s)return-1;if(!o&&s)return 1;const i=n.split("/").pop()||"",c=r.split("/").pop()||"",l=i.includes(a),d=c.includes(a);if(l&&!d)return-1;if(!l&&d)return 1;const u=e.name.split("/").length,m=t.name.split("/").length;return u!==m?u-m:e.name.localeCompare(t.name)}),s.slice(0,50)},[]),y=G(e=>{try{const t=P(e),s=[],a=process.cwd(),i=loadGitignore(a);"/"!==e&&s.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=T(r),n=o(a,r);if(i.ignores(n))return;s.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(s),m(0),p(0)}catch{}},[]);H(()=>{if(s.trim()){const e=f(s);d(e),m(0),p(0)}else y(i)},[i,y,s,f]),Z((n,r)=>{if(r.escape)t();else if(r.upArrow)m(e=>{const t=Math.max(0,e-1);return t<g&&p(t),t});else if(r.downArrow)m(e=>{const t=Math.min(l.length-1,e+1);return t>=g+h&&p(t-h+1),t});else{if(r.rightArrow){const e=l[u];if(!e)return;return void(e.isDirectory&&!s.trim()&&c(a(e.path)))}if(r.return){const t=l[u];if(!t)return;return void e(t.path)}}});const w=l.slice(g,g+h);return B.createElement(V,{flexDirection:"column",paddingLeft:1},B.createElement(V,{marginBottom:1,flexDirection:"column"},B.createElement(K,{color:"dim"},s.trim()?`Searching for: "${s}"`:`Files: ${i}`),B.createElement(K,{color:"dim"},s.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===w.length?B.createElement(K,{color:"dim"},s.trim()?`No files found matching "${s}"`:"No files found in this directory"):w.map((e,t)=>{const n=g+t,r=e.name,o=n===u;return B.createElement(K,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList");Tt(),$t(),xn(),Tt();var vc=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20)return null;const r=__name(e=>e>=90?"red":e>=70?"yellow":"dim","getColor"),o=`context: ${n}% left before auto-compact`;return B.createElement(V,{paddingRight:1},B.createElement(K,{color:r(t)},o))},"ContextUsage");Tt(),cr();var bc=__name(()=>{const[e,t]=z("continuous learning"),n=W([]),r=W(0),o=W(null),s=W(!1);H(()=>{const e=__name(e=>"analyzing"===e.type?(s.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):s.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(s.current=!1,void(n.current.length>0?(r.current=0,a()):t("continuous learning"))):void 0,"handleNewEvent"),a=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const s="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,a()},s)},"cycleThroughNextEvent");return ei.on("new-event",e),()=>{ei.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const a=9+e.length+9>er;let i=e;return i=truncateString(a?{text:e,maxChars:er}:{text:e,maxChars:er-9-9}),B.createElement(V,null,!a&&B.createElement(K,{color:"green"},"● taste: "),B.createElement(K,null,i),!a&&B.createElement(K,{dimColor:!0}," (ctrl+t)"))},"LearningFeedMini");Tt();var Cc=__name(({mode:e,pendingExitKey:t})=>t?B.createElement(K,{dimColor:!0},"Press Ctrl+C again to exit"):"auto-accept"===e?B.createElement(V,{flexDirection:"row"},B.createElement(K,{color:"#E4CCFF"},"» accept edits on "),B.createElement(K,{dimColor:!0},"(shift+tab)")):"plan"===e?B.createElement(V,{flexDirection:"row"},B.createElement(K,{color:"#FFB86C"},"plan mode "),B.createElement(K,{dimColor:!0},"(shift+tab)")):B.createElement(K,{color:"dim"},"? for shortcuts"),"ModeIndicator");Tt(),Tt();var Pc=__name(({url:e,text:t,dimColor:n=!1,color:r})=>{const o=`]8;;${e}${t}]8;;`;return B.createElement(K,{dimColor:n,color:r},o)},"TerminalLink"),Tc=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?"#FBBF24":"#A78BFA";return B.createElement(B.Fragment,null,t&&B.createElement(K,{dimColor:!0}," · "),B.createElement(K,{color:n},"PR "),B.createElement(Pc,{url:e.url,text:`#${e.number}`,dimColor:!0}))},"PRLinkBadge"),Ac=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?B.createElement(B.Fragment,null,t&&B.createElement(K,{dimColor:!0}," · "),B.createElement(K,{color:"connected"===e.type?"green":"yellow"},e.message)):null,"ConnectionIndicatorBadge"),xc=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:a,connectionIndicator:i,pendingExitKey:c,updateStatus:l,updateFailedInfo:d,currentProvider:u,showProviderInfo:m,isBashMode:g,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y})=>{const w=e>=60;return B.createElement(B.Fragment,null,B.createElement(V,{flexDirection:"column",paddingLeft:1},"auto-accept"!==r&&"plan"!==r||c?B.createElement(V,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(V,{flexDirection:"row",columnGap:0},n&&!c?B.createElement(K,{color:"#5FAFAF"},t):B.createElement(Cc,{mode:r,pendingExitKey:c}),!c&&B.createElement(Tc,{prInfo:o}),!c&&B.createElement(Ac,{indicator:i})),w&&B.createElement(V,{flexDirection:"column",alignItems:"flex-end"},s&&B.createElement(bc,null),a&&B.createElement(vc,{usage:a}))):B.createElement(B.Fragment,null,B.createElement(V,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(Cc,{mode:r}),w&&s&&B.createElement(bc,null)),B.createElement(V,{flexDirection:"row",justifyContent:"space-between",width:e-1},B.createElement(V,{flexDirection:"row",columnGap:0},B.createElement(K,{color:n?"#5FAFAF":void 0,dimColor:!n},t),B.createElement(Tc,{prInfo:o}),B.createElement(Ac,{indicator:i})),w&&a&&B.createElement(vc,{usage:a}))),(l||d||m&&u)&&B.createElement(V,{flexDirection:"row",columnGap:1},l&&B.createElement(K,null,ke.tick," ","Command Code"," updated:"," ",B.createElement(K,{dimColor:!0},"v",l.updatedFrom),B.createElement(K,{dimColor:!0}," ",ke.arrowRight," "),B.createElement(K,null,"v",l.updatedTo)),!l&&d&&B.createElement(K,{color:"yellow",dimColor:!0},ke.info," Update available:"," ",d.currentVersion," ",ke.arrowRight," ",d.latestVersion),m&&u&&B.createElement(K,{color:"green",dimColor:!0},ke.bullet," Provider:"," ",getProviderDisplayName(u)))),g&&B.createElement(V,{paddingLeft:1},B.createElement(K,{color:"green"},"! for bash mode")),h&&p&&B.createElement(V,{paddingLeft:1},B.createElement(K,{color:"#E4CCFF"},"SHARED: ",p.url," (copied to clipboard)")),f&&B.createElement(V,{paddingLeft:1},B.createElement(K,{color:f.includes("NOT SHARED")?"red":"#E4CCFF"},f)),y&&B.createElement(V,{paddingLeft:1},B.createElement(K,{color:"#E4CCFF"},y)))},"BottomIndicator");Tt(),cr();var Ic=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=z([]),[o,s]=z(0),[a,i]=z(!0);H(()=>{c()},[]);const c=__name(async()=>{i(!0);const e=await Fa.listSessions();r(e.slice(0,30)),i(!1)},"loadSessions");if(Z((r,a)=>{a.escape?t():a.upArrow?s(e=>Math.max(0,e-1)):a.downArrow?s(e=>Math.min(n.length-1,e+1)):a.return&&n.length>0&&o<n.length&&e(n[o].id)}),a)return B.createElement(V,{flexDirection:"column",paddingLeft:2},B.createElement(K,{color:"gray"},"Loading sessions..."));if(0===n.length)return B.createElement(V,{flexDirection:"column",paddingLeft:2},B.createElement(K,{color:"gray"},"No previous sessions found"),B.createElement(K,{color:"dim",dimColor:!0},"Press ESC to go back"));const l=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),d=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),u=__name(e=>truncateString({text:d(e),maxChars:Xn}),"truncateMessage"),m=__name(e=>e.title?d(e.title):u(e.firstMessage),"getSessionSummary");return B.createElement(V,{flexDirection:"column",paddingLeft:1,width:"100%"},B.createElement(K,{color:"cyan",bold:!0},"Resume Session"),B.createElement(K,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),B.createElement(V,{marginTop:1}),B.createElement(V,{columnGap:2,marginBottom:1},B.createElement(V,{width:5},B.createElement(K,{color:"gray"}," ")),B.createElement(V,{width:13},B.createElement(K,{color:"gray"},"Modified")),B.createElement(V,{width:20},B.createElement(K,{color:"gray"},"Git Branch")),B.createElement(V,{width:11},B.createElement(K,{color:"gray"},"# Messages")),B.createElement(V,null,B.createElement(K,{color:"gray"},"Summary"))),B.createElement(V,{columnGap:2},B.createElement(V,{flexDirection:"column",width:5},n.map((e,t)=>B.createElement(K,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${ke.pointer} ${t+1}.`:` ${t+1}.`))),B.createElement(V,{flexDirection:"column",width:13},n.map((e,t)=>B.createElement(K,{key:`mod-${e.id}`,color:o===t?"white":"gray"},l(e.lastModified)))),B.createElement(V,{flexDirection:"column",width:20},n.map((e,t)=>B.createElement(K,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),B.createElement(V,{flexDirection:"column",width:11},n.map((e,t)=>B.createElement(K,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),B.createElement(V,{flexDirection:"column"},n.map((e,t)=>B.createElement(K,{key:`summary-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},m(e))))))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete · Esc":"Delete · Esc":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],o=0;for(let s=0;s<e;s++){const e=`[Image #${s+1}]`.length,a=e+(r.length>0?1:0);r.length>0&&o+a>t?(n.push(r),r=[s],o=e):(r.push(s),o+=a)}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 createOSC8Link(e,t,n=!0){return`${n?"[33m":""}]8;;${e}${t||e}]8;;${n?"[0m":""}`}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const o=`[Image #${e+1}]`,s=n?createOSC8Link(`file://${n}`,o,!1):o;return B.createElement(K,null,r?" ":"",t?B.createElement(K,{inverse:!0},o):s)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:o}){if(0===e.length)return null;const s=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:o}),a=Math.max(1,r-(s.length+2)),i=buildImageRows({imageCount:e.length,rowWidth:a});return B.createElement(V,{flexDirection:"column",width:"100%",alignItems:"flex-end"},i.map((e,r)=>B.createElement(V,{key:r,flexDirection:"row"},B.createElement(V,{flexShrink:0,marginRight:1},0===r&&B.createElement(K,{color:"dim"},s)),B.createElement(V,{flexDirection:"row"},e.map((e,r)=>B.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Tt(),Tt(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),Tt(),__name(createOSC8Link,"createOSC8Link"),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Tt(),Ur();var $c=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=z(null),[s,a]=z(!1),i=W(!1),c=W(null),[l,d]=z(!1),[u,m]=z("connected"),g=W(null),p=W(null),h=G((e,t)=>{p.current&&(clearTimeout(p.current),p.current=null),m(e),d(!0),void 0!==t&&(p.current=setTimeout(()=>{d(!1)},t))},[]),f=G(()=>{p.current&&(clearTimeout(p.current),p.current=null)},[]),y=G(async(e=!1)=>{if(!i.current){i.current=!0;try{let t=c.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new Nr,c.current=t;const r=e?200:500;n=await t.connect(r)}const r=g.current;if(null===r?n&&h("connected",3e3):r!==n&&(n?h("connected",2e3):h("disconnected",5e3)),g.current=n,a(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),c.current=null),o(r)}else o(null)}catch{!0===g.current&&h("disconnected",5e3),g.current=!1,a(!1),o(null),c.current?.disconnect(),c.current=null}finally{i.current=!1}}},[h]);return H(()=>{if(!t||n)return;y(!0);const e=setInterval(()=>y(!1),500);return()=>{clearInterval(e),f(),c.current?.disconnect(),c.current=null}},[t,n,y,f]),{context:r,connected:s,refresh:y,connectionIndicator:{visible:l,message:"connected"===u?"IDE ✓":"IDE disconnected",type:u}}},"useVSCodeContext");Tt();var Rc=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:o}=e.activeFile;t.push(`File: ${n} (${r}, line ${o.line})`)}if(e.selection){const{text:n,startLine:r,endLine:o}=e.selection,s=e.activeFile?.language??"";t.push(`Selected lines ${r}-${o}:`),t.push(`\`\`\`${s}`);const a=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"</ide-context>");t.push(a),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Tt();var Dc=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),Mc=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const o=e?t?.activeFile:null;if(o?.relativePath){const e=o.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"),Nc=["\n","\r","[13;2u","[27;2;13~","[27;2;13~","[13;2u"],Oc=["","[118;5u","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isNewlineShortcutKey(e){const{inputChar:t,key:n,isPasting:r}=e;return!r&&(!(!n.return||!n.shift)||!(!n.ctrl||!n.return)||!(!n.ctrl||"j"!==t)||!("\r"!==t||n.return||n.ctrl||n.shift||n.meta)||Nc.includes(t))}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isNewlineShortcutKey,"isNewlineShortcutKey"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var Fc=__name(()=>B.createElement(V,{flexDirection:"column",paddingLeft:1},B.createElement(K,{color:"dim",bold:!0},"Available Shortcuts:"),B.createElement(V,{columnGap:4},B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"dim"},"! for bash mode"),B.createElement(K,{color:"dim"},"/ for commands"),B.createElement(K,{color:"dim"},"@ for file paths"),B.createElement(K,{color:"dim"},"shift + tab to toggle auto-accept")),B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"dim"},"double tap esc to clear input"),B.createElement(K,{color:"dim"},"ctrl + j / shift + ⏎ for newline"),B.createElement(K,{color:"dim"},"ctrl + g to open in editor"),B.createElement(K,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Lc=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:s="Enter your input…",showFileList:a,setShowFileList:i,fileSearchQuery:c,setFileSearchQuery:l,onCommand:d,contextUsage:u,tasteLearning:m=!1,tasteUsage:g=!1,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,updateStatus:w,updateFailedInfo:E,currentProvider:S,showProviderInfo:k,permissionMode:v="standard",onToggleAutoAccept:b,hintMessage:C,historyManager:P,pendingExitKey:T=null,onOverlayVisibilityChange:A,onDoubleEscapeEmpty:x,onAltP:I,isProcessing:$=!1,ideContextEnabled:R=!0})=>{const[D,M]=z(0),[N,O]=z(!1),[F,L]=z(!1),[_,U]=z(!1),[j,J]=z(!1),[Y,X]=z(""),[ee,te]=z(!1),ne=W(0),re=W(0),[oe,se]=z([]),[ae,ie]=z([]),[ce,le]=z(-1),[de,ue]=z(""),me=W(!1),ge=W(!1),[pe,he]=z(-1),[fe,ye]=z(""),we=W(0),{isEditorOpen:Ee,editorError:Se,handleOpenInEditor:ve,clearEditorError:be}=useExternalEditor({input:e,setInput:n,setInputKey:M,onEditorClose:__name(()=>{me.current=!1},"onEditorClose")}),{handlePaste:Ce,resetPasteState:Pe,isPasting:Te}=useBracketedPaste({input:e,detectedContent:oe,setInput:n,setDetectedImages:ie,setDetectedContent:se,incrementInputKey:__name(()=>M(e=>e+1),"incrementInputKey")}),{context:Ae,connected:xe,refresh:Ie,connectionIndicator:$e}=$c({enabled:R,paused:$}),{stdout:Re}=Q(),De=Re?.columns??80,{pr:Me}=yc();H(()=>{const e=a||j||ee;A?.(e)},[a,j,ee,A]);const Ne=G(()=>{ie([]),le(-1)},[]),Oe=G(()=>{n(""),L(!1),J(!1),X(""),te(!1),se([]),Ne(),ue(""),Pe(),he(-1),ye(""),M(e=>e+1)},[n,Pe,Ne]),Fe=G(()=>{me.current=!0,n(e+"\n"),M(e=>e+1),setTimeout(()=>{me.current=!1},0)},[e,n]);Z(async(t,r)=>{if(-1!==ce&&r.leftArrow)return void le(prevImageIndex({currentIndex:ce,imageCount:ae.length}));if(-1!==ce&&r.rightArrow)return void le(nextImageIndex({currentIndex:ce,imageCount:ae.length}));if(r.upArrow){if(a||j||ee)return;const t=e.indexOf("\n"),r=-1===t||we.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ae.length,selectedImageIndex:ce,historyIndex:pe}))return void le(ae.length-1);if(-1!==ce&&le(-1),0!==e.length&&-1===pe&&!r)return;const o=P?.count()??0;if(0===o)return;-1===pe&&ye(e);const s=Math.min(pe+1,o-1);return void(s!==pe&&(he(s),n(P?.getAt(s)||""),M(e=>e+1)))}if(r.downArrow){if(a||j||ee)return;if(-1===pe)return;const t=e.lastIndexOf("\n");if(!(-1===t||we.current>t))return;const r=pe-1;return he(r),n(-1===r?fe:P?.getAt(r)||""),void M(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Ne();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return me.current=!0,void ve();if(getIsExpandToolShortcut(r,t))return me.current=!0,n(e),M(e=>e+1),void setTimeout(()=>{me.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Te()}))return ge.current=!0,Fe(),void setTimeout(()=>{ge.current=!1},0);if(r.meta&&r.backspace)return void Oe();if(r.meta&&"w"===t)return me.current=!0,void Oe();const o=r.ctrl&&"v"===t||Oc.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();return r&&(ie(e=>[...e,r]),n(t),M(e=>e+1)),void(me.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!==ce&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ae,index:ce});return ie([...e]),void le(t)}if(r.escape){if(-1!==ce)return void le(-1);if(j)return;if(ee)return te(!1),n(de),void M(e=>e+1);const t=Date.now();return t-ne.current<500?(e.length>0?Oe():x?.(),ne.current=0,re.current=0):(ne.current=t,N||F||(re.current=t)),O(!1),void L(!1)}N&&(r.backspace||r.delete)&&0===e.length&&O(!1)}});const Le=G(async t=>{if(Ee)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void I?.();if(await Ce(t))return;if(me.current)return void(me.current=!1);-1!==pe&&he(-1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!N)return O(!0),n(""),void M(e=>e+1);if("!"===s&&!F)return O(!1),L(!0),n(""),void M(e=>e+1)}if("/"!==s||j||"/"!==t||(J(!0),X("")),j&&!t.startsWith("/")&&(J(!1),X("")),j&&t.startsWith("/")){const e=t.substring(1);X(e)}"@"!==s||a||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(i(!0),l(""));const c=t.lastIndexOf("@");if(t.length<e.length&&-1!==c&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(c+1),n=!e.includes(" "),r=c>0?t[c-1]:"";n&&isPrecededByWhitespace(r)&&(i(!0),l(e))}if(a)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),l("");else{const n=t.substring(e+1);l(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);l(e),i(!1)}else l(n)}}N&&(t!==e||t.length<e.length)&&O(!1),Se&&be(),0===t.length&&(L(!1),J(!1),X(""),te(!1),Ne(),se([]),l(""),ue(""),Pe()),n(t)},[N,e,n,a,i,j,F,ae,pe,Ce,Pe,I,Se,be,Ee,Ne]),_e=G(async()=>{if(Ie(),re.current=0,N)return void O(!1);let n=e.trim();if(!F&&n.startsWith("/"))return P?.add(n),d&&d(n),L(!1),J(!1),X(""),Ne(),se([]),he(-1),void ye("");n.length>0&&P?.add(n),he(-1),ye("");let r=[];const o=ae.length>0,s=oe.length>0;if(!F&&o&&(r=[...ae]),!F&&s){let e=n;oe.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:F?"bash":"user",images:r,ideContext:Ae?Rc(Ae):void 0}),L(!1),J(!1),X(""),Ne(),se([])},[t,d,N,e,F,ae,oe,P,Ie,Ne]),Ue=G(t=>{const r=o(process.cwd(),t);let s;if(a&&""!==c){const t=e.lastIndexOf("@");s=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else s=`${e}${r} `;n(s),i(!1),l(""),M(e=>e+1)},[n,i,e,a,c,l]),je=G(()=>{i(!1),l("")},[i,l]),Be=G(t=>{if("/resume"===t)P?.add(t),he(-1),ye(""),ue(e),J(!1),X(""),te(!0),n(""),M(e=>e+1);else{const e=Object.values(wc).includes(t);J(!1),X(""),e?(P?.add(t),he(-1),ye(""),n(""),M(e=>e+1),d&&d(t)):(n(t+" "),M(e=>e+1))}},[d,n,e,P]),ze=G(()=>{J(!1),X(""),n(""),he(-1),ye(""),M(e=>e+1)},[n]),We=G(e=>{te(!1),n(""),ue(""),he(-1),ye(""),M(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),He=G(()=>{te(!1),n(de),he(-1),ye(""),M(e=>e+1)},[de,n]),Ge=G(e=>{we.current=e},[]),qe=q(()=>{const t=Me&&("OPEN"===Me.state||"MERGED"===Me.state);return"auto-accept"===v||"plan"===v||xe||t?!N&&!ee:!N&&0===e.length&&!F&&!ee},[N,e,F,ee,v,xe,Me]),Ve=W(new Map),Ke=q(()=>ae.map((e,t)=>{if(Ve.current.has(e))return Ve.current.get(e)??null;const n=saveTempImage(e,t+1);return Ve.current.set(e,n),n}),[ae]),Je=__name(()=>N||a||j||ee||_?0:qe||T||F?3:4,"getBottomMargin");return B.createElement(V,{width:"100%",flexDirection:"column",marginBottom:Je()},!ee&&B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(ImageRowsDisplay,{detectedImages:ae,selectedImageIndex:ce,imageTempPaths:Ke,termWidth:De,inHistory:-1!==pe}),B.createElement(K,{color:F?"green":"gray"},ke.line.repeat(De)),B.createElement(TextInput,{key:D,value:e,placeholder:Ee?"Save and close the editor to continue...":s,onChange:Le,onSubmit:()=>{if(!ge.current)return Date.now()-re.current<100?(re.current=0,void Fe()):void(a||j||ee||Ee||_e());ge.current=!1},showCursor:!Ee&&r&&-1===ce,onCursorChange:Ge,prefix:`${F?"!":ke.pointer} `,prefixColor:F?"green":"white"}),B.createElement(K,{color:F?"green":"gray"},ke.line.repeat(De))),N&&B.createElement(Fc,null),_&&B.createElement(V,{paddingTop:1},B.createElement(K,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),a&&B.createElement(kc,{onSelectFile:Ue,onClose:je,searchQuery:c}),j&&B.createElement(Sc,{onSelectCommand:Be,onClose:ze,searchQuery:Y}),ee&&B.createElement(Ic,{onSelectSession:We,onClose:He}),(qe||T)&&B.createElement(xc,{termWidth:De,indicatorText:Mc(xe,Ae,De),isIDEIndicator:Dc(xe,Ae),permissionMode:v,prInfo:Me,tasteLearning:m,contextUsage:u,connectionIndicator:$e,pendingExitKey:T,updateStatus:w,updateFailedInfo:E,currentProvider:S,showProviderInfo:k,isBashMode:F,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y}),Se&&B.createElement(V,{paddingLeft:1,flexDirection:"column"},B.createElement(K,{color:"yellow"},Se)))},"InputBox"),_c=B.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:a,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:S,updateFailedInfo:k,currentProvider:v,showProviderInfo:b,permissionMode:C,onToggleAutoAccept:P,hintMessage:T,historyManager:A,pendingExitKey:x,onResetPendingExitKey:I,onDoubleEscapeEmpty:$,retryAttempt:R,onAltP:D})=>{const[M,N]=z(0),O=W(o);return H(()=>{x&&o!==O.current&&o.length>0&&I?.(),O.current=o},[o,x,I]),H(()=>{if(!t)return void N(0);const e=setInterval(()=>{N(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),B.createElement(V,{flexDirection:"column"},B.createElement(sc,{messages:e}),B.createElement(V,{flexDirection:"row",justifyContent:"space-between"},B.createElement(V,{flexDirection:"column"},(t||n.isExecuting)&&null===R&&B.createElement(ec,{tokens:m,timeElapsed:M,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),T&&B.createElement(V,{marginLeft:1},B.createElement(K,{dimColor:!0}," ","⎿"," Tip: ",T)))),B.createElement(Lc,{input:o,setInput:s,onSubmit:a,placeholder:"Ask your question...",showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:S,updateFailedInfo:k,currentProvider:v,showProviderInfo:b,permissionMode:C,onToggleAutoAccept:P,hintMessage:T,historyManager:A,pendingExitKey:!x||t||n.isExecuting?null:x,onDoubleEscapeEmpty:$,onAltP:D,isProcessing:t}))});Tt();var Uc=__name(({onClose:e})=>{const[t,n]=z(ei.getEvents());Z((t,n)=>{n.ctrl&&"t"===t&&(hi(),e())},{isActive:!0}),H(()=>{const e=__name(()=>{n(ei.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return ei.on("new-event",e),ei.on("cleared",t),()=>{ei.off("new-event",e),ei.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`confidence: ${parseFloat(e).toString()}%`}const a={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:a,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),s=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),a=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails");return B.createElement(V,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(Ve,{name:"vice"},B.createElement(K,null,Eo()))),B.createElement(V,{marginBottom:1,width:"100%",justifyContent:"space-between"},B.createElement(V,null,B.createElement(K,{bold:!0},"Learning Feed"),B.createElement(K,{dimColor:!0}," - Real-time taste learning activity")),B.createElement(K,{dimColor:!0},"Press ctrl+t to close")),B.createElement(V,{flexDirection:"column"},0===t.length?B.createElement(V,null,B.createElement(K,{dimColor:!0},"No learning events yet...")):B.createElement(V,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:i}=o(e.message),c="moved"===t?a(e.details):null,l="upgraded"===t||"downgraded"===t?s(r):null;return B.createElement(V,{key:e.id,marginBottom:1},B.createElement(V,{flexDirection:"column"},B.createElement(V,null,B.createElement(K,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),c?B.createElement(K,{dimColor:!0}," (",c.fullPath,")"):e.details?B.createElement(K,{dimColor:!0}," (",e.details,")"):null),B.createElement(V,{marginLeft:1},B.createElement(K,{dimColor:!0},"⎿"," "),c?B.createElement(B.Fragment,null,B.createElement(K,null,c.category," package ("),B.createElement(K,{dimColor:!0},c.oldPath),B.createElement(K,null," → ",c.newPath),B.createElement(K,null,")")):l?B.createElement(B.Fragment,null,B.createElement(K,null,l.text," ("),B.createElement(K,{dimColor:!0},"confidence: "),B.createElement(K,{dimColor:!0},l.oldPercent,"%"),B.createElement(K,null," → "),B.createElement(K,{color:l.diff>0?"green":"red"},l.newPercent,"%"),B.createElement(K,null,")")):B.createElement(B.Fragment,null,B.createElement(K,null,r),i&&B.createElement(K,{dimColor:!0}," (",i,")")))))}return B.createElement(V,{key:e.id,marginBottom:1},B.createElement(K,{dimColor:!0},ke.pointerSmall," ",e.message))}))))},"LearningFeedFull");Tt(),$t(),nn();var jc=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(0),[s,a]=z(!0),[i,c]=z(null);H(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),a(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),a(!1)}},"loadMemoryFiles")()},[]);const l=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(Z((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&l(d[r]),"1"===t&&d[0]&&l(d[0]),"2"===t&&d[1]&&l(d[1]))}),s)return B.createElement(V,{paddingLeft:1,paddingTop:1},B.createElement(K,{color:"dim"},"Loading memory files..."));if(i)return B.createElement(V,{paddingLeft:1,paddingTop:1},B.createElement(K,{color:"red"},"❌ ",i));const u=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return B.createElement(V,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},B.createElement(V,null,B.createElement(K,{color:"white",bold:!0},"Select memory to edit:")),B.createElement(V,{columnGap:4,marginTop:1},B.createElement(V,{flexDirection:"column"},u.map((e,t)=>B.createElement(K,{key:t,color:r===t?"white":"dim"},r===t?`${Qt} `:" ",e.label))),B.createElement(V,{flexDirection:"column"},u.map((e,t)=>B.createElement(K,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector");Tt(),Tt(),Tt();var Bc=class extends Je{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}list(e,t=!1,n=""){let r=super.list(e,t,n);return r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),r}},zc=new Ke;zc.setOptions({renderer:new Bc({strong:ee.bold,em:ee.italic,del:ee.strikethrough,codespan:ee.yellow,code:ee.yellow,heading:ee.bold.underline,firstHeading:ee.bold.underline,link:ee.cyan,href:ee.cyan.underline,blockquote:ee.gray.italic,table:ee.reset,hr:ee.reset,paragraph:ee.reset,html:ee.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var Wc=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=q(()=>{if(!e)return"";const t=[],n=e.replace(Wc,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=zc.parse(n);return"string"!=typeof r?e:r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").trim()}catch{return e}},[e]);return B.createElement(K,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return B.createElement(V,null,B.createElement(K,null,ke.nodejs),B.createElement(V,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage"),Tt(),nn();var Hc={"Interrupted by user":"Interrupted by user","Insufficient credits":Jt};function UserMessage({content:e}){const t="Interrupted by user"===e,n="Insufficient credits"===e,r=e.startsWith("Error:"),o=t||n||r;let s=o&&Hc[e]||e;return B.createElement(V,{paddingX:1,backgroundColor:o?void 0:"#333333"},B.createElement(K,{color:o?"red":"#AAAAAA",bold:!o},ke.pointer),B.createElement(V,{marginLeft:1},B.createElement(K,{color:o?"red":"white",wrap:"wrap"},s)))}__name(UserMessage,"UserMessage"),Tt(),Vt(),In(),cr();var Gc="#6B7280";function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,dimDiff:a=!1,maxLines:i}){const c=Ye.diffLines(e,t);let l=0,d=0,u=0,m=0;c.forEach(e=>{e.added?(l+=e.count||1,m+=e.count||1):e.removed&&(d+=e.count||1,m+=e.count||1)});const g=[];c.forEach((e,t)=>{const n=e.value.split("\n").filter(e=>e);e.added||e.removed?n.forEach((n,r)=>{e.removed?(u++,g.push(B.createElement(V,{key:`${t}-${r}-removed`,width:"100%"},B.createElement(K,{color:"gray",dimColor:a},u.toString().padStart(3)," "),B.createElement(V,{backgroundColor:"#712F37"},B.createElement(K,{dimColor:a},"-"),B.createElement(K,{dimColor:a}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(B.createElement(V,{key:`${t}-${r}-added`,width:"100%"},B.createElement(K,{color:"gray",dimColor:a},u.toString().padStart(3)," "),B.createElement(V,{backgroundColor:"#325B30"},B.createElement(K,{dimColor:a},"+"),B.createElement(K,{dimColor:a}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:B.createElement(V,{flexDirection:"column"},o&&!r&&B.createElement(K,{color:"gray"},"Updated"," ",B.createElement(K,{color:"white",bold:!0},n)," ","with ",B.createElement(K,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",B.createElement(K,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&B.createElement(K,{color:"red"},"Rejected update to",B.createElement(K,{color:"red"},` ${n}`)),B.createElement(V,{flexDirection:"column",marginLeft:s},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=Ys(e);return t?B.createElement(V,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?"☒":"☐";let r,o=!1;switch(e.status){case"completed":r="#22C55E",o=!0;break;case"in_progress":r="#E4CCFF";break;default:r="white"}return B.createElement(V,{key:e.id||t,flexDirection:"row"},B.createElement(V,{width:2},B.createElement(K,{color:r},n)),B.createElement(K,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):B.createElement(K,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:a=!1}){const i="Thinking…"===e,c="Todos"===e,l="Edit"===e,d=!0===s?.isTasteFile,u=s?.tasteCategory,m=!0===s?.permissionDenied,g=!i&&!c&&!d,{name:p}=detectTerminal(),h="iTerm2"===p?"shift":"ctrl",f=!0===s?.isAgent,y="Shell"===e,w=t&&f?(()=>{const e=t.split(/[.\n]/)[0];return e?e+(t.includes(".")||t.includes("\n")?".":""):t})():y&&t&&!a?truncateCommand({command:t}):t,E=!i&&w&&!d,S=s?.status,k=s?.tokensUsed||0,v="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0;let b,C;if(r)b="yellow",C="→";else if(o)b="red",C=ke.nodejs;else if(i)b=Gc,C="✻";else if(c&&n){const e=Ys(n),t=e?.every(e=>"completed"===e.status);b=t?"#22C55E":"#D4A017",C=ke.nodejs}else b="#22C55E",C=ke.nodejs;return B.createElement(V,null,i&&B.createElement(K,{color:b},C),B.createElement(V,{flexDirection:"column",marginLeft:i?1:0},B.createElement(V,null,i?B.createElement(B.Fragment,null,B.createElement(K,{color:Gc},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!a&&B.createElement(K,{dimColor:!0},"(",`${h}+o to expand`,")")):d?B.createElement(B.Fragment,null,B.createElement(K,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),B.createElement(K,null," ","Using your taste ",u?"package of ":"packages",u&&B.createElement(K,{bold:!0},u))):B.createElement(K,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),E&&B.createElement(K,null," ",B.createElement(Markdown,null,`(${w})`))),f&&("running"===S||n)&&B.createElement(V,{columnGap:1,marginLeft:g?1:0},g&&B.createElement(K,null,"⎿"," "),"running"===S?B.createElement(K,{color:"gray"},"Running (",formatTime2(v)," | ",formatTokens(k),")"):"interrupted"===S?B.createElement(K,{color:"red",wrap:"wrap"},"Interrupted by user"):"error"===S||o?B.createElement(K,{color:"red",wrap:"wrap"},n," (",formatTime2(v)," | ",formatTokens(k),")"):"Interrupted by user"===n?B.createElement(B.Fragment,null,B.createElement(K,{color:"red",wrap:"wrap"},"Interrupted by user")):B.createElement(B.Fragment,null,B.createElement(K,{wrap:"wrap"},"Done"),B.createElement(K,{color:"gray"}," ","(",formatTime2(v)," | ",formatTokens(k),")"))),n&&!d&&!f&&B.createElement(V,{columnGap:1,marginLeft:g?1:0},g&&B.createElement(K,null,"⎿"," "),c?formatTodosForDisplay(n):i?a?B.createElement(V,{width:"100%",flexDirection:"column"},B.createElement(K,null," "),B.createElement(K,{color:Gc,wrap:"wrap",italic:!0},n)):null:l&&s?.oldValue&&s?.newValue?B.createElement(V,{flexDirection:"column"},(()=>{const e=a?void 0:Jn,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:m,permissionDenied:m,maxLines:e});return B.createElement(B.Fragment,null,n,r&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"… (",o-Jn," more lines) (",`${h}+o to expand`,")")))})(),m&&n&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"red",wrap:"wrap"},n))):B.createElement(V,{width:"100%"},B.createElement(K,{color:o?"red":"",wrap:"wrap"},a||o?n:(()=>{const{text:t,isTruncated:r,remainingLines:o}=truncateToVisualLines({output:n,maxVisualLines:"Question"===e?Kn:Vn,maxChars:"Question"===e?1/0:Zn});return B.createElement(B.Fragment,null,t,r&&"Question"!==e&&B.createElement(K,{dimColor:!0},"\n",o>0?`... +${o} lines (${h}+o to expand)`:`... (${h}+o to expand)`))})()))),r&&!f&&B.createElement(V,{columnGap:1,marginLeft:1},B.createElement(K,null,"⎿"," "),B.createElement(K,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,s;return n?(o="yellow",s="→"):r?(o="red",s="✗"):(o="green",s="✓"),B.createElement(V,null,B.createElement(K,{color:o},s),B.createElement(V,{flexDirection:"column",marginLeft:1},B.createElement(V,null,B.createElement(K,{color:"gray"},"$ "),B.createElement(K,{color:o,bold:!0},e)),B.createElement(V,{columnGap:1,marginLeft:1},B.createElement(K,null,"⎿"," "),B.createElement(K,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),Tt(),__name(BashMessage,"BashMessage"),Tt(),Tt(),$t();Tt(),$t();var qc="Coding agent that continuously learns your taste of writing code.",Vc=34,Kc=[{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:"Esc Esc",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],Jc=[{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:"--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"}],Yc=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/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:"/add-dir",description:"Manage additional directory scope"},{key:"/exit",description:"Exit the REPL"}],Qc=[{key:"cmd info",description:"Display system information"},{key:"cmd config",description:"Manage CLI configuration"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Zc=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Xc=[{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"}],el='Start with a prompt: cmd "fix the login bug"';Tt(),Un();var tl="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]:[tl]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||tl;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||tl}catch{return tl}}function HelpMessage(){const e=getInvokedCommandName(),t=q(()=>Yc.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return B.createElement(V,{flexDirection:"column",paddingY:1},B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(V,null,B.createElement(K,{bold:!0},"Command Code"),B.createElement(K,{color:"gray"}," v","0.11.8")),B.createElement(K,{color:"gray"},qc)),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Usage"),B.createElement(V,{paddingLeft:2},B.createElement(K,null,e," <command> [options]"))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Options"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Jc.map(t=>B.createElement(V,{key:t.key},B.createElement(K,null,t.key.replace(/^cmd/,e).padEnd(Vc)),B.createElement(K,{color:"gray"},t.description))))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Commands"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Qc.map(t=>B.createElement(V,{key:t.key},B.createElement(K,null,t.key.replace(/^cmd/,e).padEnd(Vc)),B.createElement(K,{color:"gray"},t.description))))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Slash Commands"),B.createElement(V,{flexDirection:"column",paddingLeft:2},t.map(e=>B.createElement(V,{key:e.key},B.createElement(K,null,e.key.padEnd(Vc)),B.createElement(K,{color:"gray"},e.description))))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Keyboard Shortcuts"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Kc.map(e=>B.createElement(V,{key:e.key},B.createElement(K,null,e.key.padEnd(Vc)),B.createElement(K,{color:"gray"},e.description))))),B.createElement(V,{flexDirection:"column",marginBottom:1},B.createElement(K,{bold:!0},"Examples"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Xc.map(t=>B.createElement(V,{key:t.key},B.createElement(K,null,t.key.replace(/^cmd/,e).padEnd(Vc)),B.createElement(K,{color:"gray"},t.description))))),B.createElement(V,{marginBottom:1},B.createElement(K,{color:"cyan"},"❯"),B.createElement(K,{color:"gray"}," ",el.replace(/cmd/,e))),B.createElement(V,{flexDirection:"column"},B.createElement(K,{bold:!0},"Links"),B.createElement(V,{flexDirection:"column",paddingLeft:2},Zc.map(e=>B.createElement(V,{key:e.key},B.createElement(K,null,e.key.padEnd(Vc)),B.createElement(K,{color:"cyan"},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?B.createElement(HelpMessage,null):B.createElement(V,{flexDirection:"column"},B.createElement(K,{wrap:"wrap"},B.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return B.createElement(V,null,B.createElement(K,{color:"red"},t?ke.pointer:ke.warning),B.createElement(V,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?B.createElement(K,{color:"red",wrap:"wrap"},e):B.createElement(Markdown,{color:"red"},e)))}function AutoCompactMessage({content:e}){return B.createElement(V,null,B.createElement(K,{dimColor:!0},ke.info),B.createElement(V,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(K,{dimColor:!0},e)))}function InfoMessage({content:e,metadata:t}){return t?.isAutoCompact?B.createElement(AutoCompactMessage,{content:e}):B.createElement(V,null,B.createElement(K,{dimColor:!0},ke.info),B.createElement(V,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},B.createElement(K,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return B.createElement(V,{flexDirection:"column",marginBottom:0,marginTop:-1},B.createElement(V,{columnGap:1},B.createElement(K,null,"⎿"," "),B.createElement(V,{flexGrow:1,flexShrink:1,minWidth:0},B.createElement(K,{color:n?"yellow":void 0},e))),t&&B.createElement(V,{marginLeft:3},B.createElement(K,{dimColor:!0},"See ",t)))}function IDEStatusMessage({status:e,ide:t,details:n}){return B.createElement(V,{flexDirection:"column"},B.createElement(V,null,"connected"===e&&B.createElement(K,null,B.createElement(K,{color:"green"},ke.tick),B.createElement(K,null," Connected to "),B.createElement(K,{color:"cyan"},t)),"installed"===e&&B.createElement(K,null,B.createElement(K,{color:"green"},ke.tick),B.createElement(K,null," Installed for "),B.createElement(K,{color:"cyan"},t)),"needs_reload"===e&&B.createElement(K,null,B.createElement(K,{color:"yellow"},ke.circle),B.createElement(K,null," "),B.createElement(K,{color:"cyan"},t),B.createElement(K,null," extension needs reload")),"failed"===e&&B.createElement(K,null,B.createElement(K,{color:"red"},ke.cross),B.createElement(K,null," Install failed")),"not_in_ide"===e&&B.createElement(K,null,B.createElement(K,{color:"yellow"},ke.circle),B.createElement(K,null," Not in IDE"))),n?.map((e,t)=>B.createElement(K,{key:t,dimColor:!0}," ",e)))}function getModelShortName(e){const t=Object.values(St).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"}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),xn(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Tt(),__name(ErrorMessage,"ErrorMessage"),Tt(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(InfoMessage,"InfoMessage"),Tt(),__name(CommandResultMessage,"CommandResultMessage"),Tt(),__name(IDEStatusMessage,"IDEStatusMessage"),Un(),$t(),xn(),__name(getModelShortName,"getModelShortName");var nl=B.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const s=t?["header",...e]:e,a=Eo();getTerminalWidth();const i=getPackageJson().version||"0.0.0",c=o?getModelShortName(o):"sonnet-4.5",l=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",u=l.replace(d,"~"),m=getGitHeaderInfo();return B.createElement(J,{items:s,key:n,style:{width:"100%"}},e=>{if("header"===e)return B.createElement(V,{key:"header",marginBottom:1,flexDirection:"column"},B.createElement(Ve,{name:"vice"},B.createElement(K,null,a.trimEnd())),B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(V,null,B.createElement(K,{color:"gray"},"# "),B.createElement(K,{bold:!0},"Command Code"),B.createElement(K,{color:"gray"}," v",i)),B.createElement(K,{color:"gray"},"# models: ",c," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),B.createElement(V,null,B.createElement(K,{color:"gray"},"# ",u,m&&m.isLocal&&m.branch&&B.createElement(K,{color:"gray"}," (branch: ",m.branch,")")))));const t=e,n=(()=>{switch(t.role){case"user":return B.createElement(UserMessage,{content:t.input});case"assistant":return B.createElement(AssistantMessage,{content:t.input});case"tool":return B.createElement(ToolMessage,{name:Vs(t.name||""),input:t.input,output:t.output||"",isPending:Hs(t),hasError:Ws(t),metadata:t.metadata,expandedOutput:r});case"bash":return B.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:Hs(t),hasError:Ws(t)});case"system":return B.createElement(SystemMessage,{content:t.input});case"info":return B.createElement(InfoMessage,{content:t.input,metadata:t.metadata});case"error":return B.createElement(ErrorMessage,{content:t.input});case"command-result":return B.createElement(CommandResultMessage,{message:t.input,details:t.details,hasError:t.hasError??!1});case"ide-status":return B.createElement(IDEStatusMessage,{status:t.status,ide:t.ide,details:t.details});default:return B.createElement(B.Fragment,null)}})();return B.createElement(V,{key:t.id,marginBottom:1,width:"90%"},n)})});function getModelOptions(){return Object.values(St).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}Tt(),$t(),__name(getModelOptions,"getModelOptions");var rl=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0;return B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(V,null,B.createElement(K,{color:"#E4CCFF",bold:!0},"Select model")),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),B.createElement(He,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const o=r.find(e=>e.label===t),s=o?.value===n,a=e?"green":"gray";return B.createElement(V,null,B.createElement(K,{color:a},` ${(o?.label||t).padEnd(24)}`),B.createElement(K,{dimColor:!0},o?.description),s&&B.createElement(K,{color:"green"}," ✓"))}}),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press "),B.createElement(K,{dimColor:!0,bold:!0},"Esc"),B.createElement(K,{dimColor:!0}," to cancel")))},"ModelSelector");Tt(),$t();var ol=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[o]=z(0),s=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],a=__name(e=>{const t=s.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),i=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),c=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const n=t.basename(e.filePath),r=t.relative(process.cwd(),e.filePath);return r&&!r.startsWith("../")&&r.length<50?r:n||e.filePath}catch{return e.filePath}},"getDisplayPath"),l=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,color:"yellow"},`${l()} ${"edit"===e.action?c():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&B.createElement(V,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c(),marginLeft:0}).diffContent),B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0},"Do you want to ",i()," ",B.createElement(K,{color:"cyan"},c()),"?")),B.createElement(He,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:o,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"cyan"},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(K,{color:t?"cyan":"white"},e.includes("(shift+tab)")?B.createElement(B.Fragment,null,e.split("(shift+tab)")[0],B.createElement(K,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?B.createElement(B.Fragment,null,e.split("(")[0],B.createElement(K,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Tt(),xn();var sl=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,a=n&&-1===s;return B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(V,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},B.createElement(V,null,B.createElement(K,{bold:!0},"Select AI Provider")),n&&B.createElement(V,{flexDirection:"row"},B.createElement(K,{dimColor:!0},"Current: "),B.createElement(K,{color:"green"},getProviderDisplayName(n)),a&&B.createElement(K,{color:"yellow"}," [OAuth enforced]"))),B.createElement(V,{marginBottom:0},B.createElement(K,{dimColor:!0},"Available Providers:")),B.createElement(He,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"cyan":"gray",bold:e},` ${t}`)}),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");Tt();var al=__name(({staticKey:e})=>B.createElement(J,{items:[{staticKey:e}],key:e},()=>B.createElement(K,{key:e},"\0")),"Responsive");function RetryMessage({attempt:e}){const[t,n]=z(0);if(H(()=>{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(V,{marginBottom:1},B.createElement(K,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Tt(),__name(RetryMessage,"RetryMessage"),Tt(),cr(),nn();var il=[{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"}],cl=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=q(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=z(Math.max(0,r.length-1)),[a,i]=z(Math.max(0,r.length-8)),[c,l]=z("checkpoint"),[d,u]=z(null),[m,g]=z(0),p=q(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),h=q(()=>p?il:il.filter(e=>"conversation"===e.mode),[p]);if(H(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),Z((e,p)=>{p.escape?"mode"===c?(l("checkpoint"),u(null),g(0)):n():"checkpoint"===c?p.upArrow?s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t}):p.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(t-8+1),t}):p.return&&r.length>0&&(u(r[o]),l("mode"),g(0)):"mode"===c&&(p.upArrow?g(e=>Math.max(0,e-1)):p.downArrow?g(e=>Math.min(h.length-1,e+1)):p.return&&d&&h[m]&&t({messageId:d.messageId,mode:h[m].mode}))}),0===r.length)return B.createElement(V,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),B.createElement(K,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press "),B.createElement(K,{dimColor:!0,bold:!0},"Esc"),B.createElement(K,{dimColor:!0}," to close")));if("mode"===c&&d)return B.createElement(V,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Restore to: "),B.createElement(K,{color:"white"},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),B.createElement(V,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return B.createElement(V,{key:e.mode,flexDirection:"column"},B.createElement(V,{flexDirection:"row"},B.createElement(K,{color:n?"#E4CCFF":void 0},n?`${Qt} `:" "),B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:n?"#E4CCFF":"white"},e.label),B.createElement(K,{dimColor:!0},e.description))),!r&&B.createElement(K,null," "))})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press "),B.createElement(K,{dimColor:!0,bold:!0},"Enter"),B.createElement(K,{dimColor:!0}," to confirm, "),B.createElement(K,{dimColor:!0,bold:!0},"Esc"),B.createElement(K,{dimColor:!0}," to go back")));const f=r.slice(a,a+8);return B.createElement(V,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),B.createElement(K,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),B.createElement(V,{marginTop:1}),B.createElement(V,{flexDirection:"column"},f.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,c=t===f.length-1,l=n===r.length-1;return B.createElement(V,{key:e.messageId,flexDirection:"column"},B.createElement(V,{flexDirection:"row"},B.createElement(K,{color:s?"#E4CCFF":void 0},s?`${Qt} `:" "),B.createElement(V,{flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:s?"#E4CCFF":"white"},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),B.createElement(K,{dimColor:!0}," • "),B.createElement(K,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),l&&" (latest)")),B.createElement(K,{dimColor:!0},i>0?`${i} file${i>1?"s":""} changed`:"No code changes"))),!c&&B.createElement(K,null," "))})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press "),B.createElement(K,{dimColor:!0,bold:!0},"Enter"),B.createElement(K,{dimColor:!0}," to select, "),B.createElement(K,{dimColor:!0,bold:!0},"Esc"),B.createElement(K,{dimColor:!0}," to cancel")))},"RewindSelector");Tt(),cr();var ll=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=X(),[r,o]=z([]),[s,a]=z(0),[i,c]=z(!0),[l,d]=z(0),u=30;H(()=>{m()},[]);const m=__name(async()=>{c(!0);const e=await Fa.listSessions();o(e),c(!1)},"loadSessions");if(Z((t,o)=>{o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t}):o.downArrow?a(e=>{const t=Math.min(r.length-1,e+1);return t>=l+u&&d(t-u+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),i)return B.createElement(V,{flexDirection:"column",paddingLeft:2,paddingTop:1},B.createElement(K,{color:"gray"},"Loading sessions..."));const g=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5),a=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:s<7?`${s} day${s>1?"s":""} ago`:1===a?"1 week ago":`${a} weeks ago`},"formatRelativeTime"),p=__name(e=>truncateString({text:e,maxChars:Xn}),"truncateMessage");if(0===r.length)return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"gray"},"No sessions available"));const h=r.slice(l,l+u),f=l;return B.createElement(V,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>u&&B.createElement(V,{marginBottom:1},B.createElement(K,{color:"dim"},"Showing ",l+1,"-",Math.min(l+u,r.length)," ","of ",r.length," sessions",l>0&&" (↑ for more)",l+u<r.length&&" (↓ for more)")),B.createElement(V,{columnGap:2,marginBottom:1},B.createElement(V,{width:7},B.createElement(K,{color:"gray"}," ")),B.createElement(V,{width:13},B.createElement(K,{color:"gray"},"Modified")),B.createElement(V,{width:11},B.createElement(K,{color:"gray"},"# Messages")),B.createElement(V,{width:20},B.createElement(K,{color:"gray"},"Git Branch")),B.createElement(V,null,B.createElement(K,{color:"gray"},"Summary"))),B.createElement(V,{columnGap:2},B.createElement(V,{flexDirection:"column",width:7},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${ke.pointer} ${n+1}.`:` ${n+1}.`)})),B.createElement(V,{flexDirection:"column",width:13},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`mod-${e.id}`,color:s===n?"white":"gray"},g(e.lastModified))})),B.createElement(V,{flexDirection:"column",width:11},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),B.createElement(V,{flexDirection:"column",width:20},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),B.createElement(V,{flexDirection:"column"},h.map((e,t)=>{const n=f+t;return B.createElement(K,{key:`summary-${e.id}`,color:s===n?"white":"gray"},p(e.firstMessage))}))))},"SessionTable");function moveFocusDown(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?n>0?{...e,zone:"suggestions",suggestionIndex:0}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:e:"suggestions"===e.zone?e.suggestionIndex<n-1?{...e,suggestionIndex:e.suggestionIndex+1}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:{...e,zone:"input"}:e.activeDirIndex<r-1?{...e,activeDirIndex:e.activeDirIndex+1}:{...e,zone:"input"}}function moveFocusUp(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?r>0?{...e,zone:"active-dir",activeDirIndex:r-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:e:"suggestions"===e.zone?e.suggestionIndex>0?{...e,suggestionIndex:e.suggestionIndex-1}:{...e,zone:"input"}:e.activeDirIndex>0?{...e,activeDirIndex:e.activeDirIndex-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:{...e,zone:"input"}}function getAdjustedSuggestionOffset(e){const{selectedIndex:t,currentOffset:n,maxVisible:r,totalSuggestions:o}=e;return o<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),o=e.replace(/\\/g,"/");if(o.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${o.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:o};const s=o.lastIndexOf("/");return-1===s?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:o.slice(0,s+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),o=n.startsWith(".")||r.includes("/.");return w.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!o||!e.name.startsWith(".")).filter(e=>!n||e.name.toLowerCase().startsWith(n.toLowerCase())).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>`${r}${e.name}/`)}catch(e){const t=e.code;return"ENOENT"!==t&&"ENOTDIR"!==t&&console.error(`Warning: Could not list directory suggestions: ${t}`),[]}}function getFooterText(e){return"active-dir"===e.focusZone?"[Enter] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}Tt(),Ot(),Tt(),Ot(),__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 dl=__name(({onClose:e})=>{const[t,n]=z(""),[r,o]=z(null),[s,a]=z([]),[i,c]=z(getAdditionalDirectories()),[l,d]=z({zone:"input",suggestionIndex:0,activeDirIndex:0}),[u,m]=z(0);H(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),H(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const g=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),c(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),p=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void c(getAdditionalDirectories());o({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),c(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");Z((r,a)=>{if(a.escape)e();else{if(a.return)return"active-dir"===l.zone&&i[l.activeDirIndex]?void p(i[l.activeDirIndex]):"suggestions"===l.zone&&s[l.suggestionIndex]?void g(s[l.suggestionIndex]):void g(t);if((a.delete||a.backspace)&&"active-dir"===l.zone&&i[l.activeDirIndex])p(i[l.activeDirIndex]);else{if(a.tab&&s.length>0){const e=s[l.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}if(a.downArrow)d(e=>moveFocusDown(e,{suggestionCount:s.length,activeDirCount:i.length}));else if(a.upArrow)d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:i.length}));else if("input"===l.zone){if(a.backspace||a.delete)return n(e=>e.slice(0,-1)),void o(null);!r||a.ctrl||a.meta||(n(e=>e+r),o(null))}}}}),H(()=>{"suggestions"===l.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:l.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[l,s.length]),H(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=s.length?{...e,zone:"input",suggestionIndex:Math.max(0,s.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=i.length?{...e,zone:"input",activeDirIndex:Math.max(0,i.length-1)}:e)},[s.length,i.length]);const h=s.slice(u,u+8),f=getFooterText({focusZone:l.zone});return B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},B.createElement(K,{bold:!0,color:"cyan"},"Add directory to workspace"),B.createElement(K,{color:"gray"},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,{color:"gray"},"Added directories"),0===i.length?B.createElement(K,{color:"gray"}," None yet"):i.map((e,t)=>{const n="active-dir"===l.zone&&l.activeDirIndex===t;return B.createElement(K,{key:e,color:n?"yellow":"green",bold:n},n?` ${ke.pointer} `:" ",formatDirectoryForDisplay(e))})),B.createElement(V,{marginTop:1},B.createElement(K,{bold:!0,color:"white"},"Path")),B.createElement(V,null,B.createElement(K,{color:"input"===l.zone?"cyan":"gray"},"input"===l.zone?ke.pointer:" "),B.createElement(K,null," "),B.createElement(K,{color:"white"},t),"input"===l.zone&&B.createElement(K,{color:"gray"},"█")),!t&&B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray"},"Examples: ../shared ~/docs /abs/path")),r&&B.createElement(V,{marginTop:1},B.createElement(K,{color:{error:"red",warning:"yellow",success:"green"}[r.tone]},r.text)),s.length>0&&B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(K,{color:"gray"},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===l.zone&&l.suggestionIndex===n;return B.createElement(K,{key:e,color:r?"cyan":"gray",bold:r},r?` ${ke.pointer} `:" ",e)})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},f)))},"AddDirModal");Tt(),$t();var ul=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=z(0),o=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],s=__name(e=>{const r=o.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),a=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"";return t?`${e.command} ${t}`:e.command},"getCommandDisplay");return B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,color:"yellow"},"Execute Shell Command")),B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",B.createElement(K,{color:"cyan"},a()),".")),e.workingDirectory&&B.createElement(V,{marginBottom:1},B.createElement(K,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0,italic:!0},e.description)),B.createElement(He,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"cyan"},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(K,{color:t?"cyan":"white"},e.includes("(shift+tab)")?B.createElement(B.Fragment,null,e.split("(shift+tab)")[0],B.createElement(K,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt");Tt(),$t();var ml=__name(e=>Math.ceil(e.length/4),"estimateTokens"),gl=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(!0),[s,a]=z(null),[i,c]=z(0);H(()=>{__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){a(e instanceof Error?e.message:"Failed to load skills")}finally{o(!1)}},"loadSkills")()},[]);const l=t.filter(e=>"project"===e.location),d=t.filter(e=>"user"===e.location),u=[...l,...d],m=__name(async t=>{try{await Qe([{file:t.filePath,line:1}]),hi(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?a(g()):a(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");Z((t,n)=>{if(n.escape)return hi(),void e();if(n.upArrow)c(e=>Math.max(0,e-1));else if(n.downArrow)c(e=>Math.min(u.length-1,e+1));else if(n.return){const e=u[i];e&&m(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(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills"),B.createElement(K,{dimColor:!0},"Loading skills...")):s?B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,{color:"red",bold:!0},"Agent Skills"),B.createElement(K,{dimColor:!0},s),B.createElement(V,{marginTop:1}),B.createElement(K,{dimColor:!0},"Press ",B.createElement(K,{bold:!0},"Esc")," to close")):0===t.length?B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills"),B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"No skills found")),B.createElement(K,{dimColor:!0},"Create skills in:"),B.createElement(K,{dimColor:!0}," ~/",".commandcode","/","skills","/ (user)"),B.createElement(K,{dimColor:!0}," ",".commandcode","/","skills","/ (project)"),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press ",B.createElement(K,{bold:!0},"Esc")," to close"))):B.createElement(V,{flexDirection:"column",paddingX:0,width:"100%"},B.createElement(V,null,B.createElement(K,{color:"#E4CCFF",bold:!0},"Skills "),B.createElement(K,{dimColor:!0},u.length," skills")),l.length>0&&B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(V,null,B.createElement(K,{color:"#666666",bold:!0},"Project skills "),B.createElement(K,{color:"#666666"},"(",".commandcode","/","skills",")")),l.map((e,t)=>{const n=i===t;return B.createElement(V,{key:e.value},B.createElement(K,{color:n?"green":"white"},e.label),B.createElement(K,{dimColor:!0}," · ~",ml(e.description)," description tokens"))})),d.length>0&&B.createElement(V,{flexDirection:"column",marginTop:1},B.createElement(V,null,B.createElement(K,{color:"#666666",bold:!0},"User skills "),B.createElement(K,{color:"#666666"},"(~/",".commandcode","/","skills",")")),d.map((e,t)=>{const n=i===l.length+t;return B.createElement(V,{key:e.value},B.createElement(K,{color:n?"green":"white"},e.label),B.createElement(K,{dimColor:!0}," · ~",ml(e.description)," description tokens"))})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0,italic:!0},"Esc to close")))},"SkillsConfig");Tt(),Tn();var pl=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=z(!1),[s,a]=z(!0);H(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{a(!1)}},"loadSettings")()},[]),Z((t,n)=>{if(!n.return&&" "!==t)return n.escape?(hi(),void e()):void 0;i()});const i=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return s?B.createElement(V,{key:n,borderStyle:"single",borderColor:"blue",padding:1,flexDirection:"column"},B.createElement(K,{color:"blue",bold:!0},"Taste Settings"),B.createElement(K,{dimColor:!0},"Loading configuration...")):B.createElement(V,{key:n,borderStyle:"single",borderColor:"gray",padding:1,flexDirection:"column"},B.createElement(K,{bold:!0},"Taste Learning"),B.createElement(K,{dimColor:!0},"Configure taste learning preferences for this project"),B.createElement(V,{marginTop:1}),B.createElement(V,{justifyContent:"space-between"},B.createElement(K,null,"Taste learning",B.createElement(K,{dimColor:!0}," - Learn from your interactions")),B.createElement(K,{color:r?"green":"gray"},r?"enabled":"disabled")),B.createElement(V,{marginTop:1}),B.createElement(K,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),B.createElement(K,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig");Tt(),bn(),Tt(),Tt();var hl=__name(e=>{const[t,n]=z(e),[r,o]=z(null);return H(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),o(null)},"handleReset"),r=__name(e=>{"error"!==e.type?n(t=>{if("step_start"===e.type){const n=t.findIndex(t=>t.id===e.step);return n<0?t:t.map((t,r)=>r<n?{...t,active:!1,complete:!0}:r===n?{...t,active:!0,message:e.message||"",...e.label&&{label:e.label},..."complete"===e.step&&{complete:!0},...void 0!==e.learningCount&&void 0!==e.categories&&void 0!==e.storage&&t.summary&&{summary:{learningCount:e.learningCount,categories:e.categories,storage:e.storage}}}:t)}if("progress"===e.type){const n=t.findIndex(e=>e.active);return n<0?t:t.map((t,r)=>r===n?{...t,items:[...t.items,e.message]}:t)}if("insight"===e.type){const n=t.findIndex(e=>"learning"===e.id);return n<0?t:t.map((t,r)=>r===n?{...t,insights:[...t.insights,e.message]}:t)}return t}):o(e.message)},"handleNewEvent");return ei.on("reset",t),ei.on("new-event",r),()=>{ei.off("reset",t),ei.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new _o({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;if(n===yt.ANTHROPIC)try{const e=await Zt.getValidAccessToken();validateOAuthToken({token:e,provider:n}),o=e}catch(e){dlog("Failed to get or validate Anthropic OAuth token:",e instanceof Error?e.message:String(e))}const s={[gt.PROJECT_SLUG]:Fa.getCurrentProjectDirName(),[gt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(s[gt.OAUTH_TOKEN]=`Bearer ${o}`),{request:t,headers:s}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}Tt(),Tt(),bn(),Tt(),bn(),Tt(),Tt(),$t(),rn(),bn(),Tn(),In(),__name(createRequestClient,"createRequestClient"),Tt(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Tt(),Tt(),$t(),bn(),Vt(),Tt();var fl="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:${fl}`,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}`),ei.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()}`),ei.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=Be.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 ${pt.ALPHA.GENERATE} with model: ${fl}`);const r=buildRequestBody2(n);let o;try{o=await e.post({endpoint:pt.ALPHA.GENERATE,body:r,headers:t,stream:!0}),dlog("[ObserverAPI] got response stream")}catch(e){throw dlog(`[ObserverAPI] request failed: ${e instanceof Error?e.message:String(e)}`),e}await processStream(o),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const a=buildObserverPrompt(n,4);await callObserverAPI(e,t,a)}async function observeSessionPrompts(e){if(ei.observerHasRun)return;ei.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${r.length} batches`);const o=Math.min(r.length,6);for(let t=0;t<o;t++){if(ei.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const o=r[t];try{await processBatch(e,n,o,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),ei.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 yl=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(p.homedir(),".claude","projects");await D.access(r);const o=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await D.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await D.stat(s)).isDirectory())continue;const r=(await D.readdir(s)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const o of r){const r=e.join(s,o),a=await D.stat(r),i=o.replace(".jsonl","");if(n.push({id:i,filePath:r,createdAt:a.birthtime,lastModified:a.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{ei.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&ei.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 D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[];try{ei.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const o=await loadProjectSettings(),s=o.tasteOnboarding?.learnedSessions||{},a=s["claude-code"]?.length||0,i=s.codex?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${i} learned`);const c=await findNewSessions(s),l=c["claude-code"]||[],d=c.codex||[],u=l.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${l.length} new, codex=${d.length} new`),0===u){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=e.length+t.length,r=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);ei.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:n>0?`From ${r.join(" + ")} sessions`:"No sessions found for this project"});const o=[];return e.length>0&&o.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&o.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:n,learnedSessions:a+i,agentSessions:o,status:"already-learned"}}if(l.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>l.includes(e.id));n.push(...e)}if(d.length>0){const e=(await this.findCodexSessions()).filter(e=>d.includes(e.id));r.push(...e)}const m=n.length+r.length;dlog(`[Import] total sessions: ${m} (claude-code: ${n.length}, codex: ${r.length})`),ei.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){ei.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const p=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${p.length} batches`);const h=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});ei.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${p.length} batch${1===p.length?"":"es"}`});try{const o=getApiBaseUrl(),s=new _o({baseUrl:o});let a=!0;for(let e=0;e<p.length;e++){const t=p[e],n=e+1,r=p.length;r>1&&ei.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),i=new ni({request:s,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),c=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await i.checkAndProcess({messages:c})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),ei.markLearningComplete(),await h,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const i=await this.extractLearningSummary(),c=[];if(n.length>0&&c.push(`Claude Code (${n.length})`),r.length>0&&c.push(`Codex (${r.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),ei.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}return ei.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${c.join(" + ")}`,learningCount:i.totalLearnings,categories:i.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),ei.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 D.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),o=r?r.length:0;return{totalLearnings:o,categories:n.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}},wl=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),El=__name(e=>{const[t,n]=z({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return H(()=>{ei.reset(),ei.markImportStarted(),(async()=>{try{const t=await Promise.race([yl.importAndLearn(),wl(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");Tt();var Sl=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{Z((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");Tt(),bn();var kl=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=z(null),[o,s]=z(null),a=W(!1);return H(()=>{if(a.current)return;let n=null;return(async()=>{try{a.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{ei.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{ei.reset(),e()}}Tt(),bn(),Tt(),bn(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var vl=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=W(n),o=G(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=G(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=G(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=G(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current())},[e]),c=G(async()=>{dlog("[Handler] demo complete → done"),e("done"),await markDemoShown(),await completeOnboarding(()=>r.current())},[e]),l=G(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current())},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:a,handleErrorDismiss:i,handleDemoComplete:c,handleSkip:l}},"useOnboardingHandlers");Tt(),bn();var bl=__name(({conditions:e,autoLearn:t})=>{const[n,r]=z("checking"),o=W(!1);return H(()=>{if(e&&!o.current){if(o.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),H(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Tt(),Tt();var Cl=__name(({error:e})=>B.createElement(V,{padding:1},B.createElement(V,{flexDirection:"column",borderColor:"red",padding:1},B.createElement(V,{marginBottom:1},B.createElement(K,null,"Error initializing onboarding: ",e)),B.createElement(V,null,B.createElement(K,null,"Continuing without onboarding...")))),"OnboardingError");Tt(),Tt();var Pl=[{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}],Tl=__name(({onComplete:e})=>{const[t,n]=z(0),[r,o]=z(!1),s=t>=Pl.length;H(()=>{if(t>=Pl.length)return;if(r)return;const e=Pl[t],o=setTimeout(()=>{n(e=>Math.min(e+1,Pl.length))},e.duration);return()=>clearTimeout(o)},[t,r]),Z((t,r)=>{r.escape?e():s?(r.return||" "===t)&&e():" "===t?o(e=>!e):r.return&&n(e=>Math.min(e+1,Pl.length))});const a=Pl.slice(0,t);return B.createElement(V,{flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:"cyan"},"Meet Your Coding Taste")),B.createElement(V,null,B.createElement(K,null,"Command Code learns your coding style as you work.")),B.createElement(V,null,B.createElement(K,null,"Here's how your preferences evolve in real-time:")),B.createElement(V,{flexDirection:"column",marginY:1},0===a.length&&!s&&B.createElement(K,{dimColor:!0},"Starting demo..."),a.map((e,t)=>"user"===e.type?B.createElement(V,{key:t},B.createElement(K,{color:"white"},`${ke.pointer} ${e.text}`)):B.createElement(V,{key:t,marginBottom:1,marginTop:0,marginLeft:1},B.createElement(V,null,B.createElement(K,null,"⎿"),B.createElement(V,{flexDirection:"column",marginLeft:2,marginTop:0},B.createElement(K,{color:"green"},e.text),e.details&&B.createElement(K,{dimColor:!0},"Saved(",e.details,")")))))),s&&B.createElement(V,{flexDirection:"column",marginY:1,width:80},B.createElement(V,null,B.createElement(K,{color:"green",bold:!0},"Demo Complete!"," ")),B.createElement(K,null,"Command Code will now use these preferences to generate better suggestions tailored to your coding style. The more you code, the smarter it gets."),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Press Enter to get started →"))),!s&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"," ",r?"(paused)":"")))},"TasteDemoComponent");Tt(),$t();var Al=__name(()=>`(run /${Et.LEARN_TASTE} anytime)`,"getSkipHint"),xl=__name(()=>B.createElement(K,null,"Skip for now"," ",B.createElement(K,{dimColor:!0},Al())),"SkipOptionText"),Il=__name(({sessionCount:e,agentSessions:t,onImport:n,onDemo:r,onSkip:o,demoShown:s=!1})=>{const[a,i]=z(1),c=s?2:3,l=s?2:3;return Z((e,t)=>{if(t.escape)o();else if(t.upArrow)i(e=>1===e?c:e-1);else if(t.downArrow)i(e=>e===c?1:e+1);else if("1"!==e)if("2"!==e)if("3"!==e||s){if(t.return){if(1===a)return void n();if(2===a)return void(s?o():r());o()}}else o();else s?o():r();else n()}),B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},B.createElement(K,{color:"cyan",bold:!0},"Build Your Coding Taste"),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),B.createElement(V,{marginTop:1},B.createElement(K,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:1===a?"cyan":"gray"},1===a?ke.pointer:" "," 1. Yes, learn from my sessions (recommended)")),!s&&B.createElement(V,null,B.createElement(K,{color:2===a?"cyan":"gray"},2===a?ke.pointer:" "," ","2. No, show me a demo instead")),B.createElement(V,null,B.createElement(K,{color:a===l?"cyan":"gray"},a===l?ke.pointer:" "," ",l,". ",B.createElement(xl,null)))),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice"),$l=__name(({onDemo:e,onSkip:t})=>{const[n,r]=z(1);return Z((o,s)=>{s.escape?t():s.upArrow||s.downArrow?r(e=>1===e?2:1):"1"!==o?"2"!==o?s.return&&(1===n?e():t()):t():e()}),B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",padding:1},B.createElement(K,{color:"cyan",bold:!0},"No Previous Sessions Found"),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,null,"No previous sessions found to analyze."),B.createElement(V,{marginTop:1},B.createElement(K,null,"Would you like to see how taste learning works?"))),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:1===n?"cyan":"gray"},1===n?ke.pointer:" "," 1. Yes, show me a demo")),B.createElement(V,null,B.createElement(K,{color:2===n?"cyan":"gray"},2===n?ke.pointer:" "," 2."," ",B.createElement(xl,null)))),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"NoSessionsChoice");Tt(),Tt();var Rl=__name(({error:e})=>B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"red",paddingX:2,paddingY:1,marginBottom:2},B.createElement(K,{color:"red",bold:!0},"Oops, something went wrong:"),B.createElement(V,{marginTop:1},B.createElement(K,null,e))),"ErrorSection");Tt(),Tt(),Tt(),Tt(),Tt();var Dl=[ke.bullet,ke.squareSmallFilled,ke.lozenge,ke.star,ke.triangleRight,ke.triangleUp,ke.circleFilled,ke.pointer],Ml=__name(()=>B.createElement(K,{backgroundColor:"green",color:"black"}," TASTE "),"TasteBadge"),Nl=["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"],Ol=__name(()=>{const[e,t]=z(()=>Math.floor(Math.random()*Nl.length));H(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*Nl.length))},2e3);return()=>clearInterval(e)},[]);const n=Nl[e];return B.createElement(K,{color:"yellow"},n,"...")},"PulsingText"),Fl=__name(e=>String(e).padStart(3," "),"padNum"),Ll=__name(e=>Dl[e%Dl.length],"getSymbol"),_l=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${Fl(t)} ↓${Fl(n)} (↑↓ scroll)`,"buildStatusLine"),Ul=__name(({insights:e})=>{const[t,n]=z(0),[r,o]=z(!0),s=e.length,a=s>10,i=Math.max(0,s-10);if(H(()=>{r&&a&&n(i)},[s,r,a,i]),Z((e,t)=>{if(a)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(i,e+1);return t===i&&o(!0),t}))}),0===s)return null;const c=e.slice(t,t+10),l=t,d=s-t-10;return B.createElement(V,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&B.createElement(K,{dimColor:!0},_l(s,l,d,r)),c.map((e,n)=>{const r=t+n;return B.createElement(V,{key:r,marginBottom:0},B.createElement(K,{dimColor:!0},Ll(r)," ",e))}))},"ScrollableInsights"),jl=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:c})=>{if(a)return B.createElement(V,{flexDirection:"column",marginBottom:0},B.createElement(Ml,null),B.createElement(V,{marginTop:0},B.createElement(K,{dimColor:!0},"⎿"),B.createElement(V,{marginLeft:2},i?B.createElement(K,{color:"green"},"learned your coding taste"):B.createElement(Ol,null))));const l=__name(()=>{const[e,t]=z(!0);return H(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),B.createElement(K,{color:"yellow"},e?ke.circleFilled:ke.circle)},"PulsingDot"),d=__name(()=>r?B.createElement(K,{color:"green"},ke.nodejs):n?B.createElement(l,null):B.createElement(K,{dimColor:!0},ke.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||c&&c.learningCount>0;return!r||n||u?B.createElement(V,{flexDirection:"column",marginBottom:0},(n||r)&&B.createElement(V,{marginBottom:0},B.createElement(V,{marginRight:1},d()),B.createElement(K,{color:r?"white":n?"yellow":"dim"},e)),r&&t&&(!c||0===c.learningCount)&&B.createElement(V,{marginLeft:3,marginBottom:0},B.createElement(K,{dimColor:!0},t)),o.length>0&&B.createElement(V,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>B.createElement(K,{key:t,dimColor:!0},`${ke.bullet} ${e}`))),s.length>0&&B.createElement(Ul,{insights:s}),r&&c&&c.learningCount>0&&B.createElement(V,{flexDirection:"column",marginLeft:1,marginBottom:0},B.createElement(V,{marginBottom:1,flexDirection:"row"},B.createElement(K,null,"⎿"),B.createElement(V,{marginLeft:2},B.createElement(K,{color:"green"},"Learned ",c.learningCount," preference",1===c.learningCount?"":"s",c.categories.length>0?` across ${c.categories.length} ${1===c.categories.length?"category":"categories"}`:""))),B.createElement(V,{flexDirection:"column",marginLeft:1},B.createElement(K,{dimColor:!0},ke.pointerSmall," Stored in"," ",c.storage),B.createElement(K,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),Bl=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return B.createElement(V,{flexDirection:"column",marginBottom:1},e.map((e,n)=>B.createElement(V,{key:e.id,marginLeft:0===n?0:3},B.createElement(jl,{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"),zl=__name(({steps:e})=>B.createElement(Bl,{steps:e}),"ProgressSection");Tt();var Wl=__name(({isImporting:e=!1,waitingForInput:t=!1})=>B.createElement(B.Fragment,null,e&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"ESC to cancel")),t&&B.createElement(V,{marginTop:1},B.createElement(K,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Tt();var Hl=[{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"}}],Gl=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=hl(Hl),{isImporting:s,waitingForInput:a,error:i}=El(t);return Sl({onEscape:e,onEnter:__name(()=>{a&&(i&&n?n():e())},"onEnter"),enabled:s||a}),B.createElement(V,{flexDirection:"column",padding:1},o&&B.createElement(Rl,{error:o}),!o&&B.createElement(zl,{steps:r}),B.createElement(Wl,{isImporting:s,waitingForInput:a}))},"ImportProgress"),ql=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onDemoComplete:a,onDemo:i,onSkip:c})=>"asking"===e?"has_sessions"!==t?.reason?B.createElement($l,{onDemo:i,onSkip:c}):B.createElement(Il,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onDemo:i,onSkip:c,demoShown:t.demoShown}):"learning"===e?B.createElement(Gl,{onComplete:r,onError:o,onErrorDismiss:s}):"demo"===e?B.createElement(Tl,{onComplete:a}):null,"OnboardingStepRenderer"),Vl=__name(({onComplete:e,autoLearn:t=!1})=>{H(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=kl({autoLearn:t,onShouldSkip:e}),{step:s,setStep:a}=bl({conditions:n,autoLearn:t}),{handleImportStart:i,handleImportComplete:c,handleImportError:l,handleErrorDismiss:d,handleDemoComplete:u,handleSkip:m}=vl({onStepChange:__name(e=>{a(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?B.createElement(Cl,{error:r}):"done"===s?null:B.createElement(ql,{step:s,conditions:n,onImportStart:i,onImportComplete:c,onImportError:l,onErrorDismiss:d,onDemoComplete:u,onDemo:()=>a("demo"),onSkip:m})},"TasteOnboarding");Tt(),$t();var Kl=__name(({onTrust:e,onExit:t})=>{const{exit:n}=X(),[r,o]=z(1),s=process.cwd().replace(process.env.HOME||"","~");return Z((s,a)=>{a.upArrow||a.downArrow?o(1===r?2:1):a.return?1===r?e():(t(),n()):"1"===s?e():("2"===s||a.escape||a.ctrl&&"c"===s)&&(t(),n())}),B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",padding:1},B.createElement(K,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),B.createElement(V,{marginTop:1},B.createElement(K,{color:"gray"},s)),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),B.createElement(V,{marginTop:1},B.createElement(K,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:1===r?"cyan":"gray"},1===r?ke.pointer:" "," 1. Yes, proceed")),B.createElement(V,null,B.createElement(K,{color:2===r?"cyan":"gray"},2===r?ke.pointer:" "," 2. No, exit"))))},"TrustPrompt");Tt(),An(),xn();var Jl=__name(({onComplete:e,onCancel:t})=>{const[n,r]=z(!1),[o,s]=z(""),{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u,cancel:m}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return Z((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");m()}}),n?B.createElement(Cn,{onSuccess:()=>{e(!0,o?`Logged in as ${o} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,o?`Logged in as ${o}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):B.createElement(Yr,{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u})},"LoginOverlay");Tt(),Tt(),In();var Yl=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),Ql=__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"),Zl=__name(({icon:e,label:t,children:n})=>B.createElement(K,null,B.createElement(K,{color:"cyan"},e," "),B.createElement(K,{dimColor:!0},t.padEnd(12)),n),"Row"),Xl=__name(({title:e})=>B.createElement(K,null,B.createElement(K,{color:"gray"},"───"),B.createElement(K,{color:"white"}," ",e," "),B.createElement(K,{color:"gray"},"─".repeat(35))),"Header"),ed=__name(({title:e,marginTop:t=0,children:n})=>B.createElement(V,{flexDirection:"column",marginTop:t},B.createElement(Xl,{title:e}),B.createElement(V,{flexDirection:"column",paddingY:1},n)),"Section"),td=__name(({cpuCount:e,totalMem:t})=>B.createElement(ed,{title:"System Information"},B.createElement(Zl,{icon:Se.bullet,label:"Date"},B.createElement(K,null,formatDate())),B.createElement(Zl,{icon:Se.pointer,label:"Platform"},B.createElement(K,{color:"green"},Yl(p.platform())),B.createElement(K,{dimColor:!0}," ","(",p.platform(),", ",p.arch(),")")),B.createElement(Zl,{icon:Se.triangleUp,label:"Hostname"},B.createElement(K,null,p.hostname())),B.createElement(Zl,{icon:Se.bullet,label:"User"},B.createElement(K,{color:"yellow"},p.userInfo().username)),B.createElement(Zl,{icon:Se.bullet,label:"CPUs"},B.createElement(K,{color:"magenta"},e," cores")),B.createElement(Zl,{icon:Se.bullet,label:"Memory"},B.createElement(K,{color:"cyan"},t," GB")),B.createElement(Zl,{icon:Se.play,label:"Uptime"},B.createElement(K,null,Ql(p.uptime()))),B.createElement(Zl,{icon:Se.arrowRight,label:"Home"},B.createElement(K,{dimColor:!0},p.homedir())),B.createElement(Zl,{icon:Se.pointer,label:"Shell"},B.createElement(K,null,process.env.SHELL||"N/A")),B.createElement(Zl,{icon:Se.bullet,label:"Node"},B.createElement(K,{color:"green"},process.version))),"SystemInfoSection"),nd=__name(({cpus:e})=>B.createElement(ed,{title:"CPU Details",marginTop:1},e.map((e,t)=>B.createElement(Zl,{key:t,icon:Se.bullet,label:`Core ${t}`},B.createElement(K,null,e.model.trim()),B.createElement(K,{color:"yellow"}," @ ",e.speed," MHz")))),"CPUDetailsSection"),rd=__name(({networkInterfaces:e})=>B.createElement(ed,{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(Zl,{key:`${e}-${n}`,icon:Se.bullet,label:e},B.createElement(K,{color:"green"},t.address))):null})),"NetworkSection"),od=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>B.createElement(V,{flexDirection:"column"},B.createElement(K,null,"System Information"),B.createElement(K,null,"─".repeat(40)),B.createElement(K,null,"Date ",formatDate()),B.createElement(K,null,"Platform ",Yl(p.platform())," (",p.platform(),","," ",p.arch(),")"),B.createElement(K,null,"Hostname ",p.hostname()),B.createElement(K,null,"User ",p.userInfo().username),B.createElement(K,null,"CPUs ",e.length," cores"),B.createElement(K,null,"Memory ",t," GB"),B.createElement(K,null,"Uptime ",Ql(p.uptime())),B.createElement(K,null,"Home ",p.homedir()),B.createElement(K,null,"Shell ",process.env.SHELL||"N/A"),B.createElement(K,null,"Node ",process.version),r&&B.createElement(B.Fragment,null,B.createElement(K,null,"\n","CPU Details"),B.createElement(K,null,"─".repeat(40)),e.map((e,t)=>B.createElement(K,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),B.createElement(K,null,"\n","Network"),B.createElement(K,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>B.createElement(K,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),sd=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>B.createElement(V,{flexDirection:"column"},B.createElement(td,{cpuCount:e.length,totalMem:t}),r&&B.createElement(nd,{cpus:e}),r&&B.createElement(rd,{networkInterfaces:n})),"StyledInfo"),ad=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=X();H(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=p.cpus(),o=p.networkInterfaces(),s=Math.round(p.totalmem()/1024/1024/1024);return t?B.createElement(od,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e}):B.createElement(sd,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e})},"InfoUI"),id={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},cd=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),ld=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(cd("__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"),dd=__name(()=>{const e=ld();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&id[t]?id[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),ud=__name(()=>{if("win32"===h.platform()){const e=process.env.COMSPEC;return e?c(e):process.env.SHELL?c(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=c(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?c(e):"N/A"},"getShellName"),md=__name(()=>{const e=ld();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),gd=__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:Yl(h.platform()),terminal:dd(),shell:ud(),version:gd(),ide:md()}}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()}`}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),Tt(),Tt(),bn();var pd=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(p.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await D.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 D.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await D.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 D.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await D.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await D.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 pd}__name(createHistoryManager,"createHistoryManager"),Tt();var hd=__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"),fd=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r,hideReview:o=!1})=>{if(o&&1===e.length)return null;const s=[];if(e.forEach((o,a)=>{const i=a===t&&!r,c=n.has(a);let l,d;i?(l="●",d="cyan"):c?(l="✓",d="green"):(l="○",d="gray"),s.push(B.createElement(K,{key:a},B.createElement(K,{color:d},l),B.createElement(K,{color:i?"cyan":void 0}," ",o.header),a<e.length-1?B.createElement(K,{dimColor:!0}," | "):null))}),!o){const e=r;s.push(B.createElement(K,{key:"review"},B.createElement(K,{dimColor:!0}," | "),B.createElement(K,{color:e?"cyan":"gray"},e?"●":"○"),B.createElement(K,{color:e?"cyan":void 0,bold:e}," ","Review")))}return B.createElement(V,null,s)},"TabIndicator"),yd=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,o]=z(0),[s,a]=z(new Map),i=W(new Map),[c,l]=z(""),[d,u]=z(new Set),[m,g]=z(null),[p,h]=z(!1),[f,y]=z(!1),[w,E]=z(!1),[S,k]=z(null),[v,b]=z(!1),C=e[r],P=C?.multiSelect??!1,T=s.get(r),A=C?[...C.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]])),$=__name(e=>{"submit"===e.value?F():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),R=__name(()=>{if(!T||0===T.length)return 0;const e=T[0],t=C.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),D=__name(e=>{if(!p)if(P){const t=hd(e.value,C.options.length-1);if(null===t)return;const n=C.options[t]?.label||"";u(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=hd(e.value,C.options.length-1);if(null===t)return;h(!0);const n=C.options[t]?.label||"";O([n])}},"handleSelect"),M=__name(()=>{if(p)return;h(!0);const e=Array.from(d);O(e)},"handleMultiSelectDone"),N=__name(()=>{if(!p&&c.trim())if(P){const e=new Set(C.options.map(e=>e.label));u(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(c.trim()),n})}else h(!0),O([c.trim()])},"handleOtherSubmit"),O=__name(t=>{i.current.set(r,t);const s=new Map(i.current);a(s);const c=__name(t=>{const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){u(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),n?.multiSelect||1!==r?.length)l("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);l(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;c(e),o(e),h(!1),E(!1),k(null),b(!1)}else if(e.every((e,t)=>s.has(t))){if(n&&1===e.length)return void F();u(new Set),l(""),y(!0),h(!1)}else{const t=e.findIndex((e,t)=>!s.has(t));-1!==t&&(c(t),o(t)),h(!1),E(!1),k(null),b(!1)}},"finishQuestion"),F=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:i.current.get(t)||[]}));t({answers:n})},"submitAnswers"),L=__name(t=>{y(!1),o(t),b(!1),E(!1),k(null);const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){u(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),n?.multiSelect||1!==r?.length)l("");else{const e=r[0],t=!n.options.some(t=>t.label===e);l(t&&e?e:"")}},"editQuestion"),_=__name(t=>{if(t<0||t>=e.length)return;P&&(d.size>0?i.current.set(r,Array.from(d)):i.current.delete(r),a(new Map(i.current))),h(!1),E(!1),k(null),b(!1);const n=e[t],s=i.current.get(t);if(n?.multiSelect&&s){u(new Set(s));const e=s.find(e=>!n.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),n?.multiSelect||1!==s?.length)l("");else{const e=s[0],t=!n.options.some(t=>t.label===e);l(t&&e?e:"")}o(t)},"navigateToQuestion"),U=__name(()=>{if(!m||!P)return;if("done"===m.value)return;const e=hd(m.value,C.options.length-1);if(null===e)return;const t=C.options[e]?.label||"";u(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return Z((t,o)=>{if(" "===t&&P&&!w&&U(),"d"!==t||!P||w||f||M(),!f&&!p){if(o.downArrow&&!w&&!v&&!n&&m&&x.length>0&&m.value===x[x.length-1]?.value&&E(!0),o.upArrow&&!w&&!v&&m&&x.length>0&&m.value===x[0]?.value&&(P?b(!0):n||(E(!0),k(x.length-1))),o.upArrow&&w){E(!1),k(x.length-1);const e=x[x.length-1];e&&g(e)}if(o.downArrow&&w)if(E(!1),P)b(!0);else{k(0);const e=x[0];e&&g(e)}if(o.upArrow&&v&&(b(!1),E(!0)),o.downArrow&&v){b(!1),k(0);const e=x[0];e&&g(e)}o.return&&v&&P&&M()}if(p||w||v||(f?o.leftArrow&&L(e.length-1):o.leftArrow&&r>0?_(r-1):o.rightArrow&&(r<e.length-1?_(r+1):(P&&(d.size>0?i.current.set(r,Array.from(d)):i.current.delete(r),a(new Map(i.current))),y(!0)))),o.escape&&!p)if(f)y(!1);else if(w){E(!1);const e=S??x.length-1;k(e);const t=x[e];t&&g(t)}else if(v){b(!1);const e=x[x.length-1];e&&g(e)}}),C||f?f?B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(fd,{questions:e,currentIndex:e.length,answeredQuestions:new Set(s.keys()),isReviewPage:!0})),e.map((e,t)=>B.createElement(V,{key:t,marginBottom:1,flexDirection:"column"},B.createElement(K,{dimColor:!0},t+1,". ",e.question),B.createElement(K,{color:"green"}," ",s.get(t)?.join(", ")||"No answer"))),B.createElement(He,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:$,initialIndex:0,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"cyan"},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>B.createElement(K,{color:t?"cyan":"white"},e)}),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},ke.arrowLeft," to go back and edit"))):B.createElement(V,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(fd,{questions:e,currentIndex:r,answeredQuestions:new Set(s.keys()),isReviewPage:!1,hideReview:n})),B.createElement(V,{marginBottom:1},B.createElement(K,{bold:!0},C.question)),w||v?B.createElement(V,{flexDirection:"column"},x.map((e,t)=>{const n=I.get(e.label),r=P&&n&&d.has(n.label),o=!P&&n&&T?.includes(n.label),s=r||o;return B.createElement(V,{key:t,flexDirection:"column"},B.createElement(V,null,B.createElement(K,null," "),B.createElement(K,{color:s?"green":"white"}," ",t+1,"."," "),P&&(s?B.createElement(K,{color:"green"},"[",ke.tick,"]"," "):B.createElement(K,{dimColor:!0},"[ ] ")),B.createElement(K,{color:s?"green":"white"},n?.label||""),!P&&s&&B.createElement(K,{color:"green"}," ",ke.tick)),n?.description&&B.createElement(V,null,B.createElement(K,null," "),B.createElement(K,{dimColor:!0},P?" ":" ",n.description)))})):B.createElement(He,{key:`${r}-${S??"default"}`,items:x,initialIndex:S??R(),onSelect:D,onHighlight:g,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"cyan"},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=I.get(e),r=P&&n&&d.has(n.label),o=!P&&n&&T?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",c=a?.[2]||e;return B.createElement(V,{flexDirection:"column"},B.createElement(V,null,B.createElement(K,{color:t?"cyan":s?"green":"white"}," ",i,"."," "),P&&(s?B.createElement(K,{color:"green"},"[",ke.tick,"]"," "):B.createElement(K,{dimColor:!0},"[ ] ")),B.createElement(K,{color:t?"cyan":s?"green":"white"},c),!P&&s&&B.createElement(K,{color:"green"}," ",ke.tick)),n?.description&&B.createElement(K,{dimColor:!0},P?" ":" ",n.description))}}),!n&&B.createElement(V,null,B.createElement(K,{color:"cyan"},w?ke.pointer:" "),B.createElement(K,{color:w?"cyan":void 0}," ",x.length+1,"."," "),P&&(d.has(c.trim())?B.createElement(K,{color:"green"},"[",ke.tick,"] "):B.createElement(K,{dimColor:!0},"[ ] ")),B.createElement(Ze,{value:c,onChange:e=>{const t=c.trim();l(e),P&&u(n=>{const r=new Set(n);return t&&r.has(t)&&r.delete(t),e.trim()&&r.add(e.trim()),r})},onSubmit:N,placeholder:"Type something...",focus:w})),P&&B.createElement(V,null,B.createElement(K,{color:"cyan"},v?ke.pointer:" "),B.createElement(K,{color:v?"cyan":void 0,bold:v}," ",r===e.length-1?"Submit":"Next")),e.length>1&&B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function LiveAgentStatusInner({entry:e}){const t=Vs(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,a=e.metadata?.elapsedSeconds||0,i=e.metadata?.recentTools||[],[c,l]=z(".");return H(()=>{const e=setInterval(()=>{l(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),B.createElement(V,{flexDirection:"column",marginBottom:1,width:"90%"},B.createElement(V,null,B.createElement(K,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${t} `),o&&B.createElement(K,null," ","(",o,")")),B.createElement(V,{columnGap:1,marginLeft:1},B.createElement(K,null,"⎿"," "),B.createElement(K,{color:"gray"},"Running (",formatTime2(a)," | ",formatTokens(s),")",c)),i.length>0&&B.createElement(V,{flexDirection:"column",marginLeft:1},i.map((e,t)=>{const n=Vs(e.name);return B.createElement(V,{key:t,columnGap:1},B.createElement(K,{color:"gray"},"⎿"),B.createElement(K,{color:"gray"}," ",n),e.input&&B.createElement(K,{color:"gray"},"(",e.input,")"))})))}function LiveAgentStatus({entry:e}){return"tool"!==e.role?null:B.createElement(LiveAgentStatusInner,{entry:e})}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:is,capabilities:{},clientInfo:cs}})});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}Tt(),In(),__name(LiveAgentStatusInner,"LiveAgentStatusInner"),__name(LiveAgentStatus,"LiveAgentStatus"),Tt(),Tt(),Tt(),wr(),_r(),Tt(),kr(),bn(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient");var wd=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(!0),[s,a]=z(0),[i,c]=z("list"),[l,d]=z(null);H(()=>{u()},[]);const u=__name(async()=>{o(!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,o,s="disconnected";return n&&"connected"===n.status?(s="connected",r=n.tools.length):n&&"error"===n.status?(s="error",o=n.error):e.config.oauth&&(s=await hasTokens(e.name)?"authenticated":"requires_auth"),{name:e.name,config:e.config,scope:e.scope,status:s,toolCount:r,error:o}}));n(r)}catch{}finally{o(!1)}},"loadServers"),m=q(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),g=m[s]??null;Z((t,n)=>{n.ctrl&&"c"===t?e():n.escape?"actions"===i||"confirm-remove"===i?(c("list"),d(null)):e():"list"===i&&(n.upArrow&&(a(e=>Math.max(0,e-1)),d(null)),n.downArrow&&(a(e=>Math.min(m.length-1,e+1)),d(null)),n.return&&g&&(c("actions"),d(null)))});const p=__name(e=>{switch(e){case"connected":return B.createElement(K,{color:"green"},"✓");case"authenticated":return B.createElement(K,{color:"cyan"},"✓");case"requires_auth":return B.createElement(K,{color:"yellow"},"⚠");case"error":return B.createElement(K,{color:"red"},"✗");default:return B.createElement(K,{color:"gray"},"○")}},"getStatusIcon"),h=__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"),f=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),y=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),w=__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||c("confirm-remove");else{if(!g.config.oauth)return void d({text:"No OAuth configured for this server",color:"yellow"});d({text:`Authenticating ${g.name}...`,color:"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:`✓ Authenticated with ${g.name}`,color:"green"});try{const e=getMcpConnectionManager();await e.reconnectServer(g.name)}catch{}await u()}else d({text:`✗ Auth failed: ${t.error}`,color:"red"})}catch(e){d({text:`✗ Failed: ${e instanceof Error?e.message:String(e)}`,color:"red"})}}else{d({text:`Connecting ${g.name}...`,color:"cyan",loading:!0});try{const e=getMcpConnectionManager();await e.reconnectServer(g.name),d({text:`✓ Connected to ${g.name}`,color:"green"}),await u()}catch(e){d({text:`✗ Failed: ${e instanceof Error?e.message:String(e)}`,color:"red"})}}else d({text:"Already authenticated",color:"green"});else d({text:"Already connected",color:"green"});else c("list")},"handleActionSelect"),E=__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}),c("list"),await u(),a(e=>Math.min(e,Math.max(0,m.length-2)))}catch(e){d({text:`✗ Failed: ${e instanceof Error?e.message:String(e)}`,color:"red"}),c("actions")}else c("actions")},"handleRemoveConfirm");if(r)return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"#E4CCFF",bold:!0},"Manage MCP servers"),B.createElement(K,{dimColor:!0},"Loading..."));if("confirm-remove"===i&&g)return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"red",bold:!0},"Remove ",g.name,"?"),B.createElement(K,{dimColor:!0},"This will remove the server from ",g.scope," config."),B.createElement(V,{marginTop:1},B.createElement(He,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:E,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"}," ",t)})),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===i&&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(V,{flexDirection:"column"},B.createElement(K,{color:"#E4CCFF",bold:!0},g.name),B.createElement(V,null,p(g.status),B.createElement(K,{dimColor:!0}," ",h(g))),B.createElement(V,{marginTop:1},B.createElement(He,{items:e,onSelect:w,indicatorComponent:({isSelected:e})=>B.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>B.createElement(K,{color:e?"white":"gray"}," ",t)})),l&&B.createElement(V,{marginTop:1},l.loading&&B.createElement(K,{color:l.color},B.createElement(De,{type:"dots"})," "),B.createElement(K,{color:l.color},l.text)),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to go back")))}let S=null;return B.createElement(V,{flexDirection:"column"},B.createElement(K,{color:"#E4CCFF",bold:!0},"Manage MCP servers"),B.createElement(K,{dimColor:!0},t.length," ",1===t.length?"server":"servers"),0===t.length?B.createElement(V,{marginTop:1,flexDirection:"column"},B.createElement(K,{dimColor:!0},"No MCP servers configured."),B.createElement(K,{dimColor:!0},'Use "cmd mcp add" to add a server.'),B.createElement(K,{dimColor:!0},"Docs: https://commandcode.ai/docs/mcp")):B.createElement(V,{marginTop:1,flexDirection:"column"},m.map((e,t)=>{const n=e.scope!==S;S=e.scope;const r=t===s;return B.createElement(B.Fragment,{key:e.name},n&&B.createElement(V,{marginTop:0===t?0:1},B.createElement(K,{bold:!0},f(e.scope)),B.createElement(K,{dimColor:!0}," (",y(e.scope),")")),B.createElement(V,{paddingLeft:1},B.createElement(K,{color:r?"white":"gray"},r?"› ":" "),B.createElement(K,{color:r?"white":void 0,bold:r},e.name),B.createElement(K,{dimColor:!0}," · "),p(e.status),B.createElement(K,{color:"connected"===e.status?"green":"authenticated"===e.status?"cyan":"requires_auth"===e.status?"yellow":"gray"}," ",h(e))))})),l&&B.createElement(V,{marginTop:1},l.loading&&B.createElement(K,{color:l.color},B.createElement(De,{type:"dots"})," "),B.createElement(K,{color:l.color},l.text)),B.createElement(V,{marginTop:1},B.createElement(K,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");bn();var{setText:Ed}=Ne,{runIDESetup:Sd}=await Promise.resolve().then(()=>(Br(),jr));function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}__name(createKillShellPermissionRequest,"createKillShellPermissionRequest");var kd=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:o,updateFailedInfo:s,initialPrompt:a,skipOnboarding:i=!1,initialPermissionMode:c})=>{const{exit:l}=X(),[d,u]=z(""),[m,g]=z("Ready..."),p=W(!1),[h,f]=z(null),[y,w]=z(o);H(()=>{if(y){const e=setTimeout(()=>{w(null)},3e4);return()=>clearTimeout(e)}},[y]);const{stdout:E}=Q(),[S,k]=z(!1),[v,b]=z(!1),[C,P]=z(!1),[T,A]=z(!1),[x,I]=z(!1),[$,R]=z(!1),[D,M]=z(!1),[N,O]=z(!1),[F,L]=z(!1),[_,U]=z(null),[j,q]=z(null),[J,Y]=z(getConfiguredModel()),[ee,te]=z(!1),[ne,re]=z(!1),[se,ae]=z(!1),ie=W(null),ce=W(null),[le,de]=z(0),[ue,me]=z(!1),{executeBash:ge,executionState:pe}=mi(),[he,fe]=z(""),[ye,we]=z([]),[Ee,Se]=z([]),[ke,ve]=z(!1),[be,Ce]=z([]),[Pe,Te]=z(crypto.randomUUID()),[Ae,xe]=z(!1),[Ie,$e]=z(!1),[Re,De]=z(!1),Me=W(null),[Ne,Oe]=z(!1),[Fe,Le]=z(!1),[_e,Ue]=z(!0),[je,Be]=z(!1),[ze,We]=z(!1),[He,Ge]=z(null),[qe,Ve]=z(!1),Ke=W(!1),[Je,Ye]=z(!1),[Qe,Ze]=z(0),[Xe,et]=z(null),[tt,nt]=z(null),[rt,ot]=z(null),st=W(!1),at=W(!1),it=W(rt);H(()=>{it.current=rt},[rt]);const[ct,lt]=z(!1),[dt,ut]=z(""),[mt,gt]=z(!1),[ht,ft]=z(()=>c||(r?"auto-accept":"standard")),yt=W(ht);H(()=>{yt.current=ht},[ht]);const[wt,kt]=z(""),vt=W(null),bt=W(null),Ct=__name(()=>{vt.current&&clearTimeout(vt.current),bt.current&&clearTimeout(bt.current),ie.current&&clearTimeout(ie.current),ce.current&&clearTimeout(ce.current)},"cleanupTimers"),[Pt,Tt]=z(!1),[At,It]=z(!1),$t=W(null),Rt=W(0),[Dt,Mt]=z(null),Nt=G(()=>{$t.current=null,Mt(null),bt.current&&(clearTimeout(bt.current),bt.current=null)},[]);H(()=>{if(Je){Ct();try{l()}catch{process.exit(0)}}},[Je,l]);const Ot=G(()=>{We(!0),Be(!1),Ve(!1),hi(),de(e=>e+1),e&&xe(!0)},[e,t]),Ft=__name(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(e=>{dlog("[MCP] Failed to initialize",e)})},"initializeMcpInBackground"),Lt=__name(async()=>{try{const e=await isTasteLearningEnabled();gt(e),e&&await ji.initializeProject()}catch(e){}},"loadTasteStatus"),_t=__name(async()=>{const e=await getConfiguredProvider();q(e);const t=await isOAuthEnforced();te(t)},"loadCurrentProvider"),Ut=W([]),jt=W(null),Bt=W(null),[zt,Wt]=z(null),[Ht,Gt]=z(null),{requestShellPermission:qt,service:Vt,respondToPrompt:Kt,clearSessionPermissions:Jt,setEnabled:Yt}=pi({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{Wt({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),jt.current&&g("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Wt({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),jt.current&&g("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?g("Permission granted"):g("Permission denied")},"onPermissionResponse")}),Qt=__name(e=>{vt.current&&clearTimeout(vt.current),kt(e),vt.current=setTimeout(()=>{kt(""),vt.current=null},5e3)},"showHintMessage");H(()=>()=>Ct(),[]),H(()=>{Vt&&applyAutoAcceptMode({enabled:ht,service:Vt})},[ht,Vt]),H(()=>{(async()=>{if(await Fa.isProjectInitialized())if(Le(!0),Ue(!1),Lt(),_t(),Ft(),t){const e=await Fa.listSessions();if(e.length>0){const t=e[0];Tn(t.id)}}else e&&xe(!0);else if(n)if(await Fa.initializeProject(),Le(!0),Ue(!1),Lt(),_t(),Ft(),t){const e=await Fa.listSessions();if(e.length>0){const t=e[0];Tn(t.id)}}else e&&xe(!0);else isDirectoryEmpty()?(await Fa.initializeProject(),Le(!0),Ue(!1),Lt(),_t(),Ft()):(Oe(!0),Ue(!1))})()},[e,t,n,l]),H(()=>{i||triggerTasteOnboarding({projectTrusted:Fe,onboardingComplete:ze,isOnboardingMode:je,tasteOnboardingCheckedRef:Ke,setIsOnboardingMode:Be})},[Fe,ze,je,i]),H(()=>{if(je&&!He){const e=Ls();Ge(e.id),we(t=>[...t,e])}else!je&&He&&(we(e=>e.filter(e=>e.id!==He)),Ge(null))},[je,He]),H(()=>{Ut.current=be},[be]);const Xt=G(e=>({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?Se(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(Se(t=>t.filter(t=>t.id!==e.id)),we(t=>[...t,e])):we(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...Ut.current];return Ut.current=[],Ce([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ze(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{et(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{f(e)},"onRetryUpdate"),onProviderChange:__name(e=>{q(e)},"onProviderChange"),onStatusUpdate:__name(e=>{p.current=!0,g(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{if("shell_command"===e&&Vt){const e={command:t.command||"",args:t.args,workingDirectory:t.directory,description:n??buildFallbackDescription(t)};return Vt.requestShellPermission(e).then(e=>e.allowed)}if("kill_shell"===e&&Vt){const e=createKillShellPermissionRequest(t);return Vt.requestShellPermission(e).then(e=>e.allowed)}if(Vt){const n={action:e.includes("edit")?"edit":e.includes("write")?"create":e.includes("delete")?"delete":"edit",filePath:t.filePath||t.file_path||t.path||t.absolutePath||"unknown",description:t.description||`${e} operation`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return Vt.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Gt({params:e,resolve:t,reject:n}),g("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const t=it.current;return t?{sessionId:e||Pe,secret:t.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>yt.current,"getPermissionMode")}),[ht,Pe,Vt]);H(()=>{(async()=>{if(j&&"anthropic"===j&&ee)try{await Zt.getValidAccessToken()||g("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){g("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[j,ee]),H(()=>{if(!ke)return void(p.current=!1);if(null!==h)return;const e=setInterval(()=>{p.current||g(qs())},7e3);return()=>clearInterval(e)},[ke,h]);const en=G(()=>{const e=!ke&&!zt&&!Ht,t=jt.current?.hasCheckpoints()??!1;e&&t&&Tt(!0)},[ke,zt]),tn=G(()=>{if(!jt.current)return;jt.current.interrupt(!0);const e=Ee.length>0;if(ve(!1),f(null),Se([]),g("Interrupted by user"),!e){const e=Fs("Interrupted by user");we(t=>[...t,e])}if(Ut.current.length>0){const e=Ut.current.join("\n");u(t=>t?e+"\n"+t:e),Ce([]),Ut.current=[]}},[Ee]),nn=__name(()=>{ft(e=>{let t;return t="standard"===e?"auto-accept":"auto-accept"===e?"plan":"standard","auto-accept"===t&&zt&&(Kt({label:"Yes",value:"yes",description:"Allow this action",scope:void 0}),zt.resolve(!0),Wt(null)),"plan"===t&&zt&&(zt.resolve(!1),Wt(null)),t}),hi(),de(e=>e+1)},"handleToggleAutoAccept");async function getBillingLink(){if(tt)return tt;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return nt(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return nt(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}Z((e,t)=>{if(t.shift&&t.tab||"[Z"===e)nn();else if(C||T||x||$||D||N||_||F||Pt||At||Ie)Dt&&Nt();else{if(""===e||t.ctrl&&"c"===e){if(ke&&jt.current)return void tn();const e=Date.now(),t=e-Rt.current;return Rt.current=e,void("ctrl-c"===$t.current&&t<2e3?(bt.current&&(clearTimeout(bt.current),bt.current=null),Ye(!0)):(u(""),$t.current="ctrl-c",Mt("ctrl-c"),bt.current&&clearTimeout(bt.current),bt.current=setTimeout(()=>{$t.current=null,Mt(null),bt.current=null},2e3)))}if(t.ctrl&&"t"===e)return hi(),L(e=>!e),void de(e=>e+1);if(getIsExpandToolShortcut(t,e))return hi(),me(e=>!e),void de(e=>e+1);if(t.meta&&"p"===e||isAltP(e))R(!0);else{if(t.escape){if(Ht)return Ht.reject(new Error("Question cancelled by user")),Gt(null),void g("Question cancelled");zt?(Kt({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),zt.resolve(!1),Wt(null),g("Permission denied")):ke&&jt.current&&tn()}t.meta||t.ctrl}}}),H(()=>{const e=__name(()=>{hi(),de(e=>e+1)},"handleResize");if(E)return E.on("resize",e),()=>{E.off("resize",e)}},[E]),H(()=>{jt.current||!Fe||Ae||Re||(jt.current=new ii(Xt(),Pe),(async()=>{await pn()})())},[Pe,Ae,Re,Fe]),H(()=>{if(!Fe)return;const e=createHistoryManager();return Me.current=e,e.init(),()=>{e.cleanup()}},[Fe]),H(()=>{a&&Fe&&!_e&&jt.current&&!Ae&&!at.current&&(at.current=!0,rn({role:"user",input:a}))},[a,Fe,_e,Ae]),__name(getBillingLink,"getBillingLink");const rn=__name(async({role:e,input:t,images:n,ideContext:r})=>{if(t.length)if(y&&w(null),Ze(0),"bash"===e){if(st.current)return;st.current=!0;const e=Ns(t);we([...ye,e]),u(""),await ge(t,e=>{we(e)},()=>{hi(),de(e=>e+1)}),st.current=!1}else{if(ke)return Ce(e=>[...e,t]),void u("");if(st.current)return;st.current=!0,ve(!0),g(qs()),u("");try{jt.current&&await jt.current.sendMessage(t,n,r)}catch(e){if("Interrupted by user"===e?.message||e?.message?.toLowerCase().includes("interrupt")||e?.message?.toLowerCase().includes("abort")||"InterruptedError"===e?.name||"AbortError"===e?.name||"ECONNABORTED"===e?.code);else if("Insufficient credits"===e.message){g("Insufficient credits");const e=await getBillingLink(),t=Fs(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);we(e=>[...e,t])}else if(e.message.startsWith("Error:")){g("Error");const t=Fs(e.message);we(e=>[...e,t])}else{g("Error");const t=e.message||"An unexpected error occurred",n=Fs(t);we(e=>[...e,n])}}finally{ve(!1),"Interrupted by user"!==m&&"Permission denied"!==m&&"Insufficient credits"!==m&&g("Ready..."),st.current=!1}}},"handleSubmit"),on=__name(()=>{we(e=>[...e,Os("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),sn=__name(()=>{const e=$s(`/${Et.TERMINAL_SETUP}`),t=setupVSCodeTerminal(),n=_s(t.message,!t.success,t.details);we(t=>[...t,e,n])},"handleTerminalSetupCommand"),an=__name(async()=>{const e=await Sd(),t=Us(e.status,e.ide,e.details);we(e=>[...e,t])},"handleIDESetupCommand"),cn=__name(async()=>{if(we([]),Se([]),hi(),ot(null),lt(!1),ut(""),jt.current){const e=jt.current.getSessionManager();e&&await e.deleteShareInfo(),jt.current=null;const t=crypto.randomUUID();Te(t),Jt(),jt.current=new ii(Xt(t),t)}de(e=>e+1),et(null),Ze(0)},"handleClearCommand"),ln=__name(()=>{jt.current?jt.current.hasCheckpoints()?Tt(!0):we(e=>[...e,Rs("No checkpoints available. Start sending messages to create checkpoints.")]):we(e=>[...e,Rs("No active conversation to rewind.")])},"handleRewindCommand"),dn=__name(async e=>{const{messageId:t,mode:n}=e;if(Tt(!1),jt.current)try{const e=jt.current.listCheckpoints().find(e=>e.messageId===t);g("Restoring checkpoint...");const r=await jt.current.restoreToCheckpoint({messageId:t,mode:n});if(r.success){const t=jt.current.getSessionManager(),n=jt.current.getMessages(),o=t.reconstructFeedFromMessages(n);we(o),hi(),de(e=>e+1),e&&e.userPrompt&&u(e.userPrompt);const s=[];r.filesRestored>0&&s.push(`${r.filesRestored} file${r.filesRestored>1?"s":""} restored`),r.filesDeleted>0&&s.push(`${r.filesDeleted} file${r.filesDeleted>1?"s":""} deleted`),r.messagesRemoved>0&&s.push(`${r.messagesRemoved} message${r.messagesRemoved>1?"s":""} removed`);const a=s.length>0?`Restored to checkpoint: ${s.join(", ")}.`:"Restored to checkpoint.";we(e=>[...e,Rs(a)]),g("Ready...")}else we(e=>[...e,Fs(`Failed to restore: ${r.error}`)]),g("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;we(e=>[...e,Fs(t)]),g("Ready...")}},"handleRewindSelect"),un=__name(()=>{Tt(!1)},"handleRewindCancel"),mn=__name(async()=>{if(jt.current)if(jt.current.isRequestInProgress())we(e=>[...e,Rs("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{ve(!0),g("Compacting conversation...");const e=await jt.current.manualCompact();hi(),de(e=>e+1);let t="Compacted conversation.";e.didCompact||(t="Conversation is already compact."),e.didCompact&&e.tokensSaved>0&&(t=`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`),we(e=>[...e,Rs(t)]),ve(!1),g("Ready..."),et({current:jt.current.getContextTokensUsed()||0,limit:Wa})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;we(e=>[...e,Fs(t)]),ve(!1),g("Ready...")}else we(e=>[...e,Rs("No active conversation to compact.")])},"handleCompactCommand"),gn=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await Tn(t)}const t=parseCommandInput({input:e});if(!t)return;const{commandName:n,rawArguments:r,positionalArgs:o}=t;switch(n){case"/exit":return void Ye(!0);case"/clear":return void await cn();case"/help":return void on();case"/share":return void hn();case"/unshare":return void Cn();case"/taste":return void P(!0);case"/learn-taste":return void await Pn();case"/skills":return void A(!0);case"/provider":return void(isInternalTeamFlagEnforced()?I(!0):g("Provider selection not available"));case"/model":return void R(!0);case"/memory":return void M(!0);case"/init":return void fn();case"/agents":return void b(!0);case"/mcp":return void yn();case"/compact":return void await mn();case"/rewind":return void ln();case"/login":return void await En();case"/logout":return void await vn();case"/feedback":return void await bn();case"/terminal-setup":return void sn();case"/ide":return void await an();case"/add-dir":return void $e(!0)}const s=getCustomCommandContent(n);if(s){const e=processCommandTemplate({template:s,rawArguments:r,positionalArgs:o});await rn({input:e.content,role:"user"})}},"handleCommand"),pn=__name(async()=>{const e=jt.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&ot({url:t.url,secret:t.secret})}},"loadShareInfo"),hn=__name(async()=>{if(Pe){if(rt)return await Ed(rt.url),g(""),lt(!0),void setTimeout(()=>{lt(!1)},3e3);try{g("Creating share link...");const e=jt.current?.getMessages()||[],t=Ao.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new _o({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:pt.ALPHA.SHARE.CREATE,body:{sessionId:Pe,messages:t}}),o={url:r.url,secret:r.secret};ot(o);const s=jt.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await Ed(r.url),g(""),lt(!0),setTimeout(()=>{lt(!1)},5e3)}catch(e){g(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else g("No active session to share")},"handleShareCommand"),fn=__name(async()=>{try{const e=process.cwd(),t=`Created AGENTS.md at ${await initProjectMemory(e)}. You can now edit it with /memory or open it in your editor.`;we(e=>[...e,Rs(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;we(e=>[...e,Rs(t)])}},"handleInitCommand"),yn=__name(()=>{O(!0)},"handleMcpCommand"),wn=__name(()=>{O(!1)},"handleMcpClose"),En=__name(async()=>{const e=xt();if(await getAuthKey(e)){let e="";try{const t=await loadCredentials();e=t?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const t=e&&"API Key"!==e&&"Manual API Key"!==e?` as ${e}`:"";return void we(e=>[...e,Rs(`Already logged in${t}`)])}It(!0)},"handleLoginCommand"),Sn=G((e,t)=>{It(!1),e?(we(e=>[...e,Rs(t)]),jt.current&&jt.current.refreshRequest()):we(e=>[...e,Fs(t)]),g("Ready...")},[]),kn=G(()=>{It(!1),we(e=>[...e,Rs("Authentication cancelled.")]),g("Ready...")},[]),vn=__name(async()=>{const e=await performLogout();e.success?(jt.current&&jt.current.refreshRequest(),e.wasAuthenticated?e.warnings.length>0?we(t=>[...t,Rs(`Successfully logged out from Command Code. Warnings: ${e.warnings.join(", ")}`)]):we(e=>[...e,Rs("Successfully logged out from Command Code.")]):we(e=>[...e,Rs("Not currently authenticated.")])):we(t=>[...t,Fs(`Logout failed: ${e.error}`)])},"handleLogoutCommand"),bn=__name(async e=>{const t=buildGitHubIssueUrl(e);try{await oe(t,{wait:!1,background:!0}),we(e=>[...e,Rs(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`)])}catch(e){we(e=>[...e,Fs("Failed to open browser"),Os(createOSC8Link(t,"Open GitHub issue manually"))])}},"handleFeedbackCommand"),Cn=__name(async()=>{if(Pe){if(!rt)return ut("NOT SHARED: Session is not currently shared"),void setTimeout(()=>ut(""),5e3);try{g("Removing share link...");const e=new _o({baseUrl:getApiBaseUrl()});await e.delete({endpoint:pt.ALPHA.SHARE.DELETE,body:{sessionId:Pe,secret:rt.secret}});const t=jt.current?.getSessionManager();t&&await t.deleteShareInfo(),ut("UNSHARED: Sharing has stopped"),g(""),ot(null),setTimeout(()=>{ut("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;g(t),setTimeout(()=>g(""),5e3)}}else g("No active session to unshare")},"handleUnshareCommand"),Pn=__name(async()=>{Ve(!0),Be(!0);const e=Ls();Ge(e.id),we(t=>[...t,e])},"handleLearnCommand"),Tn=__name(async e=>{const t=crypto.randomUUID();Bt.current=t;try{we([]),Se([]),jt.current=null,ft("standard"),Te(e),xe(!1),De(!0),jt.current=new ii(Xt(e),e);const{feedEntries:n,corruptedLines:r,totalLines:o}=await jt.current.loadSession(e);if(Bt.current!==t)return;await pn();const s=[];if(0===n.length&&o>0?s.push(Fs(`Session could not be loaded. ${o} lines could not be parsed.`)):0===n.length?s.push(Rs("Session loaded but contains no messages.")):(r>0&&s.push(Rs(`Warning: ${r} message(s) could not be loaded.`)),s.push(...n)),Bt.current!==t)return;we(s),hi(),de(e=>e+1)}catch(e){if(Bt.current!==t)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";we([Fs(`Failed to load session: ${n}. Starting fresh session.`)]),xe(!1),De(!1),Te(crypto.randomUUID())}},"handleSelectSession"),An=__name(async()=>{we([]),Se([]),jt.current=null,ft("standard"),Te(crypto.randomUUID()),xe(!1),De(!1)},"handleNewSession"),xn=__name(async()=>{try{await Fa.initializeProject(),Oe(!1),e?(console.log("No conversations found to resume."),Ye(!0)):(Le(!0),Lt(),_t())}catch(e){console.error("Failed to initialize project:",e),Oe(!1),Ye(!0)}},"handleTrust"),In=__name(()=>{Ye(!0)},"handleNoTrust"),$n=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void U({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),q(e),I(!1);const n=getProviderDisplayName(e);g(`Provider set to ${n}`),ie.current&&clearTimeout(ie.current),re(!0),ie.current=setTimeout(()=>{re(!1),ie.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),g("Failed to set provider"),I(!1)}},"handleProviderSelect"),Rn=__name(()=>{I(!1)},"handleProviderCancel"),Dn=__name(e=>{const t=Object.values(St).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),Mn=__name(async e=>{try{await setSelectedModel({model:e}),Y(e),R(!1);const t=Dn(e);g(`Model set to ${t}`),ce.current&&clearTimeout(ce.current),ae(!0),ce.current=setTimeout(()=>{ae(!1),ce.current=null},5e3)}catch(e){console.error("Failed to set model:",e),g("Failed to set model"),R(!1)}},"handleModelSelect"),Nn=__name(()=>{R(!1)},"handleModelCancel"),On=__name(()=>{if(_){U(null),I(!1),q(_.provider);const e=getProviderDisplayName(_.provider);g(`${e} authentication successful`),ie.current&&clearTimeout(ie.current),re(!0),ie.current=setTimeout(()=>{re(!1),ie.current=null},5e3)}},"handleAuthSuccess"),Fn=__name(()=>{U(null)},"handleAuthCancel");if(Je)return null;if(Ne)return B.createElement(B.Fragment,null,B.createElement(al,{staticKey:le}),B.createElement(Kl,{onTrust:xn,onExit:In}));if(_e)return null;if(Ae)return B.createElement(ll,{onSelectSession:Tn,onNewSession:An});if(!Fe)return null;if(Ht)return B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(nl,{staticKey:le,feed:ye,showHeader:!0,expandedToolOutput:ue,currentModel:J}),B.createElement(V,{marginY:1},B.createElement(yd,{questions:Ht.params.questions,hideCustomInput:Ht.params.hideCustomInput,onResponse:e=>{if(Ht.params.exitPlanMode){const t=e.answers[0]?.selectedOptions[0]||"";t.startsWith("Yes, auto-accept")?(ft("auto-accept"),hi(),de(e=>e+1)):t.startsWith("Yes, exit")&&(ft("standard"),hi(),de(e=>e+1))}if(Ht.params.enterPlanMode){const t=e.answers[0]?.selectedOptions[0];t?.startsWith("Yes")&&(ft("plan"),hi(),de(e=>e+1))}Ht.resolve(e),Gt(null),g("Answers submitted")}})));if(zt){if("shell_command"===zt.toolName){const e=zt.params;return B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(nl,{staticKey:le,feed:ye,showHeader:!0,expandedToolOutput:ue,currentModel:J}),Ee.map(e=>B.createElement(LiveAgentStatus,{key:e.id,entry:e})),B.createElement(V,{marginY:1},B.createElement(ul,{request:e,onResponse:e=>{Kt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(g("Shell command allowed"),"standard"===ht&&Qt("Use shift+tab to enable auto-accept")):g("Shell command denied")},onToggleAutoAccept:nn})))}if("kill_shell"===zt.toolName){const e=createKillShellPermissionRequest(zt.params);return B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(nl,{staticKey:le,feed:ye,showHeader:!0,expandedToolOutput:ue,currentModel:J}),B.createElement(V,{marginY:1},B.createElement(ul,{request:e,onResponse:e=>{Kt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(g("Process termination allowed"),"standard"===ht&&Qt("Use shift+tab to enable auto-accept")):g("Process termination denied")},onToggleAutoAccept:nn})))}{const e={action:zt.toolName.includes("edit")?"edit":zt.toolName.includes("write")?"create":zt.toolName.includes("delete")?"delete":"edit",filePath:zt.params.filePath||zt.params.file_path||zt.params.path||zt.params.absolutePath||zt.params.notebook_path||"unknown",description:`Allow ${zt.toolName} operation`,oldContent:"edit_file"===zt.toolName?zt.params.oldContent:void 0,newContent:"edit_file"===zt.toolName?zt.params.newContent:void 0};return B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(nl,{staticKey:le,feed:ye,showHeader:!0,expandedToolOutput:ue,currentModel:J}),Ee.map(e=>B.createElement(LiveAgentStatus,{key:e.id,entry:e})),B.createElement(V,{marginY:1},B.createElement(ol,{request:e,onResponse:e=>{Kt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(g("File operation allowed"),"standard"===ht&&Qt("Use shift+tab to enable auto-accept")):g("File operation denied")},onToggleAutoAccept:nn})))}}return F?B.createElement(Uc,{onClose:()=>{L(!1),de(e=>e+1)}}):C?B.createElement(B.Fragment,null,B.createElement(al,{staticKey:le}),B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Press Esc to return to conversation")),B.createElement(pl,{onClose:()=>P(!1),onSettingsChange:Lt,staticKey:le}))):T?B.createElement(B.Fragment,null,B.createElement(al,{staticKey:le}),B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(V,{marginBottom:1},B.createElement(K,{dimColor:!0},"Press Esc to return to conversation")),B.createElement(gl,{onClose:()=>A(!1),staticKey:le}))):B.createElement(V,{flexDirection:"column",width:"100%"},B.createElement(nl,{staticKey:le,feed:ye.filter(e=>"taste-onboarding"!==e.role),showHeader:!0,expandedToolOutput:ue,currentModel:J}),He&&B.createElement(Vl,{onComplete:Ot,autoLearn:qe}),Ee.map(e=>B.createElement(LiveAgentStatus,{key:e.id,entry:e})),B.createElement(RetryMessage,{attempt:h}),!x&&!$&&!_&&!D&&!N&&!v&&!Pt&&!At&&!Ie&&!He&&B.createElement(_c,{queuedMessages:be,isProcessing:ke,executionState:pe,status:m,input:d,setInput:u,onSubmit:rn,showFileList:S,setShowFileList:k,fileSearchQuery:he,setFileSearchQuery:fe,onCommand:gn,outputTokens:Qe,contextUsage:Xe,tasteLearning:mt,shareInfo:rt,showShareNotification:ct,unshareNotificationMessage:dt,updateStatus:y,updateFailedInfo:s,currentProvider:j,showProviderInfo:ne,permissionMode:ht,onToggleAutoAccept:nn,hintMessage:wt,historyManager:Me.current,pendingExitKey:Dt,onResetPendingExitKey:Nt,onDoubleEscapeEmpty:en,retryAttempt:h,onAltP:()=>R(!0)}),x&&B.createElement(V,{marginY:1},B.createElement(sl,{onSelect:$n,onCancel:Rn,currentProvider:j})),$&&B.createElement(V,{marginY:1},B.createElement(rl,{onSelect:Mn,onCancel:Nn,currentModel:J})),v&&B.createElement(V,{marginY:1},B.createElement(oc,{onCancel:()=>b(!1)})),D&&B.createElement(V,{marginY:1},B.createElement(jc,{onClose:()=>M(!1)})),N&&B.createElement(V,{marginY:1},B.createElement(wd,{onClose:wn})),Pt&&jt.current&&B.createElement(V,{marginY:1},B.createElement(cl,{checkpoints:jt.current.listCheckpoints(),onSelect:dn,onCancel:un})),_&&B.createElement(V,{marginY:1},B.createElement(_.Component,{onSuccess:On,onCancel:Fn})),At&&B.createElement(V,{marginY:1},B.createElement(Jl,{onComplete:Sn,onCancel:kn})),Ie&&B.createElement(V,{marginY:1},B.createElement(dl,{onClose:()=>{$e(!1)}})))},"InteractiveCLI");kn(),dn();var vd=__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"),bd=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),Cd=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),Pd=__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"),Td=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),Ad=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),xd=__name(()=>{Ad()},"initializeTerminal"),Id=__name(async(e={})=>{const t=vd(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),xd(),bd(e)){const e=await Fa.isProjectInitialized(),t=e?await Fa.listSessions():[],n=Cd({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=Pd({options:e}),r=Td();Y(B.createElement(kd,{...n}),r)},"interactiveMode");Tt(),$t(),rn(),Tn(),In(),Vt();var $d=null,Rd=!1,Dd=new Set([Ho,Go,Jo]);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(Rd)return;Rd=!0;const e=__name(e=>{$d?.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(),$d=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:$d.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 Ro&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof Do&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof Fo&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Io&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof Lo&&(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 Md=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===yt.ANTHROPIC&&(r=await Zt.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o=getEnvironmentContext(),s=await getMemoryContent([]),a=await getTasteContent(),i=generateSkillsXML(await loadAllSkillSummaries())||null,c=crypto.randomUUID(),l=await isTasteLearningEnabled(),d={[gt.PROJECT_SLUG]:Fa.getCurrentProjectDirName(),[gt.TASTE_LEARNING]:l.toString(),[gt.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(d[gt.OAUTH_TOKEN]=`Bearer ${r}`),{tools:e,config:o,memory:s,taste:a,skills:i,headers:d,sessionId:c}}async function callApi(e,t,n,r){const o={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:`anthropic:${getConfiguredModel()}`},s={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:o,threadId:t.sessionId},a=await e.post({body:s,stream:!0,endpoint:pt.ALPHA.GENERATE,headers:t.headers,signal:r});return Be.fromReadableStream(a).finalMessage()}async function executeToolCall(e,t,n){if(Dd.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 Ro||t instanceof Do||t instanceof Fo||t instanceof Io||t instanceof Lo)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1}=e,o=getApiBaseUrl(),s=new _o({baseUrl:o}),a=[{role:"user",content:t}],i=await setupConversationContext();let c=0,l="";for(;c<Md;){if(c++,n.aborted)throw new Error("Cancelled");const e=await callApi(s,i,a,n),t=e.content.filter(e=>"text"===e.type),o=e.content.filter(e=>"tool_use"===e.type),d=t.map(e=>e.text).join("");if(d&&(l+=d),0===o.length)break;const u=[];for(const e of o){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);u.push(t)}a.push({role:"assistant",content:e.content}),a.push({role:"user",content:u})}return c>=Md&&process.stderr.write(`Warning: Reached maximum conversation turns (${Md}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),l}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery"),Ot();var Nd=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),Od=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),Fd=__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"),Ld=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),_d=__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=_d(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=Nd(e);await Od();const r=Fd(t),o=Ld({options:t,runtimeOptions:r,initialPrompt:n});Id(o)}__name(interactiveModeAction,"interactiveModeAction"),Tt(),bn(),Br(),globalThis.COMMAND_CODE_CWD=process.cwd();var Ud=__name(()=>process.cwd(),"getCwd"),jd=__name(()=>process.argv.slice(2),"getArgs"),Bd=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),zd=__name(()=>{const e=Ud(),t=jd(),n=Bd(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`)},"logStartupInfo");async function preRun(){zd(),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"),Tt(),$t(),bn(),Un(),xn();var Wd=getPackageJson(),Hd=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=Wd.version,t=getInvokedCommandName(),n=Yc.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ee.bold("Command Code")+ee.gray(` v${e}`)),console.log(ee.gray(qc)),console.log(),console.log(ee.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ee.bold("Options"));for(const e of Jc){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Vc)+ee.gray(e.description))}console.log(),console.log(ee.bold("Commands"));for(const e of Qc){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Vc)+ee.gray(e.description))}console.log(),console.log(ee.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Vc)+ee.gray(e.description));console.log(),console.log(ee.bold("Keyboard Shortcuts"));for(const e of Kc)console.log(" "+e.key.padEnd(Vc)+ee.gray(e.description));console.log(),console.log(ee.bold("Examples"));for(const e of Xc){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Vc)+ee.gray(e.description))}console.log(),console.log(ee.cyan("❯")+" "+ee.gray(el.replace(/cmd/,t))),console.log(),console.log(ee.bold("Links"));for(const e of Zc)console.log(" "+e.key.padEnd(Vc)+ee.cyan(e.description));console.log()}function createProgram(){const e=new be;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(Wd.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 Ce("--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",Hd,[]).addOption(new Ce(ut).hideHelp()).addOption(new Ce(mt).hideHelp()).addOption(new Ce("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ce("--local","Use local server").hideHelp()).addOption(new Ce("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(`[cmd] ${r&&r!==n?"subcommand":"running"}: ${n}`);const o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const a=t.args;a.length>0&&dlog(`[cmd] arguments: ${a.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Tt(),fr();var Gd=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=p.platform(),n=p.arch();let r,o,s,a;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,o=e.user?.id,s=e.org?.login,a=e.org?.id)}catch{}if(!o)try{const e=await loadCredentials();o=e?.userId}catch{}systemInfo({userName:r,userId:o,orgLogin:s,orgId:a,nodeVersion:e,platform:t,arch:n})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){Gd||(Gd=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Me("Opening GitHub issues...").start();try{await oe(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"),Tt(),__name(openGitHubIssue,"openGitHubIssue");var qd=new be("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Tt();var Vd=new be("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});Tt();var Kd=new be("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{const{waitUntilExit:t}=Y(B.createElement(ad,{verbose:e.verbose,text:e.text}));await t()});Tt(),$t(),bn(),fr();var Jd=new be(Et.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{const{unmount:e}=Y(B.createElement(Gl,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:dr.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 be("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 Ce("-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().action(async(e,t,n,r)=>{const o=getInvokedCommandName();try{let s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ee.red(`Error: Invalid server name '${e}'`)),console.error(ee.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(ee.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ee.gray("Valid options: stdio, http")),process.exit(1));let a=!1;if("http"===n.transport){t||(console.error(ee.red("Error: URL is required for http transport")),console.error(ee.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ee.red(`Error: Invalid URL '${t}'`)),process.exit(1)}s={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(ee.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ee.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ee.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(ee.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${Er}/callback`]});e&&(n=e.clientId,t=e.clientSecret)}s.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},console.log(ee.gray("A browser window will open for authentication.\n"));const o=await performOAuthFlow(e,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(ee.gray(` ${e}`))},"onStatus")});o.success?console.log(ee.green("✓ Successfully authenticated")):(a=!0,console.log(ee.yellow(`Warning: Authentication failed: ${o.error}`)),console.log(ee.gray("You can retry with: cmd mcp auth "+e)),console.log(ee.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,a=process.argv.indexOf("--");let i,c=[];if(-1!==a){const e=process.argv.slice(a+1);0===e.length&&(console.error(ee.red("Error: Command is required for stdio transport")),console.error(ee.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),i=e[0],c=e.slice(1)}else if(t){i=t;const n=o.indexOf(e);-1!==n&&o.length>n+2&&(c=o.slice(n+2))}else console.error(ee.red("Error: Command is required for stdio transport")),console.error(ee.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ee.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);s={transport:"stdio",enabled:!0,command:i,...c.length>0&&{args:c},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:s,scope:n.scope});const i="user"===n.scope?"global":"project"===n.scope?"project":"local";if(a?console.log(ee.yellow(`✓ Added MCP server '${e}' to ${i} config (authentication pending)`)):console.log(ee.green(`✓ Added MCP server '${e}' to ${i} config`)),"http"===s.transport)console.log(ee.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(ee.gray(` Command: ${e}`))}console.log(""),console.log(ee.cyan("Next steps:")),console.log(ee.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ee.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(ee.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(ee.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),o=e.substring(n+1).trim();return r||(console.error(ee.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new be("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ee.yellow("\nNo MCP servers configured\n")),console.log(ee.gray("Add a server with:")),console.log(ee.gray(" cmd mcp add --transport http <name> <url>")),console.log(ee.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ee.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ee.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ee.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?ee.green("enabled"):ee.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?ee.green("✓"):ee.red("✗"):o.config.headers||o.config.env?ee.green("✓"):ee.gray("-"),console.log(` ${ee.white(o.name.padEnd(t))} ${ee.cyan(o.config.transport.padEnd(n))} ${ee.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ee.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new be("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(ee.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ee.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ee.dim("Scope:")} ${r}`),console.log(` ${ee.dim("Transport:")} ${n.transport}`),console.log(` ${ee.dim("Status:")} ${n.enabled?ee.green("enabled"):ee.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ee.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ee.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(` ${ee.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ee.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ee.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(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new be("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ce("-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(ee.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ee.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ee.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(ee.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new be("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 Ce("-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 o,s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ee.red(`Error: Invalid server name '${e}'`)),console.error(ee.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{o=JSON.parse(t)}catch{console.error(ee.red("Error: Invalid JSON")),console.error(ee.gray("Make sure to quote the JSON string properly")),console.error(ee.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}o&&"object"==typeof o&&"type"in o&&!("transport"in o)&&(o.transport=o.type,delete o.type),o?.oauth?.callbackPort&&(s=o.oauth.callbackPort,delete o.oauth.callbackPort),n.clientSecret&&o?.oauth&&(o.oauth.clientSecret=n.clientSecret);const a=ds.safeParse(o);if(!a.success){console.error(ee.red("Error: Invalid server configuration"));for(const e of a.error.issues)console.error(ee.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const i=a.data;let c=!1;if("http"!==i.transport||i.url||(console.error(ee.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==i.transport||i.command||(console.error(ee.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:i,scope:n.scope}),i.oauth){console.log(ee.cyan("Starting OAuth authentication...")),console.log(ee.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:i.oauth.authorizationUrl,tokenUrl:i.oauth.tokenUrl,clientId:i.oauth.clientId,clientSecret:i.oauth.clientSecret,scopes:i.oauth.scopes},n=await performOAuthFlow(e,t,{...s&&{port:s},onStatus:__name(e=>{console.log(ee.gray(` ${e}`))},"onStatus")});n.success?console.log(ee.green(`\n✓ Successfully authenticated with '${e}'`)):(c=!0,console.error(ee.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ee.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ee.gray("Or authenticate via the /mcp menu in a session")))}const l="user"===n.scope?"global":"project"===n.scope?"project":"local";if(c?console.log(ee.yellow(`✓ Added MCP server '${e}' to ${l} config (authentication pending)`)):console.log(ee.green(`✓ Added MCP server '${e}' to ${l} config`)),"http"===i.transport)console.log(ee.gray(` URL: ${i.url}`));else{const e=[i.command,...i.args||[]].join(" ");console.log(ee.gray(` Command: ${e}`))}console.log(""),console.log(ee.cyan("Next steps:")),console.log(ee.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new be("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(ee.yellow("No servers with stored authentication."));console.log(ee.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ee.yellow("expired"):ee.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ee.red("Error: Server name is required")),console.error(ee.gray(`Usage: ${n} mcp auth <server>`)),console.error(ee.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ee.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ee.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ee.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ee.gray(" A refresh token is available for re-authentication"));else{if(console.log(ee.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ee.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ee.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ee.green(`✓ Cleared authentication for '${e}'`)):console.log(ee.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ee.red(`Error: MCP server '${e}' not found`)),console.error(ee.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(ee.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(ee.gray(`Add OAuth config using "${n} mcp add-json" with oauth field`)),process.exit(1));const o={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(ee.cyan(`Authenticating with '${e}'...`)),console.log(ee.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,o,{onStatus:__name(e=>{console.log(ee.gray(` ${e}`))},"onStatus")});if(s.success)return console.log(ee.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ee.gray("Restart the session to connect with the authenticated server."));console.error(ee.red(`\nError: Authentication failed: ${s.error}`)),console.log(ee.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ee.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new be("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(p.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")}Tt(),Tt(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Tt(),__name(listMcpCommand,"listMcpCommand"),Tt(),__name(getMcpCommand,"getMcpCommand"),Tt(),__name(removeMcpCommand,"removeMcpCommand"),Tt(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Tt(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Tt(),$t(),Tt(),Tt(),Tt(),$t(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Tt(),Tt();var Yd=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||Yd.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:Yd.test(o)&&!o.startsWith("#")&&!o.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:o}=findLookaheadEnd(e,t),s=o?r+1:r;return{combined:[n,...e.slice(t,s).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:s}}function processRawLine(e,t){const n=e[t],r=t+1,o=n.trim();if(!o.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(Yd.test(o))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:s,nextIdx:a}=joinMultiLineLearning(e,t+1,n);return{entry:{text:s,originalLineNum:r},nextIdx:a}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:o}=processRawLine(e,n);t.push(r),n=o}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!Yd.test(o))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),a=s.length>0?s[s.length-1]:null;if(!a)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const i=a[1],c=parseFloat(i);if(isNaN(c))return r.push({line:n,severity:"error",message:`Confidence value "${i}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(c<0||c>1)&&r.push({line:n,severity:"error",message:`Confidence value ${c} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),c>=0&&c<=1&&0===c&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const l=void 0!==a.index?o.substring(0,a.index).trim():o.trim();return l&&0!==l.length?(l.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(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),o=r.findIndex(e=>e.trim().startsWith("# "));return(-1===o?r:r.slice(0,o)).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),o=t.filter(e=>"warning"===e.severity),s=0===r.length;if(0===t.length)return{valid:s,issues:[...t],summary:`✓ ${n} is valid`};const a=[];r.length>0&&a.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&a.push(`${o.length} warning${o.length>1?"s":""}`);const i=r.length>0?"✗":"⚠";return{valid:s,issues:[...t],summary:`${i} ${n} has ${a.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ee.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ee.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`${ee.green(e)} ${ee.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?ee.red(t.summary):ee.yellow(t.summary),"",...formatIssueGroup(r,ee.red,ee.bold(ee.red("Errors:"))),...formatIssueGroup(o,ee.yellow,ee.bold(ee.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"),Tt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var Qd=new Set(["# 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:o}=e;Qd.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,o),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 Zd=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:o}=e,s=t.trim();s&&(s.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:o}):s.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):Zd.test(s)||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 o=t.split("\n"),s=preprocessLines(o),a={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of s)processLine({line:e,lineNum:t,state:a,rawLines:o});return checkFinalCategory({state:a,rawLines:o}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var Xd=__name(e=>"local-global"===e?"global":"project","locationLabel"),eu=__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 ${Xd(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=[],o=getRootTasteFile({target:n});E(o)&&r.push({path:o,displayName:"taste.md"});const s=(await D.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(...s),r}async function lintFile(e){let t=await D.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await D.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),o=r.issues.filter(e=>"error"===e.severity).length,s=r.issues.filter(e=>"warning"===e.severity).length,a=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:o,warnings:s,formatted:a}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:o}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&o.length>0)return{success:!1,filesLinted:[],errors:o,totalErrors:0,totalWarnings:0};if(0===r.length)return eu({file:"all",error:`No taste files found in ${Xd(n)}`});const s=await Promise.all(r.map(lintFile)),a=s.reduce((e,t)=>e+t.errors,0),i=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid)&&0===o.length,filesLinted:s,errors:o,totalErrors:a,totalWarnings:i}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return eu({file:"all",error:`No taste files found in ${Xd(n)}`});const o=await Promise.all(r.map(lintFile)),s=o.reduce((e,t)=>e+t.errors,0),a=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid),filesLinted:o,errors:[],totalErrors:s,totalWarnings:a}}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}):eu({file:"all",error:`No taste directory found in ${Xd(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"),Tt(),fr(),__name(resolveConflictStrategy,"resolveConflictStrategy");var tu=ee.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(`${ee.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?`${ee.dim(t[1])}${ee.green(t[2])}${ee.white(t[3]??"")}${t[4]?ee.dim(t[4]):""}`:ee.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ee.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 nu=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return et(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:nu})}function getProfileLink(e){return et(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:nu})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return Xe(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(ee.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(`${ee.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),o=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${o} day${o>1?"s":""} ago`}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(ee.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new be("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 ${ee.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(`${ee.green(Se.tick)} All ${ee.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ee.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ee.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(ee.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),o=r[0].trim(),s=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===s.length?null:{category:normalizeCategory({category:o}),learnings:s,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;let n=await D.readFile(t,"utf-8");const r=migrateHeader({content:n});return r===n?n:(await D.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 o=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===o)return{start:r,end:t.length-1};const s=trimTrailingBlanks({lines:t,from:o-1,until:r});return{start:r,end:s}}function ensureHeader(e){return e?e.trim().startsWith(_i)?e:_i+"\n\n"+e:_i+"\n\n"}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"),Tt(),Tt(),Tt(),Tt(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Tt(),__name(formatPackage,"formatPackage"),Tt(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var ru="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:ru,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 D.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:ru});if(!E(e))return[];const t=await D.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:ru,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:ru});await D.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:ru,category:n.category}),s=e.dirname(o);await D.mkdir(s,{recursive:!0});const a=formatPackage({pkg:n});await D.writeFile(o,a,"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"),Tt(),Tt();var ou="local-project";function prefixHeaderIfNeeded(e){return!e||e.trim().startsWith(_i)?e:_i+"\n\n"+e}async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!E(n))return null;const r=migrateHeader({content:await D.readFile(n,"utf-8")}).split("\n"),o=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!o)return null;const s=r.slice(0,o.start),a=o.end<r.length-1?r.slice(o.end+1):[],i={before:s.join("\n").trim(),after:a.join("\n").trim()},c=[...s,...a].join("\n").trim();return""===c&&await D.rm(n,{force:!0}),""!==c&&await D.writeFile(n,c+"\n","utf-8"),i}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:ou}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:ou,category:n}),a=e.dirname(s);return E(a)&&await D.rm(a,{recursive:!0,force:!0}),o}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,o=formatPackage({pkg:t});if(r){let e=prefixHeaderIfNeeded(r.before);e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=o.trim()+t,void await D.writeFile(n,e.trim()+"\n","utf-8")}let s="";E(n)&&(s=await D.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await D.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:ou,category:n.category}),a=e.dirname(s);await D.mkdir(a,{recursive:!0});const i=formatPackage({pkg:n});await D.writeFile(s,i,"utf-8");const c=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=prefixHeaderIfNeeded(migrateHeader({content:o.before}));e=ensureTrailingNewlines(e);const t=o.after?"\n\n"+o.after:"";return e+=c.trim()+t,void await D.writeFile(r,e.trim()+"\n","utf-8")}let l="";E(r)&&(l=await D.readFile(r,"utf-8"),l=migrateHeader({content:l})),l=ensureHeader(l),l=ensureTrailingNewlines(l),l+=c,await D.writeFile(r,l.trim()+"\n","utf-8")}__name(prefixHeaderIfNeeded,"prefixHeaderIfNeeded"),__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var su="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:su,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:su});if(!E(e))return[];const t=[],n=getRootTasteFile({target:su});if(E(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await D.readdir(e,{withFileTypes:!0}),o=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...o),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:su});await D.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:su}),o=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:o}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:o})}function exists(){const e=getTastePath({target:su});return E(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!E(n))return;const r=await D.readFile(n,"utf-8"),o=new Blob([r],{type:"text/markdown"}),s=new File([o],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,s)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:o,type:s="category",isPublic:a=!1}=t,i=new FormData;i.append("name",n),o&&i.append("description",o),i.append("type",s),i.append("isPublic",String(a));const c=formatPackage({pkg:r}),l=new Blob([c],{type:"text/markdown"}),d=new File([l],"taste.md",{type:"text/markdown"});if(i.append("files[taste.md]",d),"category"===s)return i;const u=getTastePath({target:"local-project"}),m=e.join(u,r.category);if(!E(m))return i;const g=getCategoryTasteFile({target:"local-project",category:r.category});if(!E(g))return i;const p=await D.readFile(g,"utf-8"),h=new Blob([p],{type:"text/markdown"}),f=new File([h],"taste.md",{type:"text/markdown"});return i.append(`files[${r.category}/taste.md]`,f),i}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:o=!1}=e,s=new FormData;s.append("name",n),r&&s.append("description",r),s.append("type","project"),s.append("isPublic",String(o));const a=getRootTasteFile({target:"local-project"});if(E(a)){const e=await D.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",n)}const i=t.map(e=>appendCategoryFile(s,e));return await Promise.all(i),s}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:o,extra:s}=e,a=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:a,label:n}),context:{component:dr.TASTE_REMOTE_STORAGE,heading:r,"http.status":o,...s}}),a}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(),o=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(o)return o;const s=await getAuthKey();if(!s)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:s})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,o=`${t}${pt.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let s;try{s=await fetch(o,{method:"GET"})}catch{return null}if(s.ok){const{data:e}=await s.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===s.status)return null;throwTrackedError({message:await parseApiError({response:s,fallback:`Failed to download taste package (${s.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:s.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:o}=e,s=`${t}${pt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,a=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o}`}});if(a.ok){const{data:e}=await a.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===a.status)return null;throwTrackedError({message:await parseApiError({response:a,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:a.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:dr.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()}${pt.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(),o=r.packages||[];if(0===o.length)return[];const s=[];for(let e=0;e<o.length;e+=5){const t=o.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));s.push(...n.filter(e=>null!==e))}return s}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:dr.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 o=r.files||[];if(0===o.length)return null;const s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1}=e,o=await requireAuthKey(),s=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r}),a=`${getApiBaseUrl()}${pt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,i=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:s});i.ok||throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:i.status}),await i.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:o=!1}=e,s=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:o}),i=`${getApiBaseUrl()}${pt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,c=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:a});c.ok||throwTrackedError({message:await parseApiError({response:c,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:c.status,extra:{"package.count":t.length}}),await c.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${pt.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 D.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 be("list").alias("ls").option("-g, --global","List global packages").addOption(new Ce("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ce("--staging","Use staging environment").hideHelp()).description(`List available packages ${ee.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(exists,"exists"),Tt(),Tt(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),$t(),Tt(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),fr(),Tt(),fr(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Tt(),$t(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),bn(),__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 au={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?au.remote:e.global?au.global:au.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${Se.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${Se.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,o=r?`, updated ${r}`:"";return` ${ee.white(e.category)}${e.isPublic?ee.green(" [public]"):""}${e.isPublic&&e.starCount?ee.yellow(` ${Se.star}${e.starCount}`):""}${e.downloadCount?ee.gray(` ${Se.arrowDown}${e.downloadCount}`):""}${n}${ee.dim.gray(`(${e.learningCount} learnings${o})`)}`}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?Me(`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${tu} Packages`),console.log(`${ee.gray("⎿")} ${ee.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(ee.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(ee.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,o=await D.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const s=o.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return s>=0?s+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 o=r.sourcePath,s=await findCategoryLineNumber({filePath:o,category:t});return await Qe([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Tt(),Tt(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var iu=new Set(["local-project","local-global","remote-project","remote-user"]);async function open7(e){const{package:t,target:n}=e;if(!iu.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=tt.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 be("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 ${ee.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 oe(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ee.green(Se.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(`${ee.green(Se.tick)} Opened ${ee.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"),Tt(),Tt(),Tt(),Tt();var cu=null,lu=!1;function setActiveSpinner(e){cu=e}function stopActiveSpinner(e){cu&&(cu.stop(e),cu=null)}function setPrompted(e){lu=e}function wasPrompted(){return lu}function beginPrompt(e,t){stopActiveSpinner(),Pe.intro(ee.dim(e)),t&&Pe.log.message(ee.dim(t)),setPrompted(!0)}function handleCancel(e){Pe.isCancel(e)&&(Pe.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Pe.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Pe.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:o}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ee.green(`'${t}'`)} from ${n}`,s),Pe.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${ee.dim(`(from ${n})`)}`);const a=await Pe.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${r.learnings.length} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});handleCancel(a);const i=a;return startStrategySpinner(i),i}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e,o="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ee.green(`'${t}'`)} to global`,o),Pe.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await Pe.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(s);const a=s;return startStrategySpinner(a),a}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ee.green(`'${t}'`)} from global`,o),Pe.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await Pe.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(s);const a=s;return startStrategySpinner(a),a}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const a=et(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ee.green(`'${t}'`)} to ${n}`,s),Pe.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),Pe.log.info(`Current package: ${ee.cyan(a)} ${ee.dim("(review)")}`);const i=await Pe.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(i);const c=i;return startStrategySpinner(c),c}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Pe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const a=et(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ee.green(`'${t}'`)} to ${n}`,s),Pe.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),Pe.log.info(`Current package: ${ee.cyan(a)} ${ee.dim("(review)")}`);const i=await Pe.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${o} → ${r} learnings)`}],initialValue:"skip"});handleCancel(i);const c=i;return startStrategySpinner(c),c}function mergeSingleLearning(e,t,n,r){const o=t.get(e.text);return o?e.confidence>o.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},o=new Map(n.map(e=>[e.text,e])),s=new Map(o);for(const e of t)mergeSingleLearning(e,o,s,r);const a=new Set(t.map(e=>e.text)),i=n.filter(e=>!a.has(e.text)).length;return r.unchanged+=i,{merged:Array.from(s.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:o,owner:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:o.category,owner:s,localPkg:r,remoteLearningsCount:o.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:o,result:s}=e,a=await getPackage2({category:t.category}),i=await resolveRemotePullStrategy({flagStrategy:o,overwrite:r,existingPkg:a,tastePkg:t,owner:n});if("skip"===i)return void s.skipped?.push(t.category);if("overwrite"===i&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===i){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:a});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const c=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=c}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:o,flagStrategy:s,result:a}=e,i=t.find(e=>"taste.md"===e.file);if(i){const e=parsePackages({content:i.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:o,flagStrategy:s,result:a})}const c=t.filter(e=>"taste.md"!==e.file);for(const e of c){const t=e.file.replace("/taste.md",""),i={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:i,owner:r,overwrite:o,flagStrategy:s,result:a})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,result:a}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return a.success=!1,void a.errors.push({pkg:n,error:"No taste.md file found in category package"});const c={category:n,learnings:parseTasteContent(i.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:c,owner:r,overwrite:o,flagStrategy:s,result:a})}__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"),Tt(),Tt(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Tt(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var du=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),uu=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),mu=__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:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPullStrategy({packageName:s.category,localPkg:r,globalLearningsCount:s.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:o,result:s}=e,a=await getPackage2({category:t.category}),i=await resolvePullStrategy({flagStrategy:r,overwrite:o,existingPkg:a,source:n,tastePkg:t});if("skip"===i)return void s.skipped.push(t.category);if("overwrite"===i&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===i){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:a});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const c=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=c}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:o}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return du({pkg:"all",error:`Invalid source: ${n}`});const s=mu(n);let a;try{a="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return du({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===a.length)return du({pkg:"all",error:`No taste packages found in ${s}`});const i=validatePackages({packages:a,label:s});if(i.length>0)return{success:!1,packagesPulled:[],errors:[...i],mergeDetails:{},overwritten:[],filePaths:{}};const c=t.length>0?a.filter(e=>t.includes(e.category)):a;if(t.length>0&&0===c.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const l=uu();for(const e of c)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:o,overwrite:r,result:l});return l}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s}=e,a=await downloadPackage({owner:t,packageName:n});if(!a)return du({pkg:n,error:"Taste package not found in remote"});const{type:i,files:c}=a,l=validateRemoteFiles({files:c,packageName:n});if(l.length>0)return{success:!1,packagesPulled:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:c,packageName:n,owner:t,overwrite:r,flagStrategy:o,result:s};return"project"===i?(await pullProjectPackage(d),s):(await pullCategoryPackage(d),s)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:o}=e,s=uu();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return du({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Pe.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:o,mergeDetails:s}=e,a=wasPrompted()?"":`${Se.tick} `,i=r?ee.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${ee.green(a)}Replaced ${ee.green(`'${t}'`)} taste package in project`+i;if(s){const e=formatMergeParts(s);return`${ee.green(a)}Pulled ${ee.green(`'${t}'`)} taste package from ${n} ${ee.gray(`(${e.join(", ")})`)}`+i}return`${ee.green(a)}Pulled ${ee.green(`'${t}'`)} taste package from ${n}`+i}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const o=t.packagesPulled[0],s=t.filePaths?.[o],a=t.mergeDetails?.[o];return logResult(buildPullMessage({pkgName:o,sourceName:n,filePath:s,options:r,mergeDetails:a})),!r.overwrite&&!!a&&hasMergeConflictRisk(a)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],o=t.skipped??[],s=t.packagesPulled.filter(e=>!r.includes(e)),a=t.packagesPulled.length+o.length,i=`${a} ${1===a?"package":"packages"}`,c=[];return s.length>0&&c.push(wrapLine(`${ee.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&c.push(wrapLine(`${ee.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&c.push(wrapLine(`${ee.dim("Skipped")} (${o.length}) ${ee.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(c.length>0&&Pe.log.message(c.join("\n")),Pe.outro(`${i} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ee.green(Se.tick)} ${i} from ${n}`),c.length>0&&console.log(c.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,o=t.skipped??[];t.packagesPulled.length+o.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():o.length>0?logResult(ee.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new be("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 Ce("--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 Ce("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ee.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:o}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?o??"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 o=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:o}):pullGlobal({packageName:t,options:r,strategy:o})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,o=parseOwnerPackage(t);o||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner(Me("Pulling taste package").start());const s=await pullRemote({owner:o.owner,packageName:o.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s,owner:o.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner(Me("Pulling taste package").start());const o=n.all||!t?[]:[t],s=await pull({packages:o,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new _o({baseUrl:e}),n=await t.get({endpoint:pt.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 Pe.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()?"":`${Se.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ee.green(t)}Skipped ${n}`)}return!1}const o=n.packagesPushed.length,s=`${o} ${1===o?"package":"packages"}`,a=n.filePaths?.[n.packagesPushed[0]],i=r.global&&a?shortenPath(e.dirname(e.dirname(a))):a,c=wasPrompted()?"":`${Se.tick} `;if(!i)return logResult2(`${ee.green(c)}Pushed ${s} 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?` ${ee.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ee.green(c)}Replaced ${s} in ${i}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ee.green(c)}Pushed ${s} to ${i}`),!1;let l=0,d=0,u=0;for(const e of Object.values(n.mergeDetails))l+=e.added??0,d+=e.updated??0,u+=e.unchanged??0;const m=formatMergeParts({added:l,updated:d,unchanged:u}),g=m.length>0?` ${ee.gray(`(${m.join(", ")})`)}`:"";return logResult2(`${ee.green(c)}Pushed ${s} to ${i}${g}`),(l>0||d>0)&&u>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],o=t.filePaths?.[r],s=n.remote&&o,a=s?o:"global",i=wasPrompted()?"":`${Se.tick} `,c=!s&&o?ee.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${ee.green(i)}Replaced ${ee.green(`'${r}'`)} taste package in ${a}`+c),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ee.green(i)}Pushed ${ee.green(`'${r}'`)} taste package to ${a} ${ee.gray(`(${n.join(", ")})`)}`+c),hasMergeConflictRisk(e)}return logResult2(`${ee.green(i)}Pushed ${ee.green(`'${r}'`)} taste package to ${a}`+c),!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",o=wasPrompted()?"":`${Se.tick} `;return logResult2(wrapLine(`${ee.green(o)}Pushed ${ee.green(t.packagesPushed.length)} taste packages ${ee.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[o,s]=n.split("/");if(!o||!s)continue;const a=getPackageLink({owner:o,packageName:s});r.has(a)||(r.add(a),console.log(ee.gray(` ${a}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],o=t.packagesPushed.filter(e=>!n.includes(e)),s=t.packagesPushed.length+r.length,a=[];o.length>0&&a.push(wrapLine(`${ee.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&a.push(wrapLine(`${ee.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&a.push(wrapLine(`${ee.dim("Skipped")} (${r.length}) ${ee.dim(r.join(", "))}`,4)),a.length>0&&Pe.log.message(a.join("\n"));const i=`${s} ${1===s?"package":"packages"}`;Pe.outro(i)}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)),o=[];r.length>0&&o.push(wrapLine(`${ee.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${ee.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${ee.dim("Skipped")} (${n.length}) ${ee.dim(n.join(", "))}`)),o.length>0&&console.log(o.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"),Tt(),__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"),Tt(),bn(),Tt(),$t(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Tt(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Tt(),Tt();var gu=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),pu=__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:o,projectName:s,owner:a}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const i=r.type??"category",c=o.reduce((e,t)=>e+t.learnings.length,0),l=pu(r.files);return"project"!==i?promptTypeMismatchStrategy({packageName:s,owner:a,localLearningsCount:c,remoteLearningsCount:l}):promptSameTypeStrategy({packageName:s,owner:a,localLearningsCount:c,remoteLearningsCount:l})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,isPublicExplicitlySet:a,flagStrategy:i}=t,c=e.basename(process.cwd()),l={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:c});if("skip"===await resolvePushAllStrategy({flagStrategy:i,overwrite:o,existingProject:d,packagesToPush:n,projectName:c,owner:r}))return l.skipped.push(...n.map(e=>e.category)),l;await writePackages({packages:n,projectName:c,owner:r,isPublic:a?s:d?.isPublic??!1});for(const e of n)l.packagesPushed.push(e.category),l.filePaths[e.category]=`${r}/${c}`,l.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&l.overwritten.push(...n.map(e=>e.category)),l}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return gu({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var hu=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),fu=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:o}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:o})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var yu=__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:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPushStrategy({packageName:s.category,localLearningsCount:s.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:o,userOwner:s,isPublic:a,result:i}=e,c="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),l=await resolveSinglePushStrategy({flagStrategy:r,overwrite:o,existingPkg:c,target:n,tastePkg:t});if("skip"===l)return void i.skipped.push(t.category);if("overwrite"===l&&(await writePkg({pkg:t,target:n,owner:s,isPublic:a}),i.packagesPushed.push(t.category),i.overwritten.push(t.category),i.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===l){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:c});await writePkg({pkg:e,target:n,owner:s,isPublic:a}),i.packagesPushed.push(t.category),i.mergeDetails[t.category]=r}const d=yu({target:n,category:t.category,owner:s});d&&(i.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:o=!1,isPublic:s=!1,strategy:a}=e;if(!exists())return hu({pkg:"all",error:"No taste directory found in project"});const i=await getAllPackages2();if(0===i.length)return hu({pkg:"all",error:"No taste packages found in project"});const c=validatePackages({packages:i,label:"project"});if(c.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...c],mergeDetails:{},overwritten:[],filePaths:{}};const l=n.length>0?i.filter(e=>n.includes(e.category)):i;if(n.length>0&&0===l.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:l,owner:d,overwrite:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:a}):hu({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return hu({pkg:"all",error:`Invalid target: ${r}`});const u=fu();for(const e of l)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:a,overwrite:o,userOwner:d,isPublic:s,result:u});return u}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:o=!1,isPublic:s=!1,strategy:a}=e,i=await getPackage2({category:r});if(!i)return hu({pkg:r,error:`Taste package '${r}' not found in local project`});const c=validateTasteFile({content:formatPackage({pkg:i}),filePath:`${i.category}/taste.md`});if(!c.valid){const e=formatValidationIssues({result:c,verbose:!0});return hu({pkg:r,error:`Validation failed:\n${e}`})}c.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:c,verbose:!0})+"\n"));const l=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:a,overwrite:o,existingPkg:l,target:"remote-project",tastePkg:i}),u=t?s:l?.isPublic??!1,m=fu();if("skip"===d)return m.skipped.push(r),m;if("overwrite"===d&&(await writePackage3({pkg:i,owner:n,isPublic:u}),m.packagesPushed.push(r),m.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:i,existing:l});await writePackage3({pkg:e,owner:n,isPublic:u}),m.packagesPushed.push(r),m.mergeDetails[r]=t}return m.filePaths[r]=`${n}/${r}`,m}async function pushRemote(e){const{packageName:t}=e;if(!exists())return hu({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return hu({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"}))],o=await Pe.select({message:"Owner",options:r,initialValue:t});return Pe.isCancel(o)&&(Pe.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new be("push").description(`Push taste packages to remote ${ee.dim("(commandcode.ai)")} or global ${ee.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 Ce("--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 Ce("--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"),Tt(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var wu=__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};Pe.intro(ee.dim(`pushing ${t}`)),setPrompted(!0);const o=Pe.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),Pe.outro(ee.red(`Taste package '${t}' not found in project`)),process.exit(1));const s=await fetchUserNamespaces();return o.stop(s.orgs.length>0?"Select owner to push to":""),{owner:s.orgs.length>0?await promptOwnerSelection(s):s.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 o=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:o}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:o}):pushGlobal({packageName:t,options:r,strategy:o})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const o=(await getAllPackages2()).length,s=`${o} ${1===o?"package":"packages"}`,a=e.basename(process.cwd()),i=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(ee.dim(` Pushing ${s} to ${a} (remote)${i}`)),console.log(""),setActiveSpinner(Me("Pushing taste packages").start());const c=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:wu(n),strategy:r,owner:n.owner});return stopActiveSpinner(),c}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:o,packageName:s}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:o,pkgName:s});const a=await pushRemote({owner:o,packageName:s,overwrite:n.overwrite,isPublic:wu(n),strategy:r});return stopActiveSpinner(`Pushed to ${o}/${s}`),a}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=Pe.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Me("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,o=n.all||!t?[]:[t],s=await getAllPackages2(),a=o.length>0?o.length:s.length,i=`${a} ${1===a?"package":"packages"}`,c=shortenPath(getTastePath({target:"local-global"})),l=resolveStrategyLabel({strategy:r});console.log(ee.dim(` Pushing ${i} to ${c}${l}`)),console.log(""),setActiveSpinner(Me("Pushing taste packages").start());const d=await push({packages:o,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new be(Et.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?ne.bold(ne.green(t)):ne.white(t);return`${ne.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${ne.bold(ne.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(ne.dim(`Run ${ne.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(ne.dim("Try updating manually:")),console.log(ne.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(ne.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Me("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(`${ne.green(Se.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${ne.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Me("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} ${Se.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:dr.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 ${ne.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"),Tt(),$t(),fr(),__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 Eu=new be("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Tt();var Su=__name((e,t)=>`${Se.info} ${e}: ${ne.cyan(t)}`,"formatInfoLine"),ku=__name(e=>ne.bold(`${e}:`),"formatSectionHeader"),vu=__name(e=>ne.red(e),"formatError"),bu=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),Cu=__name(e=>["",ku("User Information"),Su("Name",e.name),Su("Email",e.email),Su("Username",e.userName)],"buildUserOutput"),Pu=__name(e=>["",ku("Organization"),Su("Name",e.name),Su("Login",e.login)],"buildOrgOutput"),Tu=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),Au=__name((e,t)=>{Tu(Cu(e)),t&&Tu(Pu(t)),console.log("")},"displayUserInfo"),xu=__name(e=>null!==e&&e.length>0,"validateApiKey"),Iu=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Me("Fetching user information...").start();try{const t=await getAuthKey();xu(t)||(e.fail(vu('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();Iu(n)||(e.fail(vu("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),Au(n.user,n.org)}catch(t){e.fail(vu(`Error: ${bu(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var $u=new be("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var Ru=createProgram();Ru.action(interactiveModeAction),Ru.addCommand(Vd),Ru.addCommand(Kd),Ru.addCommand($u),Ru.addCommand(Eu),Ru.addCommand(qd),Ru.addCommand(createTasteCommand()),Ru.addCommand(createMcpCommand()),Ru.addCommand(Jd),Ru.addCommand(eo),Ru.addCommand(so),Ru.addCommand(mo),setupCommanderHooks(Ru),Ru.parse();
|