command-code 0.12.0 → 0.13.0
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 +3 -3
- package/vsix/commandcode-vscode.vsix +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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 l}from"path";import{fileURLToPath as u,URL as d,pathToFileURL as m}from"url";import g,{z as p}from"zod";import*as h from"os";import f,{tmpdir as y}from"os";import*as w from"fs";import E,{existsSync as b,readFileSync as S,promises as v,constants as C,mkdirSync as k,writeFileSync as P,readdirSync as T,statSync as A,createReadStream as x}from"fs";import{spawn as I,execSync as _,exec as N,execFile as $}from"child_process";import*as R from"fs/promises";import D,{mkdir as O,writeFile as L,readFile as M,unlink as F}from"fs/promises";import*as U from"crypto";import j,{randomUUID as B}from"crypto";import q,{useState as z,useRef as W,useEffect as H,useCallback as V,useMemo as G}from"react";import{Box as K,Text as J,Static as Q,render as Y,useStdout as Z,useInput as X,useApp as ee}from"ink";import te from"chalk";import ne from"strip-ansi";import re from"picocolors";import oe from"sharp";import se from"open";import ae from"@opentelemetry/sdk-node";import ie from"@opentelemetry/exporter-trace-otlp-http";import ce from"@opentelemetry/resources";import le from"@opentelemetry/semantic-conventions";import ue from"@opentelemetry/sdk-trace-node";import{trace as de,SpanStatusCode as me,context as ge}from"@opentelemetry/api";import{v4 as pe}from"uuid";import*as he from"http";import*as fe from"net";import ye from"net";import{promisify as we}from"util";import"dotenv/config";import Ee from"dedent";import be from"log-symbols";import Se,{mainSymbols as ve}from"figures";import Ce from"readline/promises";import{Command as ke,Option as Pe}from"commander";import*as Te from"@clack/prompts";import{cancel as Ae,select as xe,isCancel as Ie,note as _e,confirm as Ne,password as $e}from"@clack/prompts";import Re from"ink-spinner";import De from"ora";import Oe from"@crosscopy/clipboard";import Le from"tls";import Me from"stream";import{performance as Fe}from"perf_hooks";import Ue from"gray-matter";import{EventEmitter as je}from"events";import Be from"@sindresorhus/slugify";import{minimatch as qe}from"minimatch";import{glob as ze}from"glob";import{quote as We}from"shell-quote";import{MessageStream as He}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import Ve from"strip-json-comments";import*as Ge from"readline";import Ke from"ink-select-input";import Je from"semver";import Qe from"ignore";import Ye from"ink-gradient";import{Marked as Ze}from"marked";import Xe from"marked-terminal";import*as et from"diff";import tt from"open-editor";import nt from"ink-text-input";import{wrapAnsi as rt}from"fast-wrap-ansi";import ot from"terminal-link";import*as st from"process";var at,it,ct,lt,ut,dt,mt,gt,pt,ht,ft,yt,wt,Et,bt,St,vt,Ct,kt,Pt,Tt,At,xt=Object.defineProperty,It=Object.getOwnPropertyNames,__name=(e,t)=>xt(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[It(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)xt(e,n,{get:t[n],enumerable:!0})},_t=__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"(){}}),Nt=__esm({"../shared/src/constants/tracing.ts"(){_t(),at="command_code_cli_tracing"}}),$t=__esm({"src/utils/telemetry/constants.ts"(){_t(),Nt(),it="https://api.axiom.co/v1/traces",ct="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",lt="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",ut="xaat-add69148-8f73-4833-921d-bc843285c95f",dt="command-code-cli",mt=["apikey","api_key","api-key","token","secret","authorization","auth","password","passwd","credential","auth_key","authkey","access_token","access-token","refresh_token","refresh-token","client_secret","clientsecret","private_key","privatekey","bearer","key"],gt=["content","body"],pt=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 Rt,Dt,Ot=__esm({"../shared/src/constants.ts"(){_t(),ft="--xco",yt={INTERNAL_TEAM_FLAG_HEADER:`x-${(ht="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage",CLI_ENVIRONMENT:"x-cli-environment"},wt={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"}}}},Et={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(Et.ALPHA.TASTE),Object.values(Et.BETA.TASTE_PACKAGES),wt.ALPHA.GENERATE,wt.ALPHA.AGENT.GENERATE,wt.ALPHA.WHOAMI,wt.ALPHA.NAMESPACES,wt.ALPHA.SHARE.CREATE,wt.ALPHA.SHARE.DELETE,wt.ALPHA.SHARE.APPEND,wt.ALPHA.DEVREL_THREAD.CREATE,wt.ALPHA.DEVREL_THREAD.DELETE,wt.ALPHA.DEVREL_THREAD.UPDATE,wt.ALPHA.TASTE.LEARN,wt.ALPHA.TASTE.DELETE,wt.ALPHA.TASTE.GET,wt.ALPHA.TASTE.UPDATE,Object.values(wt.BETA.TASTE.PACKAGES),wt.INTERNAL.ADMIN.USERS,wt.INTERNAL.ADMIN.ORGS,wt.INTERNAL.ADMIN.ENTITY_TYPE,wt.INTERNAL.USER.AVATAR,wt.INTERNAL.USER.SETTINGS,wt.INTERNAL.API_KEYS.LIST,wt.INTERNAL.API_KEYS.CREATE,wt.INTERNAL.API_KEYS.DELETE,wt.INTERNAL.USAGE.LIST,wt.INTERNAL.USAGE.SUMMARY,wt.INTERNAL.ADMIN.GRANT_CREDITS,wt.INTERNAL.ADMIN.GRANT_ORG_CREDITS,wt.INTERNAL.BILLING.CREDITS.GET,wt.INTERNAL.BILLING.CUSTOMERS.GET,wt.INTERNAL.BILLING.CUSTOMERS.UPSERT,wt.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,wt.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,wt.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,wt.INTERNAL.BILLING.CUSTOMERS.INVOICES,wt.INTERNAL.BILLING.SUBSCRIPTIONS.GET,wt.INTERNAL.ORGS.LIST,wt.INTERNAL.ORGS.GET,wt.INTERNAL.ORGS.CREATE,wt.INTERNAL.ORGS.UPDATE,wt.INTERNAL.ORGS.DELETE,wt.INTERNAL.ORGS.MEMBERS.LIST,wt.INTERNAL.ORGS.MEMBERS.ADD,wt.INTERNAL.ORGS.MEMBERS.UPDATE,wt.INTERNAL.ORGS.MEMBERS.REMOVE,wt.INTERNAL.ORGS.INVITATIONS.LIST,wt.INTERNAL.ORGS.INVITATIONS.SEND,wt.INTERNAL.ORGS.INVITATIONS.ACCEPT,wt.INTERNAL.ORGS.INVITATIONS.CANCEL,wt.INTERNAL.TASTE.PACKAGES.LIST,Object.values(Et.INTERNAL.ORGS),Object.values(Et.INTERNAL.USER),Object.values(Et.INTERNAL.TASTE.PACKAGES),bt={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(bt.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl"),St={ANTHROPIC:"anthropic"},vt="anthropic:claude-haiku-4-5-20251001",g.enum(["owner","admin","member"]),Ct={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,Pt=kt.SONNET_4_6.id,new Set([].map(e=>e.toLowerCase())),Tt=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],At={TIER_1_THRESHOLD:.5,TIER_2_THRESHOLD:.8,TIER_3_THRESHOLD:.9,TIER_1_KEEP_COUNT:20,TIER_2_KEEP_COUNT:10,KEEP_RECENT_TOKENS:3e4}}}),Lt=__esm({"src/utils/env.ts"(){_t(),Rt=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),Dt=__name(()=>{const e=Rt();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag")}});function getAuthDir(){return t.join(f.homedir(),".commandcode")}function getAuthFile(e){const n=e??Rt(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??Rt(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var Mt,Ft,Ut=__esm({"src/utils/auth/auth-paths.ts"(){_t(),Ot(),Lt(),__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 E.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(;!E.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=f.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(f.homedir(),n.slice(1))),t.isAbsolute(n)||(n=t.resolve(process.cwd(),n)),t.normalize(n)}function createSkippedResult(e){const{inputPath:t,absolutePath:n,code:r}=e,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=E.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{E.accessSync(n,E.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"}):Ft.some(e=>isPathInDirectory(o,e)||isPathInDirectory(e,o))?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_ADDED"}):(Ft.push(o),{status:"added",inputPath:e,absolutePath:o,displayPath:formatDirectoryForDisplay(o)})}function getAdditionalDirectories(){return[...Ft]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Ft.findIndex(e=>areSamePath(t,e));return-1!==n&&(Ft.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Ft.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t)}var jt=__esm({"src/utils/additional-dirs.ts"(){_t(),Mt=new Set(["/etc","/root","/proc","/sys","/dev",t.join(f.homedir(),".ssh"),t.join(f.homedir(),".gnupg"),t.join(f.homedir(),".aws")]),Ft=[],__name(normalizePathForComparison,"normalizePathForComparison"),__name(areSamePath,"areSamePath"),__name(getCanonicalPath,"getCanonicalPath"),__name(canonicalizeForLookup,"canonicalizeForLookup"),__name(formatDirectoryForDisplay,"formatDirectoryForDisplay"),__name(isPathInDirectory,"isPathInDirectory"),__name(findSensitiveDirectoryConflict,"findSensitiveDirectoryConflict"),__name(resolveDirectoryPath,"resolveDirectoryPath"),__name(createSkippedResult,"createSkippedResult"),__name(createErrorResult,"createErrorResult"),__name(addDirectory,"addDirectory"),__name(getAdditionalDirectories,"getAdditionalDirectories"),__name(removeAdditionalDirectory,"removeAdditionalDirectory"),__name(isPathInAdditionalDirs,"isPathInAdditionalDirs"),__name(isPathInWorkspace,"isPathInWorkspace")}});function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${f.platform()}-${f.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return E.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 _("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return _("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){try{const e=_("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=_("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=_("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository(),t=getAdditionalDirectories();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getAccessibleDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[],...t.length>0?{additionalDirectories:t}:{}}}function detectTerminal(){const e=process.env;if(e.TERM_PROGRAM){const t=e.TERM_PROGRAM;if("vscode"===t)return{name:"Visual Studio Code",type:"vscode",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("iTerm.app"===t)return{name:"iTerm2",type:"iterm2",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION,iterm2Profile:e.ITERM_PROFILE}};if("Apple_Terminal"===t)return{name:"macOS Terminal",type:"terminal",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("WarpTerminal"===t)return{name:"Warp",type:"warp",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("Hyper"===t)return{name:"Hyper",type:"hyper",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("ghostty"===t)return{name:"Ghostty",type:"ghostty",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}}}if(e.WT_SESSION||e.WT_PROFILE_ID)return{name:"Windows Terminal",type:"windows-terminal",details:{wtSession:e.WT_SESSION,wtProfileId:e.WT_PROFILE_ID}};if(e.ALACRITTY_SOCKET||e.ALACRITTY_WINDOW_ID)return{name:"Alacritty",type:"alacritty",details:{alacrittySocket:e.ALACRITTY_SOCKET,alacrittyWindowId:e.ALACRITTY_WINDOW_ID}};if(e.KITTY_WINDOW_ID||e.KITTY_PID)return{name:"Kitty",type:"kitty",details:{kittyWindowId:e.KITTY_WINDOW_ID,kittyPid:e.KITTY_PID}};if(e.GNOME_TERMINAL_SERVICE||e.VTE_VERSION)return{name:"GNOME Terminal",type:"gnome-terminal",details:{gnomeTerminalService:e.GNOME_TERMINAL_SERVICE,vteVersion:e.VTE_VERSION}};if(e.KONSOLE_VERSION||e.KONSOLE_PROFILE_NAME)return{name:"Konsole",type:"konsole",details:{konsoleVersion:e.KONSOLE_VERSION,konsoleProfile:e.KONSOLE_PROFILE_NAME}};if(e.TMUX)return{name:"tmux",type:"tmux",details:{tmux:e.TMUX,tmuxPane:e.TMUX_PANE}};if(e.ConEmuPID||e.ConEmuBuild)return{name:"ConEmu",type:"conemu",details:{conEmuPid:e.ConEmuPID,conEmuBuild:e.ConEmuBuild}};if(e.SSH_CLIENT||e.SSH_TTY)return{name:"SSH",type:"ssh",details:{sshClient:e.SSH_CLIENT,sshTty:e.SSH_TTY}};if(e.CI){const t=e.GITHUB_ACTIONS?"GitHub Actions":e.GITLAB_CI?"GitLab CI":e.JENKINS_URL?"Jenkins":e.CIRCLECI?"CircleCI":"Unknown CI";return{name:t,type:"ci",details:{ci:e.CI,ciName:t}}}const t=e.TERM||"unknown";return{name:`Unknown Terminal (${t})`,type:"unknown",details:{term:t,colorterm:e.COLORTERM,shell:e.SHELL}}}function getIsTerminalIterm2(){return"iTerm2"===detectTerminal().name}var Bt,qt,zt,Wt,Ht,Vt,Gt,Kt,Jt,Qt,Yt,Zt=__esm({"src/utils/environment.ts"(){_t(),jt(),__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(getAccessibleDirectoryStructure,"getAccessibleDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext"),__name(detectTerminal,"detectTerminal"),__name(getIsTerminalIterm2,"getIsTerminalIterm2")}});function isWordLeftSequence(e){return!!Bt.has(e)||!!Qt.test(e)}function isWordRightSequence(e){return!!qt.has(e)||!!Yt.test(e)}function isHomeSequence(e){return zt.has(e)}function isEndSequence(e){return Wt.has(e)}function isForwardDeleteSequence(e){return Ht.has(e)}function isDeleteWordSequence(e){return Vt.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===Gt.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===Gt.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===Gt.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===Gt.CTRL_U}function isAltP(e){return Jt.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 Xt,en,tn,nn,rn,on,sn=__esm({"src/utils/keyboard-sequences.ts"(){_t(),Bt=new Set(["[1;3D","b","[1;5D","[1;9D","[5D"]),qt=new Set(["[1;3C","f","[1;5C","[1;9C","[5C"]),zt=new Set(["[H","[1~","[7~","OH"]),Wt=new Set(["[F","[4~","[8~","OF"]),Ht=new Set(["[3~"]),Vt=new Set(["",""]),Gt={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},Kt={ALT_P:112,ALT_P_NO_META:960},Jt=new Set([String.fromCharCode(27,Kt.ALT_P),String.fromCharCode(Kt.ALT_P_NO_META),"[112;3u"]),Qt=/^\x1b\[1;[359]D$/,Yt=/^\x1b\[1;[359]C$/,__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(isAltP,"isAltP"),__name(isCtrlKey,"isCtrlKey")}}),an=__esm({"src/auth/index.ts"(){_t(),Ot(),Lt(),(e=>{e.OAuth=p.object({type:p.literal("oauth"),refresh:p.string(),access:p.string(),expires:p.number()}),e.ApiKey=p.object({type:p.literal("api"),key:p.string()}),e.Info=p.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const n=__name(()=>t.join(f.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=Rt(),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 D.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await D.mkdir(o,{recursive:!0});let a={};try{const e=await D.readFile(s,"utf-8");a=JSON.parse(e)}catch{}a[e]=t,await D.writeFile(s,JSON.stringify(a,null,2)),await D.chmod(s,384)}async function remove(e){const t=r();try{const n=await D.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await D.unlink(t):(await D.writeFile(t,JSON.stringify(r,null,2)),await D.chmod(t,384))}catch{}}async function list2(){try{const e=await D.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")})(Xt||(Xt={}))}}),cn=__esm({"src/utils/constants.ts"(){_t(),Ot(),en="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing",tn='OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.',nn=">"}}),ln=__esm({"src/auth/anthropic.ts"(){_t(),an(),cn(),Sr(),(e=>{const t="9d1c250a-e61b-44d9-88ed-5944d1962f5e",n="https://console.anthropic.com/v1/oauth/token",r="https://console.anthropic.com/oauth/code/callback";function generateCodeVerifier(){return j.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return j.createHash("sha256").update(e).digest("base64url")}function generateState(){return j.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),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:hr.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const i=await a.json();await Xt.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 Xt.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:hr.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await Xt.remove("anthropic");const o=await r.json();return await Xt.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:hr.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await Xt.remove("anthropic")}}}async function getValidAccessToken2(){const e=await Xt.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")})(rn||(rn={}))}});function isWordBoundary(e){return!e||0===e.length||on.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 un=__esm({"src/utils/text-navigation.ts"(){_t(),on=/\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 dn,mn,gn,pn=__esm({"src/components/text/input-handlers.ts"(){_t(),un(),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(){dn||(dn=!0,mn=[],gn=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&mn.push(t)},"earlyInputHandler"),process.stdin.on("data",gn))}function stopEarlyInputCapture(){dn&&gn&&(process.stdin.off("data",gn),gn=null,dn=!1)}function consumeBufferedInput(){const e=mn.join("");return mn=[],e}function hasBufferedInput(){return mn.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("[I")||e.startsWith("[O"))}var hn=__esm({"src/utils/early-input-buffer.ts"(){_t(),dn=!1,mn=[],gn=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 l=(e||"").length,u=(i||"").length;(Math.abs(l-u)>1||r>l)&&(o(l),s.current=l)},[e,t,n,r]);const i=V(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}){X((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void a?.(n.current);const l=processInkInput(e,i,n.current,r.current,t);if(!l.handled)return;const u=clampCursor(l.cursor,l.value.length);s(l.value,u)},{isActive:e})}function useSyncedRef(e){const t=W(e);return H(()=>{t.current=e},[e]),t}var fn=__esm({"src/components/text/hooks.ts"(){_t(),un(),pn(),hn(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef")}});function renderPlaceholder(e,t){return t?0===e.length?te.inverse(" "):te.inverse(e[0])+te.grey(e.slice(1)):te.grey(e)}function renderValue(e,t,n){if(!n)return e;if(0===e.length)return te.inverse(" ");let r="";for(let n=0;n<e.length;n++)n===t?"\n"===e[n]?r+=te.inverse(" ")+"\n":r+=te.inverse(e[n]):r+=e[n];return t===e.length&&(r+=te.inverse(" ")),r}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(ne(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",l=0,u=!0;for(const e of a){const t=ne(e).length;if(l+t>(u?s:o)&&l>0&&(i+="\n"+r,l=n,u=!1),i+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=ne(t).length,u=!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 yn=__esm({"src/components/text/render-utils.ts"(){_t(),__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:l="",prefixColor:u}){const d=W(!1),m=useSyncedRef(e),g=useSyncedRef(s),{cursor:p,setCursor:h,cursorRef:f}=useCursorState({value:e,focus:n,showCursor:o});q.useEffect(()=>{i?.(p)},[p,i]);const y=V(createStdinUpdateHandler(h,m,g),[h,m,g]),w=V(()=>createInkUpdateHandler(h,m,s),[h,m,s])(),E=V(e=>{d.current=e},[]),b=V(()=>d.current,[]);useRawStdinHandler({focus:n,valueRef:m,cursorRef:f,onUpdate:y,setHandled:E}),useInkInputHandler({focus:n,showCursor:o,valueRef:m,cursorRef:f,isHandledByStdin:b,onUpdate:w,onSubmit:a});const{stdout:S}=Z(),v=S?.columns??80,C=getMaskedValue(e,r),k=wrapWithIndent(__name(()=>{if(!l)return"";if(!u)return l;const e={white:re.white,green:re.green,red:re.red,blue:re.blue,yellow:re.yellow,cyan:re.cyan,magenta:re.magenta,gray:re.gray,grey:re.gray}[u];return e?e(l):l},"getColoredPrefix")()+getDisplayValue(C,t,p,o,n),v,l?.length??0);return q.createElement(J,{wrap:"wrap"},k)}var wn=__esm({"src/components/text/text-input.tsx"(){_t(),fn(),yn(),un(),__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=oe(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,l,{width:u,height:d}=s;(u>a||d>a)&&(u>d?(d=Math.round(d*a/u),u=a):(u=Math.round(u*a/d),d=a)),t.includes("png")&&s.hasAlpha?(i=await o.resize(u,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),l="image/png"):(i=await o.resize(u,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),l="image/jpeg");const m=i.length;return{compressedBase64:i.toString("base64"),mediaType:l,originalSizeBytes:r,compressedSizeBytes:m,compressionRatio:r/m}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}var En,bn=__esm({"src/utils/image-compression.ts"(){_t(),__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=En[n];if(!r)return null;const o=a(t);if(!b(o))return null;const s=S(o).toString("base64");if(!s||0===s.length)return null;if(s.length>32e6)return null;const l=await compressImageForSharing(s,r);return l?{data:l.compressedBase64,mediaType:l.mediaType}:null}catch(e){return null}}async function detectClipboardImage(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasImage())return null;let t=null;try{if(t=await e.default.getImageBase64(),!t){const n=e.default.getImageBase64();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}if(!t||0===t.length)return null;if(t.length>32e6)return console.log("Image too large:",t.length,"bytes"),null;try{const e=await compressImageForSharing(t,"image/png");return e?{data:e.compressedBase64,mediaType:e.mediaType}:(console.log("Failed to compress clipboard image"),null)}catch(e){return console.log("Failed to process clipboard image:",e),null}}catch(e){return null}}async function detectClipboardText(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasText())return null;let t=null;try{if(t=await e.default.getText(),!t){const n=e.default.getText();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}return t&&0!==t.length?t:null}catch(e){return null}}var Sn=__esm({"src/utils/clipboard-image.ts"(){_t(),bn(),En={".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 vn,Cn,kn,Pn,Tn=__esm({"src/utils/bracketed-paste.ts"(){_t(),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode")}});function getIcon(e){if(kn[e])return kn[e];const t=e.split(":")[0];return kn[t]?kn[t]:kn.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(!Pn){Pn=!0;try{w.mkdirSync(vn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${Cn}\n════════════════════════════════════════════════════════════════\n\n`;w.appendFileSync(Cn,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} ${kn.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",w.appendFileSync(Cn,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`;w.appendFileSync(Cn,t,"utf-8")}catch{}}}var An,xn=__esm({"src/utils/dlog.ts"(){_t(),vn=e.join(h.homedir(),".commandcode","logs"),Cn=e.join(vn,"command.log"),kn={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"),Pn=!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 R.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();w.writeFileSync(t,JSON.stringify(e,null,2)),w.chmodSync(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t=await loadUserConfig(),n=getConfiguredModel(),r={...t,...e,model:e.model??n};await saveUserConfig(r)}async function isTasteLearningEnabled(){return(await loadUserConfig()).tasteLearning??!0}async function setTasteLearning(e){const{tasteLearning:t}=e;await updateUserConfig({tasteLearning:t})}async function isOAuthEnforced(){if(null!==An)return An;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),An=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),An=!0,!0;const e=await loadUserConfig();return(An=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),An}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error(tn)}function getConfiguredModel(){try{const e=getConfigFile();return(parseJSON(w.readFileSync(e,"utf-8"))||{}).model??Pt}catch{return Pt}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}var In,_n,Nn=__esm({"src/utils/user-config.ts"(){_t(),Ot(),Ut(),cn(),xn(),Rn(),Dn(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),An=null,__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel")}}),$n=__esm({"src/components/anthropic-auth.tsx"(){_t(),wn(),ln(),cn(),Sn(),Tn(),Nn(),In=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=z(""),[s,a]=z(null),[i,l]=z(!1),[u,d]=z(null),[m,g]=z(!0),[p,h]=z(!1),[f,y]=z(!1);H(()=>{const{url:e,verifier:t,state:n}=rn.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const w=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||f){if(!f||t.isPasteEnd){if(f&&t.isPasteEnd){y(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}o(e)}}else if(y(!0),t.isPasteEnd){y(!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}},[f]);X((e,n)=>{if(n.escape&&t(),m&&!p)if("y"!==e&&"Y"!==e)"n"!==e&&"N"!==e||t();else{if(!s)return;se(s.url).then(()=>{h(!0),g(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),h(!0),g(!1)})}});const E=__name(async()=>{if(r.trim()&&s&&!i){l(!0),d(null);try{const t=r.split("#")[0].trim();await rn.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),l(!1),n&&n(t)}}},"handleSubmit");return m&&!p?q.createElement(K,{flexDirection:"column"},q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,color:"cyan"},"Anthropic Authentication")),q.createElement(K,{marginBottom:1},q.createElement(J,null,"Open the Anthropic auth page?",q.createElement(J,{dimColor:!0}," (Y/n)")))):q.createElement(K,{flexDirection:"column"},q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,color:"cyan"},"Anthropic Authentication")),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"After authorizing, copy the code and paste it below:")),u&&q.createElement(K,{marginBottom:1},q.createElement(J,{color:"red"},"Error: ",u)),q.createElement(K,null,q.createElement(J,null,"Authorization code: "),q.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:w,onSubmit:E,placeholder:"Paste code here..."})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function getProviderDisplayName(e){if(!e)return"None";const t=_n[e];return t?.displayName||e}function getProviderConfig(e){return _n[e]}function isInternalTeamFlagPresent(){return process.argv.includes(ht)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(ft)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(w.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(_n).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var Rn=__esm({"src/utils/provider-config.ts"(){_t(),Ot(),ln(),$n(),Ut(),Dn(),_n={"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:In,checkAuth:__name(async()=>!!await rn.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(ft)}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 D.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 Dn=__esm({"src/utils/utils.ts"(){_t(),Ot(),Ut(),Zt(),sn(),Rn(),Nn(),__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=E.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var On=__esm({"src/utils/is-local-dev.ts"(){_t(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":Rt()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return lt;case"local":return ut;default:return ct}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(w.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var Ln=__esm({"src/utils/telemetry/config.ts"(){_t(),Ut(),Dn(),Lt(),On(),$t(),$t(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}}),Mn={};function getPackageJson(){const e=import.meta.url,t=u(e),o=r(t);return JSON.parse(S(n(o,"./../package.json"),"utf8"))}__export(Mn,{getPackageJson:()=>getPackageJson});var Fn,Un,jn,Bn,qn,zn,Wn=__esm({"src/utils/package.ts"(){_t(),__name(getPackageJson,"getPackageJson")}});function createAxiomExporter(){return new Un({url:it,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":at}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return jn({[Bn]:dt,[qn]: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 Fn({resource:t,spanProcessors:[new zn(e)],autoDetectResources:!1})}var Hn,Vn,Gn,Kn,Jn,Qn=__esm({"src/utils/telemetry/sdk-factory.ts"(){_t(),$t(),Ln(),Wn(),({NodeSDK:Fn}=ae),({OTLPTraceExporter:Un}=ie),({resourceFromAttributes:jn}=ce),({ATTR_SERVICE_NAME:Bn,ATTR_SERVICE_VERSION:qn}=le),({SimpleSpanProcessor:zn}=ue),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function generateSessionId(){return`sess_${pe().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return U.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":`${h.platform()}-${h.arch()}`,"session.node_version":process.version}}function startSession(){Jn={},Vn=null,Gn=null,Hn=generateSessionId(),Kn=Date.now();try{const e=de.getTracer(dt),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:Hn,projectPath:n,gitBranch:r,cliVersion:t});Vn=e.startSpan("session:cli",{attributes:o}),Gn=Vn.spanContext(),Vn.end()}catch{Vn=null,Gn=null}return Hn}function getTraceId(){return Gn?Gn.traceId:null}function getSessionContext(){return Gn?de.setSpanContext(ge.active(),Gn):ge.active()}function endSession(e={}){const{status:t="success"}=e;if(Gn&&Kn){const e=de.getTracer(dt),n=Date.now()-Kn,r=de.setSpanContext(ge.active(),Gn),o=e.startSpan("session:end",{attributes:{"session.id":Hn||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Jn}},r);"error"===t?o.setStatus({code:me.ERROR}):o.setStatus({code:me.OK}),o.end()}Vn=null,Gn=null,Hn=null,Kn=null,Jn={}}var Yn=__esm({"src/utils/telemetry/session.ts"(){_t(),$t(),Wn(),Zt(),Hn=null,Vn=null,Gn=null,Kn=null,Jn={},__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:me.ERROR}):e.setStatus({code:me.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=de.getTracer(dt),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:me.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 Zn,Xn,er,tr,nr,rr,or,sr,ar,ir,cr,lr,ur,dr,mr=__esm({"src/utils/telemetry/spans.ts"(){_t(),$t(),Yn(),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});function getEffectiveWidth({padding:e=tr}={}){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<=nr)return t;if(t.includes(" && ")){const e=t.split(" && ")[0].trim();return e.length<=nr-5?`${e} && ...`:truncateString({text:e,maxChars:nr})}return truncateString({text:t,maxChars:nr})}function truncateToVisualLines({output:e,maxVisualLines:t=Zn,padding:n=tr,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,l=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)){l=Math.max(1,e);break}i+=r}const u=l<a.length,d=a.slice(l).reduce((e,t)=>e+Math.max(1,Math.ceil(t.length/o)),0),m=a.slice(0,l).join("\n");return m.length>s?{text:`${m.slice(0,s-3)}...`,isTruncated:!0,remainingLines:d}:{text:m,isTruncated:u,remainingLines:d}}var gr=__esm({"src/utils/truncation.ts"(){_t(),Zn=2,Xn=10,er=10,tr=4,nr=100,rr=100,or=50,sr=100,ar=60,ir=80,cr=1e5,lr=5e4,ur=25e3,dr=200,__name(getEffectiveWidth,"getEffectiveWidth"),__name(truncateString,"truncateString"),__name(truncateCommand,"truncateCommand"),__name(truncateToVisualLines,"truncateToVisualLines")}});function isSecretKey(e){const t=e.toLowerCase();return mt.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return gt.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString2(e){return e.length<=dr?e:`${e.substring(0,dr-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>dr?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 pr=__esm({"src/utils/telemetry/sanitization.ts"(){_t(),$t(),gr(),__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,pt))}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,l={"error.type":r.name,"error.message":r.message,"error.component":o,"error.heading":s};void 0!==a&&(l["error.code"]=String(a));for(const[e,t]of Object.entries(i))null!=t&&(l[e]="object"==typeof t?safeStringify(t):String(t));const u=createSpan({name:`error:${r.name}`,attributes:l});recordError({span:u,error:r}),u.end()}function trackAPICallStart(e){const{method:t,endpoint:n}=e,r=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${r}`,attributes:{"http.method":t,"http.url":r}}),startTime:Date.now(),durationAttr:"http.duration_ms",statusAttr:"http.status"})}function getSupportId(){const e=getTraceId();return e?`req_${e}`:"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,nodeVersion:s,platform:a,arch:i}=e,l={"whoami.node_version":s,"whoami.platform":a,"whoami.arch":i,"whoami.os":`${a}-${i}`};t&&(l["whoami.user_name"]=t),n&&(l["whoami.user_id"]=n),r&&(l["whoami.org_login"]=r),o&&(l["whoami.org_id"]=o),endSpan({span:createSpan({name:"whoami",attributes:l}),status:"success"})}var hr,fr,yr,wr=__esm({"src/utils/telemetry/events.ts"(){_t(),mr(),Yn(),$t(),pr(),pr(),__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"(){_t(),hr={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(yr)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(fr=createTelemetrySDK()).start(),yr=!0,!0}catch{return fr=null,yr=!1,!1}}async function shutdownTelemetry(){if(fr&&yr)try{endSession(),await fr.shutdown()}catch{}finally{fr=null,yr=!1}}function shutdownTelemetrySync(){if(yr)try{endSession()}catch{}}function isTelemetryInitialized(){return yr}var br,Sr=__esm({"src/utils/telemetry/telemetry.ts"(){_t(),Qn(),Ln(),Yn(),mr(),wr(),Er(),fr=null,yr=!1,__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized")}});function getTokenFilePath(){return e.join(f.homedir(),".commandcode",br)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await R.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 R.mkdir(r,{recursive:!0}),await R.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await R.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 vr,Cr=__esm({"src/mcp/auth/token-storage.ts"(){_t(),Ot(),xn(),br="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(),vr);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var kr,Pr,Tr=__esm({"src/mcp/fetch.ts"(){_t(),vr=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),Ar={};function generateRandomString(e){return U.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:U.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=he.createServer((n,r)=>{const a=new d(n.url||"/",`http://${Pr}:${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,Pr,()=>{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||kr,o=n?.timeout||12e4,s=n?.onStatus||(()=>{});let a=null;try{const n=generatePKCE(),i=generateRandomString(32),l=`http://${Pr}:${r}/callback`;s("Starting authentication server...");const{server:u,getCode:m}=await startCallbackServer(r,i);a=u;const g=new d(t.authorizationUrl);if(g.searchParams.set("response_type","code"),g.searchParams.set("client_id",t.clientId),g.searchParams.set("redirect_uri",l),g.searchParams.set("state",i),g.searchParams.set("code_challenge",n.challenge),g.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&g.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))g.searchParams.set(e,n);s("Opening browser for authentication..."),await se(g.toString()),s("Waiting for authorization...");const p=m();let h;const f=new Promise((e,t)=>{h=setTimeout(()=>t(new Error("Authentication timed out")),o)}),y=await Promise.race([p,f]);clearTimeout(h),s("Exchanging authorization code for tokens...");const w=await exchangeCodeForTokens(t,y,n.verifier,l);return await storeTokens(e,w),s("Authentication successful!"),{success:!0,tokens:w}}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(Ar,{DEFAULT_OAUTH_CALLBACK_PORT:()=>kr,LOCALHOST_IP:()=>Pr,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var xr,Ir,_r,Nr,$r,Rr,Dr,Or,Lr,Mr,Fr,Ur,jr,Br,qr,zr=__esm({"src/mcp/auth/oauth-flow.ts"(){_t(),Cr(),Tr(),kr=8085,Pr="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")}}),Wr=__esm({"src/components/vscode-context/ipc-client.ts"(){_t(),xn(),xr=t.join(f.homedir(),".commandcode","ide"),Ir=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),_r=__name(e=>{if("win32"===process.platform)return null;try{const t=_(`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"),Nr=__name((e,t,n=_r)=>{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"),$r=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),Rr=__name((e,n)=>{try{E.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{E.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),Dr=__name((e,n={})=>{const{sessionDir:r=xr,parentPidFn:o=_r,startPid:s=process.ppid}=n;try{if(!E.existsSync(r))return null;const n=`${e}-`,a=E.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(E.readFileSync(n,"utf-8"));if(!Ir(o.pid)){Rr(n,r);continue}i.push({session:o,file:e})}catch{continue}if(0===i.length)return null;const l=Nr(i,s,o);if(l)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:l.session.socketPath,ideName:l.session.ideName}),l.session.socketPath;const u=process.cwd();let d=null,m=0;for(const{session:e}of i)for(const n of e.workspaceFolders)(u===n||u.startsWith(n+t.sep))&&n.length>m&&(d=e,m=n.length);return d&&dlog("[VSCode:IPC] Discovered session via workspace match",{socketPath:d.socketPath,ideName:d.ideName}),d?.socketPath??null}catch{return null}},"discoverSocketPath"),Or=__name(()=>{const e=$r();return e?Dr(e):null},"resolveSocketPath"),Lr=__name(()=>({type:"request",id:B(),payload:{action:"getContext"}}),"createContextRequest"),Mr=__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"),Fr=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!Mr(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"),Ur=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??Or()}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=ye.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=Lr();return dlog("[VSCode:IPC] Requesting context",{requestId:n.id}),await new Promise(r=>{const o=__name(()=>{t.off("data",i),t.off("error",l)},"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),l=Fr(Buffer.from(i),n.id);l?dlog("[VSCode:IPC] Context received",{hasActiveFile:!!l.activeFile,hasSelection:!!l.selection,openFilesCount:l.openFiles.length}):dlog("[VSCode:IPC] Invalid response received"),r(l)}catch(e){clearTimeout(s),o(),dlog("[VSCode:IPC] Error processing response",{error:e}),r(null)}},"handleData"),l=__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",l);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}}}}}),Hr={};function getVsixPath(){try{const e=t.dirname(u(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return E.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),Ur.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await jr(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp(`${Br}@([\\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 jr(`${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=$r();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:te.green("✔"),installed:te.green("✔"),needs_reload:te.yellow("◌"),failed:te.red("✖"),not_in_ide:te.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=>te.dim(` ${e}`)),""]}async function runIDESetup(){const e=$r(),t=e?qr[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new Ur,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(Hr,{detectIDE:()=>$r,ensureExtensionInstalled:()=>ensureExtensionInstalled,formatSetupResult:()=>formatSetupResult,getExtensionStatus:()=>getExtensionStatus,installExtension:()=>installExtension,installExtensionAsync:()=>installExtensionAsync,isAutoInstallEnabled:()=>isAutoInstallEnabled,runIDESetup:()=>runIDESetup});var Vr=__esm({"src/utils/ide-installer.ts"(){_t(),Wr(),xn(),Nn(),jr=we(N),Br="commandcode.commandcode-vscode",__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled"),qr={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"},__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup")}});_t(),_t();var Gr=process.argv.includes("-d")||process.argv.includes("--debug");Gr&&(process.env.DEBUG="true"),Gr||(process.removeAllListeners("warning"),process.on("warning",()=>{})),_t(),_t(),Sr();var{red:Kr,yellow:Jr,dim:Qr}=te,Yr=__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:hr.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${be.error} ${Kr(t)}`),console.log(`${be.error} ${Kr("ERROR →")} ${n.name}`),console.log(`${be.info} ${Kr("REASON →")} ${n.message}`),console.log(`${be.info} ${Kr("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${be.info} ${Qr(`Request ID: ${e}`)}`),console.log(`${Qr(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${be.warning} ${Jr(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:hr.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),Yr({heading:Ee`CRITICAL: Unhandled Promise Rejection!
|
|
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 l}from"path";import{fileURLToPath as u,URL as d,pathToFileURL as m}from"url";import g,{z as p}from"zod";import*as h from"os";import f,{tmpdir as y}from"os";import*as w from"fs";import E,{existsSync as b,readFileSync as S,promises as v,constants as C,mkdirSync as k,writeFileSync as P,readdirSync as T,statSync as A,createReadStream as x}from"fs";import{spawn as I,execSync as _,exec as N,execFile as $}from"child_process";import*as R from"fs/promises";import D,{mkdir as O,writeFile as L,readFile as M,unlink as F}from"fs/promises";import*as U from"crypto";import j,{randomUUID as B}from"crypto";import q,{useState as z,useRef as W,useEffect as H,useCallback as V,useMemo as G}from"react";import{Box as K,Text as J,Static as Q,render as Y,useStdout as Z,useInput as X,useApp as ee}from"ink";import te from"chalk";import ne from"strip-ansi";import re from"picocolors";import oe from"sharp";import se from"open";import ae from"@opentelemetry/sdk-node";import ie from"@opentelemetry/exporter-trace-otlp-http";import ce from"@opentelemetry/resources";import le from"@opentelemetry/semantic-conventions";import ue from"@opentelemetry/sdk-trace-node";import{trace as de,SpanStatusCode as me,context as ge}from"@opentelemetry/api";import{v4 as pe}from"uuid";import*as he from"http";import*as fe from"net";import ye from"net";import{promisify as we}from"util";import"dotenv/config";import Ee from"dedent";import be from"log-symbols";import Se,{mainSymbols as ve}from"figures";import Ce from"readline/promises";import{Command as ke,Option as Pe}from"commander";import*as Te from"@clack/prompts";import{cancel as Ae,select as xe,isCancel as Ie,note as _e,confirm as Ne,password as $e}from"@clack/prompts";import Re from"ink-spinner";import De from"ora";import Oe from"@crosscopy/clipboard";import Le from"tls";import Me from"stream";import{performance as Fe}from"perf_hooks";import Ue from"gray-matter";import{EventEmitter as je}from"events";import Be from"@sindresorhus/slugify";import{minimatch as qe}from"minimatch";import{glob as ze}from"glob";import{quote as We}from"shell-quote";import{MessageStream as He}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import Ve from"strip-json-comments";import*as Ge from"readline";import Ke from"ink-select-input";import Je from"semver";import Qe from"ignore";import Ye from"ink-gradient";import{Marked as Ze}from"marked";import Xe from"marked-terminal";import*as et from"diff";import tt from"open-editor";import nt from"ink-text-input";import{wrapAnsi as rt}from"fast-wrap-ansi";import ot from"terminal-link";import*as st from"process";var at,it,ct,lt,ut,dt,mt,gt,pt,ht,ft,yt,wt,Et,bt,St,vt,Ct,kt,Pt,Tt,At,xt=Object.defineProperty,It=Object.getOwnPropertyNames,__name=(e,t)=>xt(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[It(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)xt(e,n,{get:t[n],enumerable:!0})},_t=__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"(){}}),Nt=__esm({"../shared/src/constants/tracing.ts"(){_t(),at="command_code_cli_tracing"}}),$t=__esm({"src/utils/telemetry/constants.ts"(){_t(),Nt(),it="https://api.axiom.co/v1/traces",ct="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",lt="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",ut="xaat-add69148-8f73-4833-921d-bc843285c95f",dt="command-code-cli",mt=["apikey","api_key","api-key","token","secret","authorization","auth","password","passwd","credential","auth_key","authkey","access_token","access-token","refresh_token","refresh-token","client_secret","clientsecret","private_key","privatekey","bearer","key"],gt=["content","body"],pt=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 Rt,Dt,Ot=__esm({"../shared/src/constants.ts"(){_t(),ft="--xco",yt={INTERNAL_TEAM_FLAG_HEADER:`x-${(ht="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage",CLI_ENVIRONMENT:"x-cli-environment"},wt={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"}}}},Et={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(Et.ALPHA.TASTE),Object.values(Et.BETA.TASTE_PACKAGES),wt.ALPHA.GENERATE,wt.ALPHA.AGENT.GENERATE,wt.ALPHA.WHOAMI,wt.ALPHA.NAMESPACES,wt.ALPHA.SHARE.CREATE,wt.ALPHA.SHARE.DELETE,wt.ALPHA.SHARE.APPEND,wt.ALPHA.DEVREL_THREAD.CREATE,wt.ALPHA.DEVREL_THREAD.DELETE,wt.ALPHA.DEVREL_THREAD.UPDATE,wt.ALPHA.TASTE.LEARN,wt.ALPHA.TASTE.DELETE,wt.ALPHA.TASTE.GET,wt.ALPHA.TASTE.UPDATE,Object.values(wt.BETA.TASTE.PACKAGES),wt.INTERNAL.ADMIN.USERS,wt.INTERNAL.ADMIN.ORGS,wt.INTERNAL.ADMIN.ENTITY_TYPE,wt.INTERNAL.USER.AVATAR,wt.INTERNAL.USER.SETTINGS,wt.INTERNAL.API_KEYS.LIST,wt.INTERNAL.API_KEYS.CREATE,wt.INTERNAL.API_KEYS.DELETE,wt.INTERNAL.USAGE.LIST,wt.INTERNAL.USAGE.SUMMARY,wt.INTERNAL.ADMIN.GRANT_CREDITS,wt.INTERNAL.ADMIN.GRANT_ORG_CREDITS,wt.INTERNAL.BILLING.CREDITS.GET,wt.INTERNAL.BILLING.CUSTOMERS.GET,wt.INTERNAL.BILLING.CUSTOMERS.UPSERT,wt.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,wt.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,wt.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,wt.INTERNAL.BILLING.CUSTOMERS.INVOICES,wt.INTERNAL.BILLING.SUBSCRIPTIONS.GET,wt.INTERNAL.ORGS.LIST,wt.INTERNAL.ORGS.GET,wt.INTERNAL.ORGS.CREATE,wt.INTERNAL.ORGS.UPDATE,wt.INTERNAL.ORGS.DELETE,wt.INTERNAL.ORGS.MEMBERS.LIST,wt.INTERNAL.ORGS.MEMBERS.ADD,wt.INTERNAL.ORGS.MEMBERS.UPDATE,wt.INTERNAL.ORGS.MEMBERS.REMOVE,wt.INTERNAL.ORGS.INVITATIONS.LIST,wt.INTERNAL.ORGS.INVITATIONS.SEND,wt.INTERNAL.ORGS.INVITATIONS.ACCEPT,wt.INTERNAL.ORGS.INVITATIONS.CANCEL,wt.INTERNAL.TASTE.PACKAGES.LIST,Object.values(Et.INTERNAL.ORGS),Object.values(Et.INTERNAL.USER),Object.values(Et.INTERNAL.TASTE.PACKAGES),bt={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(bt.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl"),St={ANTHROPIC:"anthropic"},vt="anthropic:claude-haiku-4-5-20251001",g.enum(["owner","admin","member"]),Ct={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,Pt=kt.SONNET_4_6.id,new Set([].map(e=>e.toLowerCase())),Tt=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],At={TIER_1_THRESHOLD:.5,TIER_2_THRESHOLD:.8,TIER_3_THRESHOLD:.9,TIER_1_KEEP_COUNT:20,TIER_2_KEEP_COUNT:10,KEEP_RECENT_TOKENS:3e4}}}),Lt=__esm({"src/utils/env.ts"(){_t(),Rt=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),Dt=__name(()=>{const e=Rt();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag")}});function getAuthDir(){return t.join(f.homedir(),".commandcode")}function getAuthFile(e){const n=e??Rt(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??Rt(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var Mt,Ft,Ut=__esm({"src/utils/auth/auth-paths.ts"(){_t(),Ot(),Lt(),__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 E.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(;!E.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=f.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(f.homedir(),n.slice(1))),t.isAbsolute(n)||(n=t.resolve(process.cwd(),n)),t.normalize(n)}function createSkippedResult(e){const{inputPath:t,absolutePath:n,code:r}=e,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=E.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{E.accessSync(n,E.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"}):Ft.some(e=>isPathInDirectory(o,e)||isPathInDirectory(e,o))?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_ADDED"}):(Ft.push(o),{status:"added",inputPath:e,absolutePath:o,displayPath:formatDirectoryForDisplay(o)})}function getAdditionalDirectories(){return[...Ft]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Ft.findIndex(e=>areSamePath(t,e));return-1!==n&&(Ft.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Ft.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t)}var jt=__esm({"src/utils/additional-dirs.ts"(){_t(),Mt=new Set(["/etc","/root","/proc","/sys","/dev",t.join(f.homedir(),".ssh"),t.join(f.homedir(),".gnupg"),t.join(f.homedir(),".aws")]),Ft=[],__name(normalizePathForComparison,"normalizePathForComparison"),__name(areSamePath,"areSamePath"),__name(getCanonicalPath,"getCanonicalPath"),__name(canonicalizeForLookup,"canonicalizeForLookup"),__name(formatDirectoryForDisplay,"formatDirectoryForDisplay"),__name(isPathInDirectory,"isPathInDirectory"),__name(findSensitiveDirectoryConflict,"findSensitiveDirectoryConflict"),__name(resolveDirectoryPath,"resolveDirectoryPath"),__name(createSkippedResult,"createSkippedResult"),__name(createErrorResult,"createErrorResult"),__name(addDirectory,"addDirectory"),__name(getAdditionalDirectories,"getAdditionalDirectories"),__name(removeAdditionalDirectory,"removeAdditionalDirectory"),__name(isPathInAdditionalDirs,"isPathInAdditionalDirs"),__name(isPathInWorkspace,"isPathInWorkspace")}});function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${f.platform()}-${f.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return E.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 _("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return _("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){try{const e=_("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=_("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=_("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository(),t=getAdditionalDirectories();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getAccessibleDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[],...t.length>0?{additionalDirectories:t}:{}}}function detectTerminal(){const e=process.env;if(e.TERM_PROGRAM){const t=e.TERM_PROGRAM;if("vscode"===t)return{name:"Visual Studio Code",type:"vscode",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("iTerm.app"===t)return{name:"iTerm2",type:"iterm2",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION,iterm2Profile:e.ITERM_PROFILE}};if("Apple_Terminal"===t)return{name:"macOS Terminal",type:"terminal",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("WarpTerminal"===t)return{name:"Warp",type:"warp",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("Hyper"===t)return{name:"Hyper",type:"hyper",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("ghostty"===t)return{name:"Ghostty",type:"ghostty",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}}}if(e.WT_SESSION||e.WT_PROFILE_ID)return{name:"Windows Terminal",type:"windows-terminal",details:{wtSession:e.WT_SESSION,wtProfileId:e.WT_PROFILE_ID}};if(e.ALACRITTY_SOCKET||e.ALACRITTY_WINDOW_ID)return{name:"Alacritty",type:"alacritty",details:{alacrittySocket:e.ALACRITTY_SOCKET,alacrittyWindowId:e.ALACRITTY_WINDOW_ID}};if(e.KITTY_WINDOW_ID||e.KITTY_PID)return{name:"Kitty",type:"kitty",details:{kittyWindowId:e.KITTY_WINDOW_ID,kittyPid:e.KITTY_PID}};if(e.GNOME_TERMINAL_SERVICE||e.VTE_VERSION)return{name:"GNOME Terminal",type:"gnome-terminal",details:{gnomeTerminalService:e.GNOME_TERMINAL_SERVICE,vteVersion:e.VTE_VERSION}};if(e.KONSOLE_VERSION||e.KONSOLE_PROFILE_NAME)return{name:"Konsole",type:"konsole",details:{konsoleVersion:e.KONSOLE_VERSION,konsoleProfile:e.KONSOLE_PROFILE_NAME}};if(e.TMUX)return{name:"tmux",type:"tmux",details:{tmux:e.TMUX,tmuxPane:e.TMUX_PANE}};if(e.ConEmuPID||e.ConEmuBuild)return{name:"ConEmu",type:"conemu",details:{conEmuPid:e.ConEmuPID,conEmuBuild:e.ConEmuBuild}};if(e.SSH_CLIENT||e.SSH_TTY)return{name:"SSH",type:"ssh",details:{sshClient:e.SSH_CLIENT,sshTty:e.SSH_TTY}};if(e.CI){const t=e.GITHUB_ACTIONS?"GitHub Actions":e.GITLAB_CI?"GitLab CI":e.JENKINS_URL?"Jenkins":e.CIRCLECI?"CircleCI":"Unknown CI";return{name:t,type:"ci",details:{ci:e.CI,ciName:t}}}const t=e.TERM||"unknown";return{name:`Unknown Terminal (${t})`,type:"unknown",details:{term:t,colorterm:e.COLORTERM,shell:e.SHELL}}}function getIsTerminalIterm2(){return"iTerm2"===detectTerminal().name}var Bt,qt,zt,Wt,Ht,Vt,Gt,Kt,Jt,Qt,Yt,Zt=__esm({"src/utils/environment.ts"(){_t(),jt(),__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(getAccessibleDirectoryStructure,"getAccessibleDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext"),__name(detectTerminal,"detectTerminal"),__name(getIsTerminalIterm2,"getIsTerminalIterm2")}});function isWordLeftSequence(e){return!!Bt.has(e)||!!Qt.test(e)}function isWordRightSequence(e){return!!qt.has(e)||!!Yt.test(e)}function isHomeSequence(e){return zt.has(e)}function isEndSequence(e){return Wt.has(e)}function isForwardDeleteSequence(e){return Ht.has(e)}function isDeleteWordSequence(e){return Vt.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===Gt.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===Gt.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===Gt.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===Gt.CTRL_U}function isAltP(e){return Jt.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 Xt,en,tn,nn,rn,on,sn=__esm({"src/utils/keyboard-sequences.ts"(){_t(),Bt=new Set(["[1;3D","b","[1;5D","[1;9D","[5D"]),qt=new Set(["[1;3C","f","[1;5C","[1;9C","[5C"]),zt=new Set(["[H","[1~","[7~","OH"]),Wt=new Set(["[F","[4~","[8~","OF"]),Ht=new Set(["[3~"]),Vt=new Set(["",""]),Gt={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},Kt={ALT_P:112,ALT_P_NO_META:960},Jt=new Set([String.fromCharCode(27,Kt.ALT_P),String.fromCharCode(Kt.ALT_P_NO_META),"[112;3u"]),Qt=/^\x1b\[1;[359]D$/,Yt=/^\x1b\[1;[359]C$/,__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(isAltP,"isAltP"),__name(isCtrlKey,"isCtrlKey")}}),an=__esm({"src/auth/index.ts"(){_t(),Ot(),Lt(),(e=>{e.OAuth=p.object({type:p.literal("oauth"),refresh:p.string(),access:p.string(),expires:p.number()}),e.ApiKey=p.object({type:p.literal("api"),key:p.string()}),e.Info=p.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const n=__name(()=>t.join(f.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=Rt(),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 D.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await D.mkdir(o,{recursive:!0});let a={};try{const e=await D.readFile(s,"utf-8");a=JSON.parse(e)}catch{}a[e]=t,await D.writeFile(s,JSON.stringify(a,null,2)),await D.chmod(s,384)}async function remove(e){const t=r();try{const n=await D.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await D.unlink(t):(await D.writeFile(t,JSON.stringify(r,null,2)),await D.chmod(t,384))}catch{}}async function list2(){try{const e=await D.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")})(Xt||(Xt={}))}}),cn=__esm({"src/utils/constants.ts"(){_t(),Ot(),en="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing",tn='OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.',nn=">"}}),ln=__esm({"src/auth/anthropic.ts"(){_t(),an(),cn(),Sr(),(e=>{const t="9d1c250a-e61b-44d9-88ed-5944d1962f5e",n="https://console.anthropic.com/v1/oauth/token",r="https://console.anthropic.com/oauth/code/callback";function generateCodeVerifier(){return j.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return j.createHash("sha256").update(e).digest("base64url")}function generateState(){return j.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),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:hr.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const i=await a.json();await Xt.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 Xt.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:hr.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await Xt.remove("anthropic");const o=await r.json();return await Xt.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:hr.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await Xt.remove("anthropic")}}}async function getValidAccessToken2(){const e=await Xt.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")})(rn||(rn={}))}});function isWordBoundary(e){return!e||0===e.length||on.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 un=__esm({"src/utils/text-navigation.ts"(){_t(),on=/\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 stripBracketedPasteMarkers(e){return e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"").replace(/\x1B\[201~/g,"").replace(/\[201~/g,"")}function processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};const r=stripBracketedPasteMarkers(e);let o,s;if(t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){o=e.slice(0,t.index);const r=e.slice(t.index+t[0].length);if(n){const e=r.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(s=r.slice(0,e.index))}else s=r}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:r,textBeforePaste:o,pastedContent:s}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}var dn=__esm({"src/utils/bracketed-paste.ts"(){_t(),__name(stripBracketedPasteMarkers,"stripBracketedPasteMarkers"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode")}});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=stripBracketedPasteMarkers(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 mn,gn,pn,hn=__esm({"src/components/text/input-handlers.ts"(){_t(),un(),sn(),dn(),__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(){mn||(mn=!0,gn=[],pn=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&gn.push(t)},"earlyInputHandler"),process.stdin.on("data",pn))}function stopEarlyInputCapture(){mn&&pn&&(process.stdin.off("data",pn),pn=null,mn=!1)}function consumeBufferedInput(){const e=gn.join("");return gn=[],e}function hasBufferedInput(){return gn.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("[I")||e.startsWith("[O"))}var fn=__esm({"src/utils/early-input-buffer.ts"(){_t(),mn=!1,gn=[],pn=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 l=(e||"").length,u=(i||"").length;(Math.abs(l-u)>1||r>l)&&(o(l),s.current=l)},[e,t,n,r]);const i=V(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}){X((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void a?.(n.current);const l=processInkInput(e,i,n.current,r.current,t);if(!l.handled)return;const u=clampCursor(l.cursor,l.value.length);s(l.value,u)},{isActive:e})}function useSyncedRef(e){const t=W(e);return H(()=>{t.current=e},[e]),t}var yn=__esm({"src/components/text/hooks.ts"(){_t(),un(),hn(),fn(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef")}});function renderPlaceholder(e,t){return t?0===e.length?te.inverse(" "):te.inverse(e[0])+te.grey(e.slice(1)):te.grey(e)}function renderValue(e,t,n){if(!n)return e;if(0===e.length)return te.inverse(" ");let r="";for(let n=0;n<e.length;n++)n===t?"\n"===e[n]?r+=te.inverse(" ")+"\n":r+=te.inverse(e[n]):r+=e[n];return t===e.length&&(r+=te.inverse(" ")),r}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(ne(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",l=0,u=!0;for(const e of a){const t=ne(e).length;if(l+t>(u?s:o)&&l>0&&(i+="\n"+r,l=n,u=!1),i+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=ne(t).length,u=!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 wn=__esm({"src/components/text/render-utils.ts"(){_t(),__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:l="",prefixColor:u}){const d=W(!1),m=useSyncedRef(e),g=useSyncedRef(s),{cursor:p,setCursor:h,cursorRef:f}=useCursorState({value:e,focus:n,showCursor:o});q.useEffect(()=>{i?.(p)},[p,i]);const y=V(createStdinUpdateHandler(h,m,g),[h,m,g]),w=V(()=>createInkUpdateHandler(h,m,s),[h,m,s])(),E=V(e=>{d.current=e},[]),b=V(()=>d.current,[]);useRawStdinHandler({focus:n,valueRef:m,cursorRef:f,onUpdate:y,setHandled:E}),useInkInputHandler({focus:n,showCursor:o,valueRef:m,cursorRef:f,isHandledByStdin:b,onUpdate:w,onSubmit:a});const{stdout:S}=Z(),v=S?.columns??80,C=getMaskedValue(e,r),k=wrapWithIndent(__name(()=>{if(!l)return"";if(!u)return l;const e={white:re.white,green:re.green,red:re.red,blue:re.blue,yellow:re.yellow,cyan:re.cyan,magenta:re.magenta,gray:re.gray,grey:re.gray}[u];return e?e(l):l},"getColoredPrefix")()+getDisplayValue(C,t,p,o,n),v,l?.length??0);return q.createElement(J,{wrap:"wrap"},k)}var En=__esm({"src/components/text/text-input.tsx"(){_t(),yn(),wn(),un(),__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=oe(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,l,{width:u,height:d}=s;(u>a||d>a)&&(u>d?(d=Math.round(d*a/u),u=a):(u=Math.round(u*a/d),d=a)),t.includes("png")&&s.hasAlpha?(i=await o.resize(u,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),l="image/png"):(i=await o.resize(u,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),l="image/jpeg");const m=i.length;return{compressedBase64:i.toString("base64"),mediaType:l,originalSizeBytes:r,compressedSizeBytes:m,compressionRatio:r/m}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}var bn,Sn=__esm({"src/utils/image-compression.ts"(){_t(),__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=bn[n];if(!r)return null;const o=a(t);if(!b(o))return null;const s=S(o).toString("base64");if(!s||0===s.length)return null;if(s.length>32e6)return null;const l=await compressImageForSharing(s,r);return l?{data:l.compressedBase64,mediaType:l.mediaType}:null}catch(e){return null}}async function detectClipboardImage(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasImage())return null;let t=null;try{if(t=await e.default.getImageBase64(),!t){const n=e.default.getImageBase64();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}if(!t||0===t.length)return null;if(t.length>32e6)return console.log("Image too large:",t.length,"bytes"),null;try{const e=await compressImageForSharing(t,"image/png");return e?{data:e.compressedBase64,mediaType:e.mediaType}:(console.log("Failed to compress clipboard image"),null)}catch(e){return console.log("Failed to process clipboard image:",e),null}}catch(e){return null}}async function detectClipboardText(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasText())return null;let t=null;try{if(t=await e.default.getText(),!t){const n=e.default.getText();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}return t&&0!==t.length?t:null}catch(e){return null}}var vn,Cn,kn,Pn,Tn=__esm({"src/utils/clipboard-image.ts"(){_t(),Sn(),bn={".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 getIcon(e){if(kn[e])return kn[e];const t=e.split(":")[0];return kn[t]?kn[t]:kn.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(!Pn){Pn=!0;try{w.mkdirSync(vn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${Cn}\n════════════════════════════════════════════════════════════════\n\n`;w.appendFileSync(Cn,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} ${kn.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",w.appendFileSync(Cn,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`;w.appendFileSync(Cn,t,"utf-8")}catch{}}}var An,xn=__esm({"src/utils/dlog.ts"(){_t(),vn=e.join(h.homedir(),".commandcode","logs"),Cn=e.join(vn,"command.log"),kn={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"),Pn=!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 R.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();w.writeFileSync(t,JSON.stringify(e,null,2)),w.chmodSync(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t=await loadUserConfig(),n=getConfiguredModel(),r={...t,...e,model:e.model??n};await saveUserConfig(r)}async function isTasteLearningEnabled(){return(await loadUserConfig()).tasteLearning??!0}async function setTasteLearning(e){const{tasteLearning:t}=e;await updateUserConfig({tasteLearning:t})}async function isOAuthEnforced(){if(null!==An)return An;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),An=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),An=!0,!0;const e=await loadUserConfig();return(An=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),An}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error(tn)}function getConfiguredModel(){try{const e=getConfigFile();return(parseJSON(w.readFileSync(e,"utf-8"))||{}).model??Pt}catch{return Pt}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}var In,_n,Nn=__esm({"src/utils/user-config.ts"(){_t(),Ot(),Ut(),cn(),xn(),Rn(),Dn(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),An=null,__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel")}}),$n=__esm({"src/components/anthropic-auth.tsx"(){_t(),En(),ln(),cn(),Tn(),dn(),Nn(),In=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=z(""),[s,a]=z(null),[i,l]=z(!1),[u,d]=z(null),[m,g]=z(!0),[p,h]=z(!1),[f,y]=z(!1);H(()=>{const{url:e,verifier:t,state:n}=rn.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const w=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||f){if(!f||t.isPasteEnd){if(f&&t.isPasteEnd){y(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}o(e)}}else if(y(!0),t.isPasteEnd){y(!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}},[f]);X((e,n)=>{if(n.escape&&t(),m&&!p)if("y"!==e&&"Y"!==e)"n"!==e&&"N"!==e||t();else{if(!s)return;se(s.url).then(()=>{h(!0),g(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),h(!0),g(!1)})}});const E=__name(async()=>{if(r.trim()&&s&&!i){l(!0),d(null);try{const t=r.split("#")[0].trim();await rn.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),l(!1),n&&n(t)}}},"handleSubmit");return m&&!p?q.createElement(K,{flexDirection:"column"},q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,color:"cyan"},"Anthropic Authentication")),q.createElement(K,{marginBottom:1},q.createElement(J,null,"Open the Anthropic auth page?",q.createElement(J,{dimColor:!0}," (Y/n)")))):q.createElement(K,{flexDirection:"column"},q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,color:"cyan"},"Anthropic Authentication")),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"After authorizing, copy the code and paste it below:")),u&&q.createElement(K,{marginBottom:1},q.createElement(J,{color:"red"},"Error: ",u)),q.createElement(K,null,q.createElement(J,null,"Authorization code: "),q.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:w,onSubmit:E,placeholder:"Paste code here..."})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function getProviderDisplayName(e){if(!e)return"None";const t=_n[e];return t?.displayName||e}function getProviderConfig(e){return _n[e]}function isInternalTeamFlagPresent(){return process.argv.includes(ht)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(ft)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(w.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(_n).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var Rn=__esm({"src/utils/provider-config.ts"(){_t(),Ot(),ln(),$n(),Ut(),Dn(),_n={"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:In,checkAuth:__name(async()=>!!await rn.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(ft)}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 D.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 Dn=__esm({"src/utils/utils.ts"(){_t(),Ot(),Ut(),Zt(),sn(),Rn(),Nn(),__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=E.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var On=__esm({"src/utils/is-local-dev.ts"(){_t(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":Rt()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return lt;case"local":return ut;default:return ct}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(w.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var Ln=__esm({"src/utils/telemetry/config.ts"(){_t(),Ut(),Dn(),Lt(),On(),$t(),$t(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}}),Mn={};function getPackageJson(){const e=import.meta.url,t=u(e),o=r(t);return JSON.parse(S(n(o,"./../package.json"),"utf8"))}__export(Mn,{getPackageJson:()=>getPackageJson});var Fn,Un,jn,Bn,qn,zn,Wn=__esm({"src/utils/package.ts"(){_t(),__name(getPackageJson,"getPackageJson")}});function createAxiomExporter(){return new Un({url:it,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":at}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return jn({[Bn]:dt,[qn]: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 Fn({resource:t,spanProcessors:[new zn(e)],autoDetectResources:!1})}var Hn,Vn,Gn,Kn,Jn,Qn=__esm({"src/utils/telemetry/sdk-factory.ts"(){_t(),$t(),Ln(),Wn(),({NodeSDK:Fn}=ae),({OTLPTraceExporter:Un}=ie),({resourceFromAttributes:jn}=ce),({ATTR_SERVICE_NAME:Bn,ATTR_SERVICE_VERSION:qn}=le),({SimpleSpanProcessor:zn}=ue),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function generateSessionId(){return`sess_${pe().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return U.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":`${h.platform()}-${h.arch()}`,"session.node_version":process.version}}function startSession(){Jn={},Vn=null,Gn=null,Hn=generateSessionId(),Kn=Date.now();try{const e=de.getTracer(dt),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:Hn,projectPath:n,gitBranch:r,cliVersion:t});Vn=e.startSpan("session:cli",{attributes:o}),Gn=Vn.spanContext(),Vn.end()}catch{Vn=null,Gn=null}return Hn}function getTraceId(){return Gn?Gn.traceId:null}function getSessionContext(){return Gn?de.setSpanContext(ge.active(),Gn):ge.active()}function endSession(e={}){const{status:t="success"}=e;if(Gn&&Kn){const e=de.getTracer(dt),n=Date.now()-Kn,r=de.setSpanContext(ge.active(),Gn),o=e.startSpan("session:end",{attributes:{"session.id":Hn||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Jn}},r);"error"===t?o.setStatus({code:me.ERROR}):o.setStatus({code:me.OK}),o.end()}Vn=null,Gn=null,Hn=null,Kn=null,Jn={}}var Yn=__esm({"src/utils/telemetry/session.ts"(){_t(),$t(),Wn(),Zt(),Hn=null,Vn=null,Gn=null,Kn=null,Jn={},__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:me.ERROR}):e.setStatus({code:me.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=de.getTracer(dt),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:me.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 Zn,Xn,er,tr,nr,rr,or,sr,ar,ir,cr,lr,ur,dr,mr=__esm({"src/utils/telemetry/spans.ts"(){_t(),$t(),Yn(),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});function getEffectiveWidth({padding:e=tr}={}){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<=nr)return t;if(t.includes(" && ")){const e=t.split(" && ")[0].trim();return e.length<=nr-5?`${e} && ...`:truncateString({text:e,maxChars:nr})}return truncateString({text:t,maxChars:nr})}function truncateToVisualLines({output:e,maxVisualLines:t=Zn,padding:n=tr,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,l=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)){l=Math.max(1,e);break}i+=r}const u=l<a.length,d=a.slice(l).reduce((e,t)=>e+Math.max(1,Math.ceil(t.length/o)),0),m=a.slice(0,l).filter(e=>e.trim().length>0).join("\n");if(m.length>s){const e=m.slice(0,s-3).trimEnd(),t=e.lastIndexOf("\n"),n=t>0?e.slice(0,t):e;return{text:u?n:`${n}...`,isTruncated:!0,remainingLines:d}}return{text:m,isTruncated:u,remainingLines:d}}var gr=__esm({"src/utils/truncation.ts"(){_t(),Zn=2,Xn=10,er=10,tr=4,nr=100,rr=100,or=50,sr=100,ar=60,ir=80,cr=1e5,lr=5e4,ur=25e3,dr=200,__name(getEffectiveWidth,"getEffectiveWidth"),__name(truncateString,"truncateString"),__name(truncateCommand,"truncateCommand"),__name(truncateToVisualLines,"truncateToVisualLines")}});function isSecretKey(e){const t=e.toLowerCase();return mt.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return gt.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString2(e){return e.length<=dr?e:`${e.substring(0,dr-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>dr?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 pr=__esm({"src/utils/telemetry/sanitization.ts"(){_t(),$t(),gr(),__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,pt))}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,l={"error.type":r.name,"error.message":r.message,"error.component":o,"error.heading":s};void 0!==a&&(l["error.code"]=String(a));for(const[e,t]of Object.entries(i))null!=t&&(l[e]="object"==typeof t?safeStringify(t):String(t));const u=createSpan({name:`error:${r.name}`,attributes:l});recordError({span:u,error:r}),u.end()}function trackAPICallStart(e){const{method:t,endpoint:n}=e,r=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${r}`,attributes:{"http.method":t,"http.url":r}}),startTime:Date.now(),durationAttr:"http.duration_ms",statusAttr:"http.status"})}function getSupportId(){const e=getTraceId();return e?`req_${e}`:"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,nodeVersion:s,platform:a,arch:i}=e,l={"whoami.node_version":s,"whoami.platform":a,"whoami.arch":i,"whoami.os":`${a}-${i}`};t&&(l["whoami.user_name"]=t),n&&(l["whoami.user_id"]=n),r&&(l["whoami.org_login"]=r),o&&(l["whoami.org_id"]=o),endSpan({span:createSpan({name:"whoami",attributes:l}),status:"success"})}var hr,fr,yr,wr=__esm({"src/utils/telemetry/events.ts"(){_t(),mr(),Yn(),$t(),pr(),pr(),__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"(){_t(),hr={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(yr)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(fr=createTelemetrySDK()).start(),yr=!0,!0}catch{return fr=null,yr=!1,!1}}async function shutdownTelemetry(){if(fr&&yr)try{endSession(),await fr.shutdown()}catch{}finally{fr=null,yr=!1}}function shutdownTelemetrySync(){if(yr)try{endSession()}catch{}}function isTelemetryInitialized(){return yr}var br,Sr=__esm({"src/utils/telemetry/telemetry.ts"(){_t(),Qn(),Ln(),Yn(),mr(),wr(),Er(),fr=null,yr=!1,__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized")}});function getTokenFilePath(){return e.join(f.homedir(),".commandcode",br)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await R.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 R.mkdir(r,{recursive:!0}),await R.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await R.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 vr,Cr=__esm({"src/mcp/auth/token-storage.ts"(){_t(),Ot(),xn(),br="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(),vr);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var kr,Pr,Tr=__esm({"src/mcp/fetch.ts"(){_t(),vr=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),Ar={};function generateRandomString(e){return U.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:U.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=he.createServer((n,r)=>{const a=new d(n.url||"/",`http://${Pr}:${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,Pr,()=>{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||kr,o=n?.timeout||12e4,s=n?.onStatus||(()=>{});let a=null;try{const n=generatePKCE(),i=generateRandomString(32),l=`http://${Pr}:${r}/callback`;s("Starting authentication server...");const{server:u,getCode:m}=await startCallbackServer(r,i);a=u;const g=new d(t.authorizationUrl);if(g.searchParams.set("response_type","code"),g.searchParams.set("client_id",t.clientId),g.searchParams.set("redirect_uri",l),g.searchParams.set("state",i),g.searchParams.set("code_challenge",n.challenge),g.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&g.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))g.searchParams.set(e,n);s("Opening browser for authentication..."),await se(g.toString()),s("Waiting for authorization...");const p=m();let h;const f=new Promise((e,t)=>{h=setTimeout(()=>t(new Error("Authentication timed out")),o)}),y=await Promise.race([p,f]);clearTimeout(h),s("Exchanging authorization code for tokens...");const w=await exchangeCodeForTokens(t,y,n.verifier,l);return await storeTokens(e,w),s("Authentication successful!"),{success:!0,tokens:w}}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(Ar,{DEFAULT_OAUTH_CALLBACK_PORT:()=>kr,LOCALHOST_IP:()=>Pr,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var xr,Ir,_r,Nr,$r,Rr,Dr,Or,Lr,Mr,Fr,Ur,jr,Br,qr,zr=__esm({"src/mcp/auth/oauth-flow.ts"(){_t(),Cr(),Tr(),kr=8085,Pr="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")}}),Wr=__esm({"src/components/vscode-context/ipc-client.ts"(){_t(),xn(),xr=t.join(f.homedir(),".commandcode","ide"),Ir=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),_r=__name(e=>{if("win32"===process.platform)return null;try{const t=_(`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"),Nr=__name((e,t,n=_r)=>{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"),$r=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),Rr=__name((e,n)=>{try{E.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{E.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),Dr=__name((e,n={})=>{const{sessionDir:r=xr,parentPidFn:o=_r,startPid:s=process.ppid}=n;try{if(!E.existsSync(r))return null;const n=`${e}-`,a=E.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(E.readFileSync(n,"utf-8"));if(!Ir(o.pid)){Rr(n,r);continue}i.push({session:o,file:e})}catch{continue}if(0===i.length)return null;const l=Nr(i,s,o);if(l)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:l.session.socketPath,ideName:l.session.ideName}),l.session.socketPath;const u=process.cwd();let d=null,m=0;for(const{session:e}of i)for(const n of e.workspaceFolders)(u===n||u.startsWith(n+t.sep))&&n.length>m&&(d=e,m=n.length);return d&&dlog("[VSCode:IPC] Discovered session via workspace match",{socketPath:d.socketPath,ideName:d.ideName}),d?.socketPath??null}catch{return null}},"discoverSocketPath"),Or=__name(()=>{const e=$r();return e?Dr(e):null},"resolveSocketPath"),Lr=__name(()=>({type:"request",id:B(),payload:{action:"getContext"}}),"createContextRequest"),Mr=__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"),Fr=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!Mr(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"),Ur=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??Or()}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=ye.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=Lr();return dlog("[VSCode:IPC] Requesting context",{requestId:n.id}),await new Promise(r=>{const o=__name(()=>{t.off("data",i),t.off("error",l)},"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),l=Fr(Buffer.from(i),n.id);l?dlog("[VSCode:IPC] Context received",{hasActiveFile:!!l.activeFile,hasSelection:!!l.selection,openFilesCount:l.openFiles.length}):dlog("[VSCode:IPC] Invalid response received"),r(l)}catch(e){clearTimeout(s),o(),dlog("[VSCode:IPC] Error processing response",{error:e}),r(null)}},"handleData"),l=__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",l);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}}}}}),Hr={};function getVsixPath(){try{const e=t.dirname(u(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return E.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),Ur.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await jr(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp(`${Br}@([\\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 jr(`${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=$r();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:te.green("✔"),installed:te.green("✔"),needs_reload:te.yellow("◌"),failed:te.red("✖"),not_in_ide:te.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=>te.dim(` ${e}`)),""]}async function runIDESetup(){const e=$r(),t=e?qr[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new Ur,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(Hr,{detectIDE:()=>$r,ensureExtensionInstalled:()=>ensureExtensionInstalled,formatSetupResult:()=>formatSetupResult,getExtensionStatus:()=>getExtensionStatus,installExtension:()=>installExtension,installExtensionAsync:()=>installExtensionAsync,isAutoInstallEnabled:()=>isAutoInstallEnabled,runIDESetup:()=>runIDESetup});var Vr=__esm({"src/utils/ide-installer.ts"(){_t(),Wr(),xn(),Nn(),jr=we(N),Br="commandcode.commandcode-vscode",__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled"),qr={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"},__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup")}});_t(),_t();var Gr=process.argv.includes("-d")||process.argv.includes("--debug");Gr&&(process.env.DEBUG="true"),Gr||(process.removeAllListeners("warning"),process.on("warning",()=>{})),_t(),_t(),Sr();var{red:Kr,yellow:Jr,dim:Qr}=te,Yr=__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:hr.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${be.error} ${Kr(t)}`),console.log(`${be.error} ${Kr("ERROR →")} ${n.name}`),console.log(`${be.info} ${Kr("REASON →")} ${n.message}`),console.log(`${be.info} ${Kr("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${be.info} ${Qr(`Request ID: ${e}`)}`),console.log(`${Qr(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${be.warning} ${Jr(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:hr.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),Yr({heading:Ee`CRITICAL: Unhandled Promise Rejection!
|
|
3
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:hr.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),Yr({heading:Ee`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=fe.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}Sr(),__name(handleUnhandledErrors,"handleUnhandledErrors"),_t(),_t(),Ot(),_t(),_t(),Ot(),_t(),_t(),_t(),_t(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable");var Zr=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=he.createServer((e,o)=>{const a=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],i=e.headers.origin||"",l=a.includes(i)?i:a[0];if(o.setHeader("Access-Control-Allow-Origin",l),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 u="";e.on("data",t=>{u+=t.toString(),u.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(u);if(e.error){const t=e,n={success:!0};return o.writeHead(200),o.end(JSON.stringify(n)),"access_denied"===t.error?r(new Zr(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 U.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await se(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:hr.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(Rt()){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"),Lt(),Ut(),Sr(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl");var Xr=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 R.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 R.writeFile(n,r,{mode:384}),await R.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await R.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"),_t(),__name(getApiBaseUrl,"getApiBaseUrl"),Ot(),Sr();var eo=12e4;async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${wt.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:hr.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=eo}=e,[s,a]=z("initializing"),[i,l]=z("Starting authentication..."),[u,d]=z(""),[m,g]=z(null),p=W(null),h=W(!1),f=W(!1),y=W(null),w=W(t),E=W(n),b=W(r);H(()=>{w.current=t,E.current=n,b.current=r});const S=V(()=>{y.current&&(clearTimeout(y.current),y.current=null),p.current&&(stopServer(p.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),p.current=null)},[]),v=V(()=>{f.current||(f.current=!0,h.current=!0,S(),b.current())},[S]),C=V((e,t)=>{f.current||(f.current=!0,S(),w.current(e,t))},[S]),k=V((e,t)=>{f.current||(f.current=!0,S(),E.current(e,t))},[S]),P=V(async e=>{const t=sanitizeApiKey(e);if(!t)return;a("validating"),l("Validating API key...");const n=await validateApiKey(t);if(h.current)return;if(f.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return a("invalid_key"),l(e),void(y.current=setTimeout(()=>{h.current||f.current||(a("manual_entry"),l("Paste a valid API key below.")),y.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(f.current)return;await storeCredentials(e),a("success"),C(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:hr.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),l("Failed to save API key. Please try again."),a("manual_entry")}},[C]);return H(()=>{let e=!0;return __name(async()=>{if(!h.current)try{const t=await findAvailablePort(5959,10);if(!e||h.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);g(r);const{server:s,waitForCallback:i}=createAuthServer(t,n);if(p.current=s,!e||h.current)return void await stopServer(s);a("waiting_browser"),l("Opening browser for authentication...");const u=await openBrowser(r);if(!e||h.current)return;if(!u)return S(),l("Could not open browser. Paste your API key below."),void a("manual_entry");l("Complete login in your browser...");const d=new Promise((e,t)=>{setTimeout(()=>{t(new Xr("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([i,d]);if(!e||h.current)return;if(f.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(f.current)return;if(await storeCredentials(n),!e||h.current||f.current)return;a("browser_success"),C(n,"browser")}catch(t){if(f.current)return;if(!e||h.current)return;if(t instanceof Zr)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:hr.AUTH_FLOW,heading:"Authorization denied by user"}}),a("denied"),void k("denied","Authorization denied by user.");S(),t instanceof Xr&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:hr.AUTH_FLOW,heading:"Browser auth timed out"}}),l("Browser auth timed out. Paste your API key below.")):(trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_failed"}),context:{component:hr.AUTH_FLOW,heading:"Browser auth failed"}}),l("Browser auth failed. Paste your API key below.")),a("manual_entry")}}catch(t){if(f.current)return;if(!e||h.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:hr.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),S(),a("manual_entry"),l("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,S()}},[o,C,k,S]),{authState:s,statusMessage:i,browserUrl:m,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:P,cancel:v,hasCompleted:f.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"),_t(),wn(),Ot(),Lt(),_t(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel");var to=__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 q.createElement(Re,{type:"dots"});case"browser_success":case"success":return q.createElement(J,{color:"green"},Se.tick);case"denied":case"invalid_key":return q.createElement(J,{color:"red"},Se.cross);case"manual_entry":return q.createElement(J,{color:"yellow"},Se.arrowDown);case"error":return q.createElement(J,{color:"red"},Se.warning)}},"getStatusIcon"),i=__name(()=>getAuthStatusColor(e),"getStatusColor");if("browser_success"===e||"success"===e||"denied"===e)return null;const l="initializing"===e||"waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,u=n&&("waiting_browser"===e||"manual_entry"===e);return q.createElement(K,{flexDirection:"column",paddingY:1},q.createElement(K,{marginBottom:1},q.createElement(K,{marginRight:1},a()),q.createElement(J,{color:i()},t)),l&&q.createElement(K,{flexDirection:"column"},q.createElement(K,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?"yellow":"gray",paddingX:1},q.createElement(J,{dimColor:!0},"API Key: "),q.createElement(K,{flexGrow:1},q.createElement(TextInput,{value:r,onChange:o,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},getAuthHelpText(e))),u&&q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,{dimColor:!0},getAuthUrlLabel(e)),q.createElement(J,{color:"cyan",dimColor:!0},n||getStudioAuthUrl(Rt())))),"validating"===e&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"initializing"===e||"invalid_key"===e)&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Ctrl+C to cancel")))},"AuthFlowUI"),no=__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 X((e,t)=>{t.ctrl&&"c"===e&&i()}),q.createElement(to,{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?`${re.bgGreen(re.black(` ${e} `))}${o}`:n?`${re.bgBlack(re.white(` ${e} `))}${o}`:`${re.bold(re.bgCyan(re.black(` ${e} `)))}${o}`}async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=rn.createAuthorizationUrl(),r=await Ne({message:"Open the Anthropic auth page?"});if(Ie(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await se(e),console.log(),console.log(re.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(re.dim(" Open this URL in your browser:")),console.log(),console.log(re.cyan(` ${e}`)),console.log(),console.log(re.yellow(" Copy your authorization code and paste it below.")),console.log());const o=await $e({message:"Paste your authorization code:",mask:"*"});if(Ie(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 rn.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}cn(),Lt(),_t(),__name(heading,"heading"),Rn(),Nn(),_t(),ln(),__name(performAnthropicAuth,"performAnthropicAuth"),_t();var ro=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},oo=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 D.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=De("Checking authentication status...").start();try{const t=Rt(),n=await checkAuthStatus(t);n.error&&(e.fail(re.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(re.red("Not authenticated")),console.log(""),console.log(`${re.dim("Run")} ${re.cyan("cmd auth login")} ${re.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${re.green(Se.tick)} ${re.bold("Authenticated")} with ${re.cyan("Command Code")}`),n.userName&&console.log(`${re.dim("Logged in as")} ${re.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(re.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}_t(),Ot(),Ut(),Lt(),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(getUserName,"getUserName"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction");var so=new ke("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction),ao=__name(({message:e})=>q.createElement(q.Fragment,null,q.createElement(J,{color:"cyan"},q.createElement(Re,{type:"dots"})),q.createElement(J,null," ",e)),"LoadingIndicator"),io=__name(({message:e})=>q.createElement(q.Fragment,null,q.createElement(J,{color:"green"},Se.tick),q.createElement(J,null," ",e)),"SuccessIndicator"),co=__name(({children:e})=>q.createElement(K,{flexDirection:"column"},q.createElement(J,null," "),q.createElement(K,null,e)),"StatusContainer");function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,a]=z("loading"),[i,l]=z(null);return H(()=>{n().then(e=>{l(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:q.createElement(co,null,"loading"===s?q.createElement(ao,{message:e}):q.createElement(io,{message:t}))}async function checkExistingAuth(e){const t=await checkAuthStatus(e);return t.authenticated?{isAuthenticated:!0,userName:t.userName}:{isAuthenticated:!1}}function getAuthFileName(e){return"local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json"}function isGenericUserName(e){return!e||"API Key"===e}function isGenericUserNameForOutro(e){return isGenericUserName(e)||"Manual API Key"===e}function formatUserDisplay(e,t=!1){return(t?isGenericUserNameForOutro(e):isGenericUserName(e))?t?" successfully":"":` as ${re.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${re.green(Se.tick)} ${re.bold("Already logged in")}${t}`,"",`${re.dim("Run")} ${re.cyan("cmd")} ${re.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${re.green(Se.tick)} ${re.bold("Logged in")}${n}`,"",`${re.dim("API key stored in")} ${re.cyan(`~/.commandcode/${t}`)}`,`${re.dim("Run")} ${re.cyan("cmd")} ${re.dim("to get started.")}`].join("\n")}function isLoginSuccess(e){return e.success}function isLoginDenied(e){return"denied"===e.reason}function isLoginCancelled(e){return"cancelled"===e.reason}function createLoginError(e){return isLoginDenied(e)?new oo(e.message):isLoginCancelled(e)?new ro(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 ro||e instanceof oo}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),Te.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await xe({message:"Select provider",options:e});if(Ie(t))throw Ae(`${Se.cross} No provider selected.`),new ro("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){Ae(`${Se.cross} ${e}`)}function showAnthropicAuthNote(){_e("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(q.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(q.createElement(no,{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 lo=__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]),q.createElement(co,null,"checking"===n&&q.createElement(ao,{message:"Checking authentication status..."}),"logged_in"===n&&q.createElement(io,{message:"Authenticated"}),"not_logged_in"===n&&q.createElement(io,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=Y(q.createElement(lo,{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=Rt(),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 uo=new ke("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction);async function safeRemoveFile(e,t){try{return await D.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"}}}_t(),_t(),Ut(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout");var mo=__name(()=>q.createElement(q.Fragment,null,q.createElement(J,{color:"cyan"},q.createElement(Re,{type:"dots"})),q.createElement(J,null," Logging out...")),"LoadingIndicator"),po=__name(()=>q.createElement(q.Fragment,null,q.createElement(J,{color:"green"},Se.tick),q.createElement(J,null," Logged out")),"SuccessIndicator"),ho=__name(({errorMessage:e})=>q.createElement(q.Fragment,null,q.createElement(J,{color:"red"},Se.cross),q.createElement(J,{color:"red"}," Logout failed: ",e)),"ErrorIndicator"),fo=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return q.createElement(mo,null);case"success":return q.createElement(po,null);case"error":return q.createElement(ho,{errorMessage:t})}},"StatusDisplay"),yo=__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]),q.createElement(K,{flexDirection:"column"},q.createElement(J,null," "),q.createElement(K,null,q.createElement(fo,{status:t,errorMessage:r})))},"LogoutSpinner");function printWarnings(e){e.length>0&&(console.warn(re.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(re.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=Y(q.createElement(yo,{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 wo=new ke("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction);Lt(),Ut(),new ke("auth").description("Manage authentication with Command Code").addCommand(uo).addCommand(wo).addCommand(so),_t(),Ot();var Eo="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",bo="\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 So=getMaxLineWidth(Eo),vo=getMaxLineWidth(bo),Co=So+1,ko=vo+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var Po=__name(e=>{const t=e??getTerminalWidth();return t>=Co?Eo:t>=ko?bo:To},"getResponsiveCommandLogo"),To="⌘ CMD\n",Ao=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),xo=__name(e=>{console.log(te.white(Po())),console.log(""),console.log(`${Se.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),Io=__name(async e=>{const t=Ce.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"),_o=__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"),No=__name(()=>{console.log(""),console.log(`${Se.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),$o=__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;xo(Dt());const{answer:e,cancelled:t}=await Io(`Would you like to sign in now? ${te.dim("(y/n)")}: `);return t?($o(),!1):Ao(e)?(console.log(""),_o()):(No(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin"),_t(),_t(),Ot(),_t();var Ro=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))}};_t(),_t();var Do=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 Oo({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Lo(e,o,n,r);case 401:return new Mo(e,o,n,r);case 403:return new Fo(e,o,n,r);case 404:return new Uo(e,o,n,r);case 409:return new jo(e,o,n,r);case 422:return new Bo(e,o,n,r);case 429:return new qo(e,o,n,r);default:return e>=500?new zo(e,o,n,r):new _APIError(e,o,n,r)}}},Oo=class extends Do{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)}},Lo=class extends Do{static{__name(this,"BadRequestError")}status=400},Mo=class extends Do{static{__name(this,"AuthenticationError")}status=401},Fo=class extends Do{static{__name(this,"PermissionDeniedError")}status=403},Uo=class extends Do{static{__name(this,"NotFoundError")}status=404},jo=class extends Do{static{__name(this,"ConflictError")}status=409},Bo=class extends Do{static{__name(this,"UnprocessableEntityError")}status=422},qo=class extends Do{static{__name(this,"RateLimitError")}status=429},zo=class extends Do{static{__name(this,"InternalServerError")}};Sr(),Yn(),Ln(),_t(),_t();var Wo=p.object({messageId:p.string().optional(),timestamp:p.string(),model:p.string().optional(),duration:p.number().optional(),usage:p.object({inputTokens:p.number(),outputTokens:p.number(),totalTokens:p.number(),cacheReadTokens:p.number().optional(),cacheWriteTokens:p.number().optional(),estimatedCost:p.number().optional()}).optional(),source:p.string().optional(),context:p.object({sessionId:p.string().optional(),threadId:p.string().optional(),userId:p.string().optional()}).optional(),highlight:p.boolean().optional(),isSummary:p.boolean().optional()});p.object({message:p.any(),meta:Wo}),p.object({sessionId:p.string(),messages:p.array(p.any()).optional()}),p.object({secret:p.string(),url:p.string()}),p.object({sessionId:p.string(),secret:p.string()}),p.object({sessionId:p.string(),secret:p.string(),key:p.string(),content:p.any()}),p.object({sessionId:p.string(),secret:p.string(),message:p.any()}),p.object({shortId:p.string()}),p.object({info:p.any().optional(),messages:p.array(p.any())}),_t(),_t(),_t(),p.object({to:p.union([p.email(),p.array(p.email())]),subject:p.string(),html:p.string().optional(),text:p.string().optional(),template:p.string().optional(),templateData:p.record(p.any(),p.any()).optional(),cc:p.array(p.email()).optional(),bcc:p.array(p.email()).optional(),replyTo:p.array(p.email()).optional(),tags:p.array(p.object({name:p.string(),value:p.string()})).optional()}),p.object({success:p.boolean(),messageId:p.string().optional(),error:p.string().optional()}),_t();var Ho=p.enum(["active","canceled","incomplete","incomplete_expired","past_due","trialing","unpaid"]),Vo=p.enum(["admin_grant","signup_credits","purchased_credits","subscription_credits"]),Go=p.enum(["agent","learning","custom-agent","custom-agent-create"]),Ko=p.enum(["free","monthly","purchased"]);p.enum(["team","individual","enterprise"]),p.object({type:p.enum(["api","oauth"]).default("api"),orgId:p.string().nullable().optional(),model:p.string().min(1),userId:p.string().min(1),traceId:p.string(),provider:p.enum(["openai","anthropic","azure"]).default("anthropic"),tokensIn:p.number().min(0),tokensOut:p.number().min(0),inputCost:p.number().min(0),totalCost:p.number().min(0),outputCost:p.number().min(0),ownerLogin:p.string(),tokensTotal:p.number().min(0),creditsTotal:p.number().min(0),durationTotal:p.number().min(0),mode:Go.nullable().optional(),cacheCost:p.number().min(0).optional(),cacheSavings:p.number().optional(),cacheCreation:p.object({ephemeral_5m_input_tokens:p.number().optional(),ephemeral_1h_input_tokens:p.number().optional()}).nullable().optional(),cacheCreationInputTokens:p.number().min(0).nullable().optional(),cacheReadInputTokens:p.number().min(0).nullable().optional(),threadId:p.string().nullable().optional(),messageInId:p.string().nullable().optional(),messageOutId:p.string().nullable().optional()}),p.object({success:p.boolean(),instanceId:p.string().optional(),error:p.string().optional()}),p.object({userId:p.string().min(1),orgId:p.string().nullable()}),p.object({credits:p.object({freeCredits:p.number(),belowThreshold:p.boolean(),monthlyCredits:p.number(),creditThreshold:p.number(),availableCredits:p.number(),purchasedCredits:p.number()})}),p.object({userId:p.string().min(1),orgId:p.string().nullable().optional()}),p.object({success:p.boolean(),data:p.object({id:p.string(),userId:p.uuid(),orgId:p.string().nullable(),stripeCustomerId:p.string(),autoCharge:p.boolean(),creditThreshold:p.string(),rechargeAmount:p.string(),monthlyCreditThreshold:p.string()}).optional(),error:p.string().optional()}),p.object({userId:p.string().min(1),orgId:p.string().nullable().optional(),autoCharge:p.boolean().optional(),rechargeAmount:p.number().min(0).optional(),creditThreshold:p.number().min(0).optional(),monthlyCreditThreshold:p.number().min(0).optional(),stripeCustomerId:p.string().optional()}),p.object({success:p.boolean(),data:p.object({id:p.string(),userId:p.uuid(),orgId:p.string().nullable(),stripeCustomerId:p.string(),autoCharge:p.boolean(),creditThreshold:p.string(),rechargeAmount:p.string()}).optional(),error:p.string().optional()}),p.object({userId:p.string().min(1),userEmail:p.email(),orgId:p.string().nullable().optional()}),p.object({success:p.boolean(),data:p.object({clientSecret:p.string(),customerId:p.string()}).optional(),error:p.string().optional(),message:p.string().optional()}),p.object({userId:p.string().min(1),orgId:p.string().nullable().optional()}),p.object({success:p.boolean(),data:p.object({hasPaymentMethod:p.boolean(),paymentMethods:p.array(p.object({id:p.string(),brand:p.string().optional(),last4:p.string().optional(),expMonth:p.number().optional(),expYear:p.number().optional(),default:p.boolean()})),customerId:p.string().optional()}).optional(),error:p.string().optional()}),p.object({userId:p.string().min(1),paymentMethodId:p.string().min(1),orgId:p.string().nullable().optional()}),p.object({success:p.boolean(),error:p.string().optional()}),p.object({userId:p.string().min(1),orgId:p.string().nullable().optional(),customerId:p.string().min(1),paymentMethodId:p.string().min(1)}),p.object({success:p.boolean(),message:p.string().optional(),error:p.string().optional()}),p.object({body:p.string(),signature:p.string()}),p.object({success:p.boolean(),received:p.boolean().optional(),error:p.string().optional()}),p.object({orgId:p.string().nullable().optional(),amount:p.number().min(0),credits:p.number().min(0),userEmail:p.email(),creditType:Ko.optional(),invoiceType:Vo}),p.object({success:p.boolean(),message:p.string().optional(),error:p.string().optional()}),p.object({orgId:p.string().nullable(),limit:p.number().min(1).max(100).default(10),userId:p.string().min(1),startingAfter:p.string().optional()}),p.object({success:p.boolean(),data:p.object({invoices:p.array(p.object({id:p.string(),status:p.enum(["paid"]),invoicePdf:p.url().nullable(),amountPaid:p.number(),currency:p.string(),credits:p.string(),autoCharged:p.boolean(),createdAt:p.string(),invoiceType:Vo})),hasMore:p.boolean()}).optional(),error:p.string().optional()}),p.object({userId:p.uuid(),orgId:p.uuid().nullable().optional()}),p.object({success:p.boolean(),data:p.object({id:p.string(),orgId:p.string().nullable(),userId:p.string().nullable(),status:Ho,planId:p.string(),priceId:p.string(),quantity:p.number(),currentPeriodEnd:p.string(),cancelAtPeriodEnd:p.boolean(),currentPeriodStart:p.string()}).nullable(),error:p.string().optional()}),p.object({success:p.boolean(),data:p.object({totalGiven:p.number(),limit:p.number(),remaining:p.number()}).optional(),error:p.string().optional()}),p.object({amount:p.number().min(0)}),p.object({success:p.boolean(),totalGiven:p.number().optional(),exceeded:p.boolean().optional(),error:p.string().optional()}),_t(),_t(),_t(),_t(),_t(),_t();var Jo=p.object({name:p.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:p.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:p.string().optional(),compatibility:p.string().max(500,"Skill compatibility must be 500 characters or less").optional(),metadata:p.record(p.string(),p.any()).optional(),"allowed-tools":p.union([p.string(),p.array(p.string())]).optional()});p.object({name:p.string(),description:p.string(),license:p.string().optional(),compatibility:p.string().max(500).optional(),metadata:p.record(p.string(),p.any()).optional(),"allowed-tools":p.union([p.string(),p.array(p.string())]).optional(),content:p.string(),filePath:p.string()}),p.object({name:p.string(),description:p.string(),filePath:p.string()}),_t(),_t(),Ot(),Ot(),Nt(),_t(),_t(),_t(),_t(),_t();var Qo=new Map,Yo=new Map,Zo=Symbol("OriginError"),Xo={},es=class extends Promise{static{__name(this,"Query")}constructor(e,t,n,r,o={}){let s,a;super((e,t)=>{s=e,a=t}),this.tagged=Array.isArray(e.raw),this.strings=e,this.args=t,this.handler=n,this.canceller=r,this.options=o,this.state=null,this.statement=null,this.resolve=e=>(this.active=!1,s(e)),this.reject=e=>(this.active=!1,a(e)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[Zo]=this.handler.debug?new Error:this.tagged&&cachedError(this.strings)}get origin(){return(this.handler.debug?this[Zo].stack:this.tagged&&Yo.has(this.strings)?Yo.get(this.strings):Yo.set(this.strings,this[Zo].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(e=1,t){if(this.options.simple=!1,"function"==typeof e&&(t=e,e=1),this.cursorRows=e,"function"==typeof t)return this.cursorFn=t,this;let n;return{[Symbol.asyncIterator]:()=>({next:__name(()=>{if(this.executed&&!this.active)return{done:!0};n&&n();const e=new Promise((e,t)=>{this.cursorFn=t=>(e({value:t,done:!1}),new Promise(e=>n=e)),this.resolve=()=>(this.active=!1,e({done:!0})),this.reject=e=>(this.active=!1,t(e))});return this.execute(),e},"next"),return:()=>(n&&n(Xo),{done:!0})})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(e){return this.forEachFn=e,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}};function cachedError(e){if(Qo.has(e))return Qo.get(e);const t=Error.stackTraceLimit;return Error.stackTraceLimit=4,Qo.set(e,new Error),Error.stackTraceLimit=t,Qo.get(e)}__name(cachedError,"cachedError"),_t();var ts=class extends Error{static{__name(this,"PostgresError")}constructor(e){super(e.message),this.name=this.constructor.name,Object.assign(this,e)}},ns={connection:connection,postgres:postgres,generic:generic,notSupported:notSupported};function connection(e,t,n){const{host:r,port:o}=n||t,s=Object.assign(new Error("write "+e+" "+(t.path||r+":"+o)),{code:e,errno:e,address:t.path||r},t.path?{}:{port:o});return Error.captureStackTrace(s,connection),s}function postgres(e){const t=new ts(e);return Error.captureStackTrace(t,postgres),t}function generic(e,t){const n=Object.assign(new Error(e+": "+t),{code:e});return Error.captureStackTrace(n,generic),n}function notSupported(e){const t=Object.assign(new Error(e+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:e});return Error.captureStackTrace(t,notSupported),t}__name(connection,"connection"),__name(postgres,"postgres"),__name(generic,"generic"),__name(notSupported,"notSupported");var rs={string:{to:25,from:null,serialize:__name(e=>""+e,"serialize")},number:{to:0,from:[21,23,26,700,701],serialize:__name(e=>""+e,"serialize"),parse:__name(e=>+e,"parse")},json:{to:114,from:[114,3802],serialize:__name(e=>JSON.stringify(e),"serialize"),parse:__name(e=>JSON.parse(e),"parse")},boolean:{to:16,from:16,serialize:__name(e=>!0===e?"t":"f","serialize"),parse:__name(e=>"t"===e,"parse")},date:{to:1184,from:[1082,1114,1184],serialize:__name(e=>(e instanceof Date?e:new Date(e)).toISOString(),"serialize"),parse:__name(e=>new Date(e),"parse")},bytea:{to:17,from:17,serialize:__name(e=>"\\x"+Buffer.from(e).toString("hex"),"serialize"),parse:__name(e=>Buffer.from(e.slice(2),"hex"),"parse")}},os=class{static{__name(this,"NotTagged")}then(){notTagged()}catch(){notTagged()}finally(){notTagged()}},ss=class extends os{static{__name(this,"Identifier")}constructor(e){super(),this.value=ps(e)}},as=class extends os{static{__name(this,"Parameter")}constructor(e,t,n){super(),this.value=e,this.type=t,this.array=n}},cs=class extends os{static{__name(this,"Builder")}constructor(e,t){super(),this.first=e,this.rest=t}build(e,t,n,r){const o=us.map(([t,n])=>({fn:n,i:e.search(t)})).sort((e,t)=>e.i-t.i).pop();return-1===o.i?escapeIdentifiers(this.first,r):o.fn(this.first,this.rest,t,n,r)}};function handleValue(e,t,n,r){let o=e instanceof as?e.value:e;if(void 0===o&&(e instanceof as?e.value=r.transform.undefined:o=e=r.transform.undefined,void 0===o))throw ns.generic("UNDEFINED_VALUE","Undefined values are not allowed");return"$"+n.push(e instanceof as?(t.push(e.value),e.array?e.array[e.type||hs(e.value)]||e.type||firstIsString(e.value):e.type):(t.push(e),hs(e)))}__name(handleValue,"handleValue");var ls=typeHandlers(rs);function stringify(e,t,n,r,o,s){for(let a=1;a<e.strings.length;a++)t+=stringifyValue(t,n,r,o,s)+e.strings[a],n=e.args[a];return t}function stringifyValue(e,t,n,r,o){return t instanceof cs?t.build(e,n,r,o):t instanceof es?fragment(t,n,r,o):t instanceof ss?t.value:t&&t[0]instanceof es?t.reduce((e,t)=>e+" "+fragment(t,n,r,o),""):handleValue(t,n,r,o)}function fragment(e,t,n,r){return e.fragment=!0,stringify(e,e.strings[0],e.args[0],t,n,r)}function valuesBuilder(e,t,n,r,o){return e.map(e=>"("+r.map(r=>stringifyValue("values",e[r],t,n,o)).join(",")+")").join(",")}function values(e,t,n,r,o){const s=Array.isArray(e[0]);return valuesBuilder(s?e:[e],n,r,t.length?t.flat():Object.keys(s?e[0]:e),o)}function select2(e,t,n,r,o){if("string"==typeof e&&(e=[e].concat(t)),Array.isArray(e))return escapeIdentifiers(e,o);let s;return(t.length?t.flat():Object.keys(e)).map(t=>(s=e[t],(s instanceof es?fragment(s,n,r,o):s instanceof ss?s.value:handleValue(s,n,r,o))+" as "+ps(o.transform.column.to?o.transform.column.to(t):t))).join(",")}__name(stringify,"stringify"),__name(stringifyValue,"stringifyValue"),__name(fragment,"fragment"),__name(valuesBuilder,"valuesBuilder"),__name(values,"values"),__name(select2,"select");var us=Object.entries({values:values,in:__name((...e)=>{const t=values(...e);return"()"===t?"(null)":t},"in"),select:select2,as:select2,returning:select2,"\\(":select2,update:(e,t,n,r,o)=>(t.length?t.flat():Object.keys(e)).map(t=>ps(o.transform.column.to?o.transform.column.to(t):t)+"="+stringifyValue("values",e[t],n,r,o)),insert(e,t,n,r,o){const s=t.length?t.flat():Object.keys(Array.isArray(e)?e[0]:e);return"("+escapeIdentifiers(s,o)+")values"+valuesBuilder(Array.isArray(e)?e:[e],n,r,s,o)}}).map(([e,t])=>[new RegExp("((?:^|[\\s(])"+e+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),t]);function notTagged(){throw ns.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}__name(notTagged,"notTagged");var ds=ls.serializers,ms=ls.parsers;function firstIsString(e){return Array.isArray(e)?firstIsString(e[0]):"string"==typeof e?1009:0}__name(firstIsString,"firstIsString");var gs=__name(function(e){const t=typeHandlers(e||{});return{serializers:Object.assign({},ds,t.serializers),parsers:Object.assign({},ms,t.parsers)}},"mergeUserTypes");function typeHandlers(e){return Object.keys(e).reduce((t,n)=>(e[n].from&&[].concat(e[n].from).forEach(r=>t.parsers[r]=e[n].parse),e[n].serialize&&(t.serializers[e[n].to]=e[n].serialize,e[n].from&&[].concat(e[n].from).forEach(r=>t.serializers[r]=e[n].serialize)),t),{parsers:{},serializers:{}})}function escapeIdentifiers(e,{transform:{column:t}}){return e.map(e=>ps(t.to?t.to(e):e)).join(",")}__name(typeHandlers,"typeHandlers"),__name(escapeIdentifiers,"escapeIdentifiers");var ps=__name(function escape(e){return'"'+e.replace(/"/g,'""').replace(/\./g,'"."')+'"'},"escape"),hs=__name(function inferType2(e){return e instanceof as?e.type:e instanceof Date?1184:e instanceof Uint8Array?17:!0===e||!1===e?16:"bigint"==typeof e?20:Array.isArray(e)?inferType2(e[0]):0},"inferType"),fs=/\\/g,ys=/"/g;function arrayEscape(e){return e.replace(fs,"\\\\").replace(ys,'\\"')}__name(arrayEscape,"arrayEscape");var ws=__name(function arraySerializer2(e,t,n,r){if(!1===Array.isArray(e))return e;if(!e.length)return"{}";const o=e[0],s=1020===r?";":",";return Array.isArray(o)&&!o.type?"{"+e.map(e=>arraySerializer2(e,t,n,r)).join(s)+"}":"{"+e.map(e=>{if(void 0===e&&void 0===(e=n.transform.undefined))throw ns.generic("UNDEFINED_VALUE","Undefined values are not allowed");return null===e?"null":'"'+arrayEscape(t?t(e.type?e.value:e):""+e)+'"'}).join(s)+"}"},"arraySerializer"),Es={i:0,char:null,str:"",quoted:!1,last:0},bs=__name(function arrayParser2(e,t,n){return Es.i=Es.last=0,arrayParserLoop(Es,e,t,n)},"arrayParser");function arrayParserLoop(e,t,n,r){const o=[],s=1020===r?";":",";for(;e.i<t.length;e.i++){if(e.char=t[e.i],e.quoted)"\\"===e.char?e.str+=t[++e.i]:'"'===e.char?(o.push(n?n(e.str):e.str),e.str="",e.quoted='"'===t[e.i+1],e.last=e.i+2):e.str+=e.char;else if('"'===e.char)e.quoted=!0;else if("{"===e.char)e.last=++e.i,o.push(arrayParserLoop(e,t,n,r));else{if("}"===e.char){e.quoted=!1,e.last<e.i&&o.push(n?n(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1;break}e.char===s&&"}"!==e.p&&'"'!==e.p&&(o.push(n?n(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1)}e.p=e.char}return e.last<e.i&&o.push(n?n(t.slice(e.last,e.i+1)):t.slice(e.last,e.i+1)),o}__name(arrayParserLoop,"arrayParserLoop");var Ss=__name(e=>{let t=e[0];for(let n=1;n<e.length;n++)t+="_"===e[n]?e[++n].toUpperCase():e[n];return t},"toCamel"),vs=__name(e=>{let t=e[0].toUpperCase();for(let n=1;n<e.length;n++)t+="_"===e[n]?e[++n].toUpperCase():e[n];return t},"toPascal"),Cs=__name(e=>e.replace(/_/g,"-"),"toKebab"),ks=__name(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase(),"fromCamel"),Ps=__name(e=>(e.slice(0,1)+e.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),"fromPascal"),Ts=__name(e=>e.replace(/-/g,"_"),"fromKebab");function createJsonTransform(e){return __name(function jsonTransform(t,n){return"object"!=typeof t||null===t||114!==n.type&&3802!==n.type?t:Array.isArray(t)?t.map(e=>jsonTransform(e,n)):Object.entries(t).reduce((t,[r,o])=>Object.assign(t,{[e(r)]:jsonTransform(o,n)}),{})},"jsonTransform")}__name(createJsonTransform,"createJsonTransform"),Ss.column={from:Ss},Ss.value={from:createJsonTransform(Ss)},ks.column={to:ks};var As={...Ss};As.column.to=ks,vs.column={from:vs},vs.value={from:createJsonTransform(vs)},Ps.column={to:Ps};var xs={...vs};xs.column.to=Ps,Cs.column={from:Cs},Cs.value={from:createJsonTransform(Cs)},Ts.column={to:Ts};var Is={...Cs};Is.column.to=Ts,_t(),_t();var _s=class extends Array{static{__name(this,"Result")}constructor(){super(),Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}};_t();var Ns=Queue;function Queue(e=[]){let t=e.slice(),n=0;return{get length(){return t.length-n},remove:__name(e=>{const n=t.indexOf(e);return-1===n?null:(t.splice(n,1),e)},"remove"),push:__name(e=>(t.push(e),e),"push"),shift:__name(()=>{const e=t[n++];return n===t.length?(n=0,t=[]):t[n-1]=void 0,e},"shift")}}__name(Queue,"Queue"),_t();var $s=Buffer.allocUnsafe(256),Rs="BCcDdEFfHPpQSX".split("").reduce((e,t)=>{const n=t.charCodeAt(0);return e[t]=()=>($s[0]=n,Ds.i=5,Ds),e},{}),Ds=Object.assign(reset,Rs,{N:String.fromCharCode(0),i:0,inc:e=>(Ds.i+=e,Ds),str(e){const t=Buffer.byteLength(e);return fit(t),Ds.i+=$s.write(e,Ds.i,t,"utf8"),Ds},i16:e=>(fit(2),$s.writeUInt16BE(e,Ds.i),Ds.i+=2,Ds),i32:(e,t)=>t||0===t?($s.writeUInt32BE(e,t),Ds):(fit(4),$s.writeUInt32BE(e,Ds.i),Ds.i+=4,Ds),z:e=>(fit(e),$s.fill(0,Ds.i,Ds.i+e),Ds.i+=e,Ds),raw:e=>($s=Buffer.concat([$s.subarray(0,Ds.i),e]),Ds.i=$s.length,Ds),end(e=1){$s.writeUInt32BE(Ds.i-e,e);const t=$s.subarray(0,Ds.i);return Ds.i=0,$s=Buffer.allocUnsafe(256),t}}),Os=Ds;function fit(e){if($s.length-Ds.i<e){const t=$s,n=t.length;$s=Buffer.allocUnsafe(n+(n>>1)+e),t.copy($s)}}function reset(){return Ds.i=0,Ds}__name(fit,"fit"),__name(reset,"reset");var Ls=Connection,Ms=1,Fs=Os().S().end(),Us=Os().H().end(),js=Os().i32(8).i32(80877103).end(8),Bs=Buffer.concat([Os().E().str(Os.N).i32(0).end(),Fs]),qs=Os().D().str("S").str(Os.N).end(),zs=__name(()=>{},"noop"),Ws=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Hs={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function Connection(e,t={},{onopen:n=zs,onend:r=zs,onclose:o=zs}={}){const{sslnegotiation:s,ssl:a,max:i,user:l,host:u,port:d,database:m,parsers:g,transform:p,onnotice:h,onnotify:f,onparameter:y,max_pipeline:w,keep_alive:E,backoff:b,target_session_attrs:S}=e,v=Ns(),C=Ms++,k={pid:null,secret:null},P=timer(end,e.idle_timeout),T=timer(end,e.max_lifetime),A=timer(function connectTimedOut(){errored(ns.connection("CONNECT_TIMEOUT",e,I)),I.destroy()},e.connect_timeout);let x,I=null,_=null,N=new _s,$=Buffer.alloc(0),R=e.fetch_types,D={},O={},L=Math.random().toString(36).slice(2),M=1,F=0,U=0,B=0,q=0,z=0,W=0,H=0,V=null,G=null,K=!1,J=null,Q=null,Y=null,Z=null,X=null,ee=null,te=null,ne=null,re=null,oe=null;const se={queue:t.closed,idleTimer:P,connect(e){Y=e,reconnect()},terminate:terminate,execute:execute,cancel:async function cancel5({pid:e,secret:t},n,r){try{x=Os().i32(16).i32(80877102).i32(e).i32(t).end(16),await connect(),I.once("error",r),I.once("close",n)}catch(e){r(e)}},end:end,count:0,id:C};return t.closed&&t.closed.push(se),se;function execute(t){if(K)return queryError(t,ns.connection("CONNECTION_DESTROYED",e));if(X)return queryError(t,ns.generic("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(!t.cancelled)try{return t.state=k,re?v.push(t):(re=t,re.active=!0),function build(t){const n=[],r=[],o=stringify(t,t.strings[0],t.args[0],n,r,e);!t.tagged&&t.args.forEach(t=>handleValue(t,n,r,e)),t.prepare=e.prepare&&(!("prepare"in t.options)||t.options.prepare),t.string=o,t.signature=t.prepare&&r+o,t.onlyDescribe&&delete O[t.signature],t.parameters=t.parameters||n,t.prepared=t.prepare&&t.signature in O,t.describeFirst=t.onlyDescribe||n.length&&!t.prepared,t.statement=t.prepared?O[t.signature]:{string:o,types:r,name:t.prepare?L+M++:""},"function"==typeof e.debug&&e.debug(C,o,n,r)}(t),write(function toBuffer(e){if(e.parameters.length>=65534)throw ns.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return e.options.simple?Os().Q().str(e.statement.string+Os.N).end():e.describeFirst?Buffer.concat([describe(e),Us]):e.prepare?e.prepared?prepared(e):Buffer.concat([describe(e),prepared(e)]):function unnamed(e){return Buffer.concat([Parse(e.statement.string,e.parameters,e.statement.types),qs,prepared(e)])}(e)}(t))&&!t.describeFirst&&!t.cursorFn&&v.length<w&&(!t.options.onexecute||t.options.onexecute(se))}catch(e){return 0===v.length&&write(Fs),errored(e),!0}}function describe(e){return Buffer.concat([Parse(e.statement.string,e.parameters,e.statement.types,e.statement.name),Describe("S",e.statement.name)])}function prepared(e){return Buffer.concat([Bind(e.parameters,e.statement.types,e.statement.name,e.cursorName),e.cursorFn?Execute("",e.cursorRows):Bs])}function write(e,t){return ee=ee?Buffer.concat([ee,e]):Buffer.from(e),ee.length>=1024?nextWrite(t):(null===G&&(G=setImmediate(nextWrite)),!0)}function nextWrite(e){const t=I.write(ee,e);return null!==G&&clearImmediate(G),ee=G=null,t}async function secure(){if("direct"!==s&&(write(js),!await new Promise(e=>I.once("data",t=>e(83===t[0])))&&"prefer"===a))return connected();const e={socket:I,servername:ye.isIP(I.host)?void 0:I.host};"direct"===s&&(e.ALPNProtocols=["postgresql"]),"require"===a||"allow"===a||"prefer"===a?e.rejectUnauthorized=!1:"object"==typeof a&&Object.assign(e,a),I.removeAllListeners(),I=Le.connect(e),I.on("secureConnect",connected),I.on("error",error),I.on("close",closed),I.on("drain",drain)}function drain(){!re&&n(se)}function data(e){if(!(J&&(J.push(e),U-=e.length,U>0)))for($=J?Buffer.concat(J,z-U):0===$.length?e:Buffer.concat([$,e],$.length+e.length);$.length>4;){if(z=$.readUInt32BE(1),z>=$.length){U=z-$.length,J=[$];break}try{handle($.subarray(0,z+1))}catch(e){re&&(re.cursorFn||re.describeFirst)&&write(Fs),errored(e)}$=$.subarray(z+1),U=0,J=null}}async function connect(){if(K=!1,D={},I||(I=await async function createSocket(){let t;try{t=e.socket?await Promise.resolve(e.socket(e)):new ye.Socket}catch(e){return void error(e)}return t.on("error",error),t.on("close",closed),t.on("drain",drain),t}()),I){if(A.start(),e.socket)return a?secure():connected();if(I.on("connect",a?secure:connected),e.path)return I.connect(e.path);I.ssl=a,I.connect(d[B],u[B]),I.host=u[B],I.port=d[B],B=(B+1)%d.length}}function reconnect(){setTimeout(connect,F?Math.max(0,F+W-Fe.now()):0)}function connected(){try{O={},R=e.fetch_types,L=Math.random().toString(36).slice(2),M=1,T.start(),I.on("data",data),E&&I.setKeepAlive&&I.setKeepAlive(!0,1e3*E),write(function StartupMessage(){return x||Os().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:l,database:m,client_encoding:"UTF8"},e.connection)).filter(([,e])=>e).map(([e,t])=>e+Os.N+t).join(Os.N)).z(2).end(0)}())}catch(e){error(e)}}function error(n){if(se.queue!==t.connecting||!e.host[q+1])for(errored(n);v.length;)queryError(v.shift(),n)}function errored(e){X&&(X.destroy(e),X=null),re&&queryError(re,e),Y&&(queryError(Y,e),Y=null)}function queryError(t,n){if(t.reserve)return t.reject(n);n&&"object"==typeof n||(n=new Error(n)),"query"in n||"parameters"in n||Object.defineProperties(n,{stack:{value:n.stack+t.origin.replace(/.*\n/,"\n"),enumerable:e.debug},query:{value:t.string,enumerable:e.debug},parameters:{value:t.parameters,enumerable:e.debug},args:{value:t.args,enumerable:e.debug},types:{value:t.statement&&t.statement.types,enumerable:e.debug}}),t.reject(n)}function end(){return Z||(!se.reserved&&r(se),se.reserved||Y||re||0!==v.length?Z=new Promise(e=>te=e):(terminate(),new Promise(e=>I&&"closed"!==I.readyState?I.once("close",e):e())))}function terminate(){K=!0,(X||re||Y||v.length)&&error(ns.connection("CONNECTION_DESTROYED",e)),clearImmediate(G),I&&(I.removeListener("data",data),I.removeListener("connect",connected),"open"===I.readyState&&I.end(Os().X().end())),te&&(te(),Z=te=null)}async function closed(t){if($=Buffer.alloc(0),U=0,J=null,clearImmediate(G),I.removeListener("data",data),I.removeListener("connect",connected),P.cancel(),T.cancel(),A.cancel(),I.removeAllListeners(),I=null,Y)return reconnect();!t&&(re||v.length)&&error(ns.connection("CONNECTION_CLOSED",e,I)),F=Fe.now(),t&&e.shared.retries++,W=1e3*("function"==typeof b?b(e.shared.retries):b),o(se,ns.connection("CONNECTION_CLOSED",e,I))}function handle(e,t=e[0]){(68===t?DataRow:100===t?CopyData:65===t?NotificationResponse:83===t?ParameterStatus:90===t?ReadyForQuery:67===t?CommandComplete:50===t?BindComplete:49===t?ParseComplete:116===t?ParameterDescription:84===t?RowDescription:82===t?Authentication:110===t?NoData:75===t?BackendKeyData:69===t?ErrorResponse:115===t?PortalSuspended:51===t?CloseComplete:71===t?CopyInResponse:78===t?NoticeResponse:72===t?CopyOutResponse:99===t?CopyDone:73===t?EmptyQueryResponse:86===t?FunctionCallResponse:118===t?NegotiateProtocolVersion:87===t?CopyBothResponse:UnknownMessage)(e)}function DataRow(e){let t,n,r,o=7;const s=re.isRaw?new Array(re.statement.columns.length):{};for(let a=0;a<re.statement.columns.length;a++)n=re.statement.columns[a],t=e.readInt32BE(o),o+=4,r=-1===t?null:!0===re.isRaw?e.subarray(o,o+=t):void 0===n.parser?e.toString("utf8",o,o+=t):!0===n.parser.array?n.parser(e.toString("utf8",o+1,o+=t)):n.parser(e.toString("utf8",o,o+=t)),re.isRaw?s[a]=!0===re.isRaw?r:p.value.from?p.value.from(r,n):r:s[n.name]=p.value.from?p.value.from(r,n):r;re.forEachFn?re.forEachFn(p.row.from?p.row.from(s):s,N):N[H++]=p.row.from?p.row.from(s):s}function ParameterStatus(t){const[n,r]=t.toString("utf8",5,t.length-1).split(Os.N);D[n]=r,e.parameters[n]!==r&&(e.parameters[n]=r,y&&y(n,r))}function ReadyForQuery(t){if(re?_?re.retried?errored(re.retried):re.prepared&&Ws.has(_.routine)?function retry(e,t){delete O[e.signature],e.retried=t,execute(e)}(re,_):errored(_):re.resolve(Q||N):_&&errored(_),re=Q=_=null,N=new _s,A.cancel(),Y){if(S){if(!D.in_hot_standby||!D.default_transaction_read_only)return function fetchState(){const e=new es(["\n show transaction_read_only;\n select pg_catalog.pg_is_in_recovery()\n "],[],execute,null,{simple:!0});e.resolve=([[e],[t]])=>{D.default_transaction_read_only=e.transaction_read_only,D.in_hot_standby=t.pg_is_in_recovery?"on":"off"},e.execute()}();if(function tryNext(t,n){return"read-write"===t&&"on"===n.default_transaction_read_only||"read-only"===t&&"off"===n.default_transaction_read_only||"primary"===t&&"on"===n.in_hot_standby||"standby"===t&&"off"===n.in_hot_standby||"prefer-standby"===t&&"off"===n.in_hot_standby&&e.host[q]}(S,D))return terminate()}return R?(Y.reserve&&(Y=null),async function fetchArrayTypes(){R=!1,(await new es(["\n select b.oid, b.typarray\n from pg_catalog.pg_type a\n left join pg_catalog.pg_type b on b.oid = a.typelem\n where a.typcategory = 'A'\n group by b.oid, b.typarray\n order by b.oid\n "],[],execute)).forEach(({oid:t,typarray:n})=>function addArrayType(t,n){if(e.parsers[n]&&e.serializers[n])return;const r=e.parsers[t];e.shared.typeArrayMap[t]=n,e.parsers[n]=e=>bs(e,r,n),e.parsers[n].array=!0,e.serializers[n]=r=>ws(r,e.serializers[t],e,n)}(t,n))}()):(Y&&!Y.reserve&&execute(Y),e.shared.retries=q=0,void(Y=null))}for(;v.length&&(re=v.shift())&&(re.active=!0,re.cancelled);)Connection(e).cancel(re.state,re.cancelled.resolve,re.cancelled.reject);re||(se.reserved?se.reserved.release||73!==t[5]?se.reserved():Z?terminate():(se.reserved=null,n(se)):Z?terminate():n(se))}function CommandComplete(e){H=0;for(let t=e.length-1;t>0;t--)if(32===e[t]&&e[t+1]<58&&null===N.count&&(N.count=+e.toString("utf8",t+1,e.length-1)),e[t-1]>=65){N.command=e.toString("utf8",5,t),N.state=k;break}return oe&&(oe(),oe=null),"BEGIN"!==N.command||1===i||se.reserved?re.options.simple?BindComplete():void(re.cursorFn&&(N.count&&re.cursorFn(N),write(Fs))):errored(ns.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"))}function ParseComplete(){re.parsing=!1}function BindComplete(){!N.statement&&(N.statement=re.statement),N.columns=re.statement.columns}function ParameterDescription(e){const t=e.readUInt16BE(5);for(let n=0;n<t;++n)!re.statement.types[n]&&(re.statement.types[n]=e.readUInt32BE(7+4*n));re.prepare&&(O[re.signature]=re.statement),re.describeFirst&&!re.onlyDescribe&&(write(prepared(re)),re.describeFirst=!1)}function RowDescription(e){N.command&&(Q=Q||[N],Q.push(N=new _s),N.count=null,re.statement.columns=null);const t=e.readUInt16BE(5);let n,r=7;re.statement.columns=Array(t);for(let o=0;o<t;++o){for(n=r;0!==e[r++];);const t=e.readUInt32BE(r),s=e.readUInt16BE(r+4),a=e.readUInt32BE(r+6);re.statement.columns[o]={name:p.column.from?p.column.from(e.toString("utf8",n,r-1)):e.toString("utf8",n,r-1),parser:g[a],table:t,number:s,type:a},r+=18}if(N.statement=re.statement,re.onlyDescribe)return re.resolve(re.statement),write(Fs)}async function Authentication(e,t=e.readUInt32BE(5)){(3===t?AuthenticationCleartextPassword:5===t?AuthenticationMD5Password:10===t?SASL:11===t?SASLContinue:12===t?SASLFinal:0!==t?UnknownAuth:zs)(e,t)}async function AuthenticationCleartextPassword(){const e=await Pass();write(Os().p().str(e).z(1).end())}async function AuthenticationMD5Password(e){const t="md5"+await md5(Buffer.concat([Buffer.from(await md5(await Pass()+l)),e.subarray(9)]));write(Os().p().str(t).z(1).end())}async function SASL(){ne=(await j.randomBytes(18)).toString("base64"),Os().p().str("SCRAM-SHA-256"+Os.N);const e=Os.i;write(Os.inc(4).str("n,,n=*,r="+ne).i32(Os.i-e-4,e).end())}async function SASLContinue(e){const t=e.toString("utf8",9).split(",").reduce((e,t)=>(e[t[0]]=t.slice(2),e),{}),n=await j.pbkdf2Sync(await Pass(),Buffer.from(t.s,"base64"),parseInt(t.i),32,"sha256"),r=await hmac(n,"Client Key"),o="n=*,r="+ne+",r="+t.r+",s="+t.s+",i="+t.i+",c=biws,r="+t.r;V=(await hmac(await hmac(n,"Server Key"),o)).toString("base64");const s="c=biws,r="+t.r+",p="+xor(r,Buffer.from(await hmac(await sha256(r),o))).toString("base64");write(Os().p().str(s).end())}function SASLFinal(e){e.toString("utf8",9).split(Os.N,1)[0].slice(2)!==V&&(errored(ns.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),I.destroy())}function Pass(){return Promise.resolve("function"==typeof e.pass?e.pass():e.pass)}function NoData(){if(N.statement=re.statement,N.statement.columns=[],re.onlyDescribe)return re.resolve(re.statement),write(Fs)}function BackendKeyData(e){k.pid=e.readUInt32BE(5),k.secret=e.readUInt32BE(9)}function ErrorResponse(e){re?((re.cursorFn||re.describeFirst)&&write(Fs),_=ns.postgres(parseError(e))):errored(ns.postgres(parseError(e)))}function NotificationResponse(e){if(!f)return;let t=9;for(;0!==e[t++];);f(e.toString("utf8",9,t-1),e.toString("utf8",t,e.length-1))}async function PortalSuspended(){try{const e=await Promise.resolve(re.cursorFn(N));H=0,e===Xo?write(function Close(e=""){return Buffer.concat([Os().C().str("P").str(e+Os.N).end(),Os().S().end()])}(re.portal)):(N=new _s,write(Execute("",re.cursorRows)))}catch(e){write(Fs),re.reject(e)}}function CloseComplete(){N.count&&re.cursorFn(N),re.resolve(N)}function CopyInResponse(){X=new Me.Writable({autoDestroy:!0,write(e,t,n){I.write(Os().d().raw(e).end(),n)},destroy(e,t){t(e),I.write(Os().f().str(e+Os.N).end()),X=null},final(e){I.write(Os().c().end()),oe=e,X=null}}),re.resolve(X)}function CopyOutResponse(){X=new Me.Readable({read(){I.resume()}}),re.resolve(X)}function CopyBothResponse(){X=new Me.Duplex({autoDestroy:!0,read(){I.resume()},write(e,t,n){I.write(Os().d().raw(e).end(),n)},destroy(e,t){t(e),I.write(Os().f().str(e+Os.N).end()),X=null},final(e){I.write(Os().c().end()),oe=e}}),re.resolve(X)}function CopyData(e){X&&(X.push(e.subarray(5))||I.pause())}function CopyDone(){X&&X.push(null),X=null}function NoticeResponse(e){h?h(parseError(e)):console.log(parseError(e))}function EmptyQueryResponse(){}function FunctionCallResponse(){errored(ns.notSupported("FunctionCallResponse"))}function NegotiateProtocolVersion(){errored(ns.notSupported("NegotiateProtocolVersion"))}function UnknownMessage(e){console.error("Postgres.js : Unknown Message:",e[0])}function UnknownAuth(e,t){console.error("Postgres.js : Unknown Auth:",t)}function Bind(t,n,r="",o=""){let s,a;return Os().B().str(o+Os.N).str(r+Os.N).i16(0).i16(t.length),t.forEach((r,o)=>{if(null===r)return Os.i32(4294967295);a=n[o],t[o]=r=a in e.serializers?e.serializers[a](r):""+r,s=Os.i,Os.inc(4).str(r).i32(Os.i-s-4,s)}),Os.i16(0),Os.end()}function Parse(e,t,n,r=""){return Os().P().str(r+Os.N).str(e+Os.N).i16(t.length),t.forEach((e,t)=>Os.i32(n[t]||0)),Os.end()}function Describe(e,t=""){return Os().D().str(e).str(t+Os.N).end()}function Execute(e="",t=0){return Buffer.concat([Os().E().str(e+Os.N).i32(t).end(),Us])}}function parseError(e){const t={};let n=5;for(let r=5;r<e.length-1;r++)0===e[r]&&(t[Hs[e[n]]]=e.toString("utf8",n+1,r),n=r+1);return t}function md5(e){return j.createHash("md5").update(e).digest("hex")}function hmac(e,t){return j.createHmac("sha256",e).update(t).digest()}function sha256(e){return j.createHash("sha256").update(e).digest()}function xor(e,t){const n=Math.max(e.length,t.length),r=Buffer.allocUnsafe(n);for(let o=0;o<n;o++)r[o]=e[o]^t[o];return r}function timer(e,t){if(!(t="function"==typeof t?t():t))return{cancel:zs,start:zs};let n;return{cancel(){n&&(clearTimeout(n),n=null)},start(){n&&clearTimeout(n),n=setTimeout(done,1e3*t,arguments)}};function done(t){e.apply(null,t),n=null}}__name(Connection,"Connection"),__name(parseError,"parseError"),__name(md5,"md5"),__name(hmac,"hmac"),__name(sha256,"sha256"),__name(xor,"xor"),__name(timer,"timer"),_t();var Vs=__name(()=>{},"noop");function Subscribe(e,t){const n=new Map,r="postgresjs_"+Math.random().toString(36).slice(2),o={};let s,a,i=!1;const l=subscribe.sql=e({...t,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...t.connection,replication:"database"},onclose:__name(async function(){i||(a=null,o.pid=o.secret=void 0,connected(await init(l,r,t.publications)),n.forEach(e=>e.forEach(({onsubscribe:e})=>e())))},"onclose"),no_subscribe:!0}),u=l.end,d=l.close;return l.end=async()=>(i=!0,a&&await new Promise(e=>(a.once("close",e),a.end())),u()),l.close=async()=>(a&&await new Promise(e=>(a.once("close",e),a.end())),d()),subscribe;async function subscribe(e,i,u=Vs,d=Vs){e=parseEvent(e),s||(s=init(l,r,t.publications));const m={fn:i,onsubscribe:u},g=n.has(e)?n.get(e).add(m):n.set(e,new Set([m])).get(e),p=__name(()=>{g.delete(m),0===g.size&&n.delete(e)},"unsubscribe");return s.then(e=>(connected(e),u(),a&&a.on("error",d),{unsubscribe:p,state:o,sql:l}))}function connected(e){a=e.stream,o.pid=e.state.pid,o.secret=e.state.secret}async function init(e,n,r){if(!r)throw new Error("Missing publication names");const o=await e.unsafe(`CREATE_REPLICATION_SLOT ${n} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[s]=o,a=await e.unsafe(`START_REPLICATION SLOT ${n} LOGICAL ${s.consistent_point} (proto_version '1', publication_names '${r}')`).writable(),i={lsn:Buffer.concat(s.consistent_point.split("/").map(e=>Buffer.from(("00000000"+e).slice(-8),"hex")))};return a.on("data",function data(n){119===n[0]?parse(n.subarray(25),i,e.options.parsers,handle,t.transform):107===n[0]&&n[17]&&(i.lsn=n.subarray(1,9),function pong(){const e=Buffer.alloc(34);e[0]="r".charCodeAt(0),e.fill(i.lsn,1),e.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2e3,0,1))*BigInt(1e3),25),a.write(e)}())}),a.on("error",function error(e){console.error("Unexpected error during logical streaming - reconnecting",e)}),a.on("close",e.close),{stream:a,state:o.state};function handle(e,t){const n=t.relation.schema+"."+t.relation.table;call("*",e,t),call("*:"+n,e,t),t.relation.keys.length&&call("*:"+n+"="+t.relation.keys.map(t=>e[t.name]),e,t),call(t.command,e,t),call(t.command+":"+n,e,t),t.relation.keys.length&&call(t.command+":"+n+"="+t.relation.keys.map(t=>e[t.name]),e,t)}}function call(e,t,r){n.has(e)&&n.get(e).forEach(({fn:n})=>n(t,r,e))}}function Time(e){return new Date(Date.UTC(2e3,0,1)+Number(e/BigInt(1e3)))}function parse(e,t,n,r,o){const s=__name((e,[t,n])=>(e[t.charCodeAt(0)]=n,e),"char");Object.entries({R:__name(e=>{let r=1;const s=t[e.readUInt32BE(r)]={schema:e.toString("utf8",r+=4,r=e.indexOf(0,r))||"pg_catalog",table:e.toString("utf8",r+1,r=e.indexOf(0,r+1)),columns:Array(e.readUInt16BE(r+=2)),keys:[]};r+=2;let a,i=0;for(;r<e.length;)a=s.columns[i++]={key:e[r++],name:o.column.from?o.column.from(e.toString("utf8",r,r=e.indexOf(0,r))):e.toString("utf8",r,r=e.indexOf(0,r)),type:e.readUInt32BE(r+=1),parser:n[e.readUInt32BE(r)],atttypmod:e.readUInt32BE(r+=4)},a.key&&s.keys.push(a),r+=4},"R"),Y:__name(()=>{},"Y"),O:__name(()=>{},"O"),B:__name(e=>{t.date=Time(e.readBigInt64BE(9)),t.lsn=e.subarray(1,9)},"B"),I:__name(e=>{let n=1;const s=t[e.readUInt32BE(n)],{row:a}=tuples(e,s.columns,n+=7,o);r(a,{command:"insert",relation:s})},"I"),D:__name(e=>{let n=1;const s=t[e.readUInt32BE(n)];n+=4;const a=75===e[n];r(a||79===e[n]?tuples(e,s.columns,n+=3,o).row:null,{command:"delete",relation:s,key:a})},"D"),U:__name(e=>{let n=1;const s=t[e.readUInt32BE(n)];n+=4;const a=75===e[n],i=a||79===e[n]?tuples(e,s.columns,n+=3,o):null;i&&(n=i.i);const{row:l}=tuples(e,s.columns,n+3,o);r(l,{command:"update",relation:s,key:a,old:i&&i.row})},"U"),T:__name(()=>{},"T"),C:__name(()=>{},"C")}).reduce(s,{})[e[0]](e)}function tuples(e,t,n,r){let o,s,a;const i=r.raw?new Array(t.length):{};for(let l=0;l<t.length;l++)o=e[n++],s=t[l],a=110===o?null:117===o?void 0:void 0===s.parser?e.toString("utf8",n+4,n+=4+e.readUInt32BE(n)):!0===s.parser.array?s.parser(e.toString("utf8",n+5,n+=4+e.readUInt32BE(n))):s.parser(e.toString("utf8",n+4,n+=4+e.readUInt32BE(n))),r.raw?i[l]=!0===r.raw?a:r.value.from?r.value.from(a,s):a:i[s.name]=r.value.from?r.value.from(a,s):a;return{i:n,row:r.row.from?r.row.from(i):i}}function parseEvent(e){const t=e.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!t)throw new Error("Malformed subscribe pattern: "+e);const[,n,r,o]=t;return(n||"*")+(r?":"+(-1===r.indexOf(".")?"public."+r:r):"")+(o?"="+o:"")}function largeObject(e,t,n=393216){return new Promise(async(r,o)=>{await e.begin(async e=>{let o;!t&&([{oid:t}]=await(e`select lo_creat(-1) as oid`));const[{fd:s}]=await(e`select lo_open(${t}, ${n}) as fd`),a={writable:async function writable({highWaterMark:e=16384,start:t=0}={}){return t&&await a.seek(t),new Me.Writable({highWaterMark:e,write(e,t,n){a.write(e).then(()=>n(),n)}})},readable:async function readable({highWaterMark:e=16384,start:t=0,end:n=1/0}={}){let r=n-t;return t&&await a.seek(t),new Me.Readable({highWaterMark:e,async read(e){const t=e>r?e-r:e;r-=e;const[{data:n}]=await a.read(t);this.push(n),n.length<e&&this.push(null)}})},close:__name(()=>e`select lo_close(${s})`.then(o),"close"),tell:__name(()=>e`select lo_tell64(${s})`,"tell"),read:__name(t=>e`select loread(${s}, ${t}) as data`,"read"),write:__name(t=>e`select lowrite(${s}, ${t})`,"write"),truncate:__name(t=>e`select lo_truncate64(${s}, ${t})`,"truncate"),seek:__name((t,n=0)=>e`select lo_lseek64(${s}, ${t}, ${n})`,"seek"),size:__name(()=>e`
|
|
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=fe.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}Sr(),__name(handleUnhandledErrors,"handleUnhandledErrors"),_t(),_t(),Ot(),_t(),_t(),Ot(),_t(),_t(),_t(),_t(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable");var Zr=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=he.createServer((e,o)=>{const a=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],i=e.headers.origin||"",l=a.includes(i)?i:a[0];if(o.setHeader("Access-Control-Allow-Origin",l),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 u="";e.on("data",t=>{u+=t.toString(),u.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(u);if(e.error){const t=e,n={success:!0};return o.writeHead(200),o.end(JSON.stringify(n)),"access_denied"===t.error?r(new Zr(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 U.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await se(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:hr.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(Rt()){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"),Lt(),Ut(),Sr(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl");var Xr=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 R.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 R.writeFile(n,r,{mode:384}),await R.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await R.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"),_t(),__name(getApiBaseUrl,"getApiBaseUrl"),Ot(),Sr();var eo=12e4;async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${wt.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:hr.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=eo}=e,[s,a]=z("initializing"),[i,l]=z("Starting authentication..."),[u,d]=z(""),[m,g]=z(null),p=W(null),h=W(!1),f=W(!1),y=W(null),w=W(t),E=W(n),b=W(r);H(()=>{w.current=t,E.current=n,b.current=r});const S=V(()=>{y.current&&(clearTimeout(y.current),y.current=null),p.current&&(stopServer(p.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),p.current=null)},[]),v=V(()=>{f.current||(f.current=!0,h.current=!0,S(),b.current())},[S]),C=V((e,t)=>{f.current||(f.current=!0,S(),w.current(e,t))},[S]),k=V((e,t)=>{f.current||(f.current=!0,S(),E.current(e,t))},[S]),P=V(async e=>{const t=sanitizeApiKey(e);if(!t)return;a("validating"),l("Validating API key...");const n=await validateApiKey(t);if(h.current)return;if(f.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return a("invalid_key"),l(e),void(y.current=setTimeout(()=>{h.current||f.current||(a("manual_entry"),l("Paste a valid API key below.")),y.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(f.current)return;await storeCredentials(e),a("success"),C(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:hr.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),l("Failed to save API key. Please try again."),a("manual_entry")}},[C]);return H(()=>{let e=!0;return __name(async()=>{if(!h.current)try{const t=await findAvailablePort(5959,10);if(!e||h.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);g(r);const{server:s,waitForCallback:i}=createAuthServer(t,n);if(p.current=s,!e||h.current)return void await stopServer(s);a("waiting_browser"),l("Opening browser for authentication...");const u=await openBrowser(r);if(!e||h.current)return;if(!u)return S(),l("Could not open browser. Paste your API key below."),void a("manual_entry");l("Complete login in your browser...");const d=new Promise((e,t)=>{setTimeout(()=>{t(new Xr("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([i,d]);if(!e||h.current)return;if(f.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(f.current)return;if(await storeCredentials(n),!e||h.current||f.current)return;a("browser_success"),C(n,"browser")}catch(t){if(f.current)return;if(!e||h.current)return;if(t instanceof Zr)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:hr.AUTH_FLOW,heading:"Authorization denied by user"}}),a("denied"),void k("denied","Authorization denied by user.");S(),t instanceof Xr&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:hr.AUTH_FLOW,heading:"Browser auth timed out"}}),l("Browser auth timed out. Paste your API key below.")):(trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_failed"}),context:{component:hr.AUTH_FLOW,heading:"Browser auth failed"}}),l("Browser auth failed. Paste your API key below.")),a("manual_entry")}}catch(t){if(f.current)return;if(!e||h.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:hr.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),S(),a("manual_entry"),l("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,S()}},[o,C,k,S]),{authState:s,statusMessage:i,browserUrl:m,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:P,cancel:v,hasCompleted:f.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"),_t(),En(),Ot(),Lt(),_t(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel");var to=__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 q.createElement(Re,{type:"dots"});case"browser_success":case"success":return q.createElement(J,{color:"green"},Se.tick);case"denied":case"invalid_key":return q.createElement(J,{color:"red"},Se.cross);case"manual_entry":return q.createElement(J,{color:"yellow"},Se.arrowDown);case"error":return q.createElement(J,{color:"red"},Se.warning)}},"getStatusIcon"),i=__name(()=>getAuthStatusColor(e),"getStatusColor");if("browser_success"===e||"success"===e||"denied"===e)return null;const l="initializing"===e||"waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,u=n&&("waiting_browser"===e||"manual_entry"===e);return q.createElement(K,{flexDirection:"column",paddingY:1},q.createElement(K,{marginBottom:1},q.createElement(K,{marginRight:1},a()),q.createElement(J,{color:i()},t)),l&&q.createElement(K,{flexDirection:"column"},q.createElement(K,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?"yellow":"gray",paddingX:1},q.createElement(J,{dimColor:!0},"API Key: "),q.createElement(K,{flexGrow:1},q.createElement(TextInput,{value:r,onChange:o,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},getAuthHelpText(e))),u&&q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,{dimColor:!0},getAuthUrlLabel(e)),q.createElement(J,{color:"cyan",dimColor:!0},n||getStudioAuthUrl(Rt())))),"validating"===e&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"initializing"===e||"invalid_key"===e)&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Ctrl+C to cancel")))},"AuthFlowUI"),no=__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 X((e,t)=>{t.ctrl&&"c"===e&&i()}),q.createElement(to,{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?`${re.bgGreen(re.black(` ${e} `))}${o}`:n?`${re.bgBlack(re.white(` ${e} `))}${o}`:`${re.bold(re.bgCyan(re.black(` ${e} `)))}${o}`}async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=rn.createAuthorizationUrl(),r=await Ne({message:"Open the Anthropic auth page?"});if(Ie(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await se(e),console.log(),console.log(re.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(re.dim(" Open this URL in your browser:")),console.log(),console.log(re.cyan(` ${e}`)),console.log(),console.log(re.yellow(" Copy your authorization code and paste it below.")),console.log());const o=await $e({message:"Paste your authorization code:",mask:"*"});if(Ie(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 rn.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}cn(),Lt(),_t(),__name(heading,"heading"),Rn(),Nn(),_t(),ln(),__name(performAnthropicAuth,"performAnthropicAuth"),_t();var ro=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},oo=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 D.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=De("Checking authentication status...").start();try{const t=Rt(),n=await checkAuthStatus(t);n.error&&(e.fail(re.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(re.red("Not authenticated")),console.log(""),console.log(`${re.dim("Run")} ${re.cyan("cmd auth login")} ${re.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${re.green(Se.tick)} ${re.bold("Authenticated")} with ${re.cyan("Command Code")}`),n.userName&&console.log(`${re.dim("Logged in as")} ${re.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(re.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}_t(),Ot(),Ut(),Lt(),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(getUserName,"getUserName"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction");var so=new ke("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction),ao=__name(({message:e})=>q.createElement(q.Fragment,null,q.createElement(J,{color:"cyan"},q.createElement(Re,{type:"dots"})),q.createElement(J,null," ",e)),"LoadingIndicator"),io=__name(({message:e})=>q.createElement(q.Fragment,null,q.createElement(J,{color:"green"},Se.tick),q.createElement(J,null," ",e)),"SuccessIndicator"),co=__name(({children:e})=>q.createElement(K,{flexDirection:"column"},q.createElement(J,null," "),q.createElement(K,null,e)),"StatusContainer");function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,a]=z("loading"),[i,l]=z(null);return H(()=>{n().then(e=>{l(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:q.createElement(co,null,"loading"===s?q.createElement(ao,{message:e}):q.createElement(io,{message:t}))}async function checkExistingAuth(e){const t=await checkAuthStatus(e);return t.authenticated?{isAuthenticated:!0,userName:t.userName}:{isAuthenticated:!1}}function getAuthFileName(e){return"local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json"}function isGenericUserName(e){return!e||"API Key"===e}function isGenericUserNameForOutro(e){return isGenericUserName(e)||"Manual API Key"===e}function formatUserDisplay(e,t=!1){return(t?isGenericUserNameForOutro(e):isGenericUserName(e))?t?" successfully":"":` as ${re.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${re.green(Se.tick)} ${re.bold("Already logged in")}${t}`,"",`${re.dim("Run")} ${re.cyan("cmd")} ${re.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${re.green(Se.tick)} ${re.bold("Logged in")}${n}`,"",`${re.dim("API key stored in")} ${re.cyan(`~/.commandcode/${t}`)}`,`${re.dim("Run")} ${re.cyan("cmd")} ${re.dim("to get started.")}`].join("\n")}function isLoginSuccess(e){return e.success}function isLoginDenied(e){return"denied"===e.reason}function isLoginCancelled(e){return"cancelled"===e.reason}function createLoginError(e){return isLoginDenied(e)?new oo(e.message):isLoginCancelled(e)?new ro(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 ro||e instanceof oo}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),Te.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await xe({message:"Select provider",options:e});if(Ie(t))throw Ae(`${Se.cross} No provider selected.`),new ro("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){Ae(`${Se.cross} ${e}`)}function showAnthropicAuthNote(){_e("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(q.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(q.createElement(no,{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 lo=__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]),q.createElement(co,null,"checking"===n&&q.createElement(ao,{message:"Checking authentication status..."}),"logged_in"===n&&q.createElement(io,{message:"Authenticated"}),"not_logged_in"===n&&q.createElement(io,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=Y(q.createElement(lo,{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=Rt(),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 uo=new ke("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction);async function safeRemoveFile(e,t){try{return await D.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"}}}_t(),_t(),Ut(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout");var mo=__name(()=>q.createElement(q.Fragment,null,q.createElement(J,{color:"cyan"},q.createElement(Re,{type:"dots"})),q.createElement(J,null," Logging out...")),"LoadingIndicator"),po=__name(()=>q.createElement(q.Fragment,null,q.createElement(J,{color:"green"},Se.tick),q.createElement(J,null," Logged out")),"SuccessIndicator"),ho=__name(({errorMessage:e})=>q.createElement(q.Fragment,null,q.createElement(J,{color:"red"},Se.cross),q.createElement(J,{color:"red"}," Logout failed: ",e)),"ErrorIndicator"),fo=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return q.createElement(mo,null);case"success":return q.createElement(po,null);case"error":return q.createElement(ho,{errorMessage:t})}},"StatusDisplay"),yo=__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]),q.createElement(K,{flexDirection:"column"},q.createElement(J,null," "),q.createElement(K,null,q.createElement(fo,{status:t,errorMessage:r})))},"LogoutSpinner");function printWarnings(e){e.length>0&&(console.warn(re.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(re.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=Y(q.createElement(yo,{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 wo=new ke("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction);Lt(),Ut(),new ke("auth").description("Manage authentication with Command Code").addCommand(uo).addCommand(wo).addCommand(so),_t(),Ot();var Eo="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",bo="\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 So=getMaxLineWidth(Eo),vo=getMaxLineWidth(bo),Co=So+1,ko=vo+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var Po=__name(e=>{const t=e??getTerminalWidth();return t>=Co?Eo:t>=ko?bo:To},"getResponsiveCommandLogo"),To="⌘ CMD\n",Ao=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),xo=__name(e=>{console.log(te.white(Po())),console.log(""),console.log(`${Se.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),Io=__name(async e=>{const t=Ce.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"),_o=__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"),No=__name(()=>{console.log(""),console.log(`${Se.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),$o=__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;xo(Dt());const{answer:e,cancelled:t}=await Io(`Would you like to sign in now? ${te.dim("(y/n)")}: `);return t?($o(),!1):Ao(e)?(console.log(""),_o()):(No(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin"),_t(),_t(),Ot(),_t();var Ro=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))}};_t(),_t();var Do=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 Oo({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Lo(e,o,n,r);case 401:return new Mo(e,o,n,r);case 403:return new Fo(e,o,n,r);case 404:return new Uo(e,o,n,r);case 409:return new jo(e,o,n,r);case 422:return new Bo(e,o,n,r);case 429:return new qo(e,o,n,r);default:return e>=500?new zo(e,o,n,r):new _APIError(e,o,n,r)}}},Oo=class extends Do{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)}},Lo=class extends Do{static{__name(this,"BadRequestError")}status=400},Mo=class extends Do{static{__name(this,"AuthenticationError")}status=401},Fo=class extends Do{static{__name(this,"PermissionDeniedError")}status=403},Uo=class extends Do{static{__name(this,"NotFoundError")}status=404},jo=class extends Do{static{__name(this,"ConflictError")}status=409},Bo=class extends Do{static{__name(this,"UnprocessableEntityError")}status=422},qo=class extends Do{static{__name(this,"RateLimitError")}status=429},zo=class extends Do{static{__name(this,"InternalServerError")}};Sr(),Yn(),Ln(),_t(),_t();var Wo=p.object({messageId:p.string().optional(),timestamp:p.string(),model:p.string().optional(),duration:p.number().optional(),usage:p.object({inputTokens:p.number(),outputTokens:p.number(),totalTokens:p.number(),cacheReadTokens:p.number().optional(),cacheWriteTokens:p.number().optional(),estimatedCost:p.number().optional()}).optional(),source:p.string().optional(),context:p.object({sessionId:p.string().optional(),threadId:p.string().optional(),userId:p.string().optional()}).optional(),highlight:p.boolean().optional(),isSummary:p.boolean().optional()});p.object({message:p.any(),meta:Wo}),p.object({sessionId:p.string(),messages:p.array(p.any()).optional()}),p.object({secret:p.string(),url:p.string()}),p.object({sessionId:p.string(),secret:p.string()}),p.object({sessionId:p.string(),secret:p.string(),key:p.string(),content:p.any()}),p.object({sessionId:p.string(),secret:p.string(),message:p.any()}),p.object({shortId:p.string()}),p.object({info:p.any().optional(),messages:p.array(p.any())}),_t(),_t(),_t(),p.object({to:p.union([p.email(),p.array(p.email())]),subject:p.string(),html:p.string().optional(),text:p.string().optional(),template:p.string().optional(),templateData:p.record(p.any(),p.any()).optional(),cc:p.array(p.email()).optional(),bcc:p.array(p.email()).optional(),replyTo:p.array(p.email()).optional(),tags:p.array(p.object({name:p.string(),value:p.string()})).optional()}),p.object({success:p.boolean(),messageId:p.string().optional(),error:p.string().optional()}),_t();var Ho=p.enum(["active","canceled","incomplete","incomplete_expired","past_due","trialing","unpaid"]),Vo=p.enum(["admin_grant","signup_credits","purchased_credits","subscription_credits"]),Go=p.enum(["agent","learning","custom-agent","custom-agent-create"]),Ko=p.enum(["free","monthly","purchased"]);p.enum(["team","individual","enterprise"]),p.object({type:p.enum(["api","oauth"]).default("api"),orgId:p.string().nullable().optional(),model:p.string().min(1),userId:p.string().min(1),traceId:p.string(),provider:p.enum(["openai","anthropic","azure"]).default("anthropic"),tokensIn:p.number().min(0),tokensOut:p.number().min(0),inputCost:p.number().min(0),totalCost:p.number().min(0),outputCost:p.number().min(0),ownerLogin:p.string(),tokensTotal:p.number().min(0),creditsTotal:p.number().min(0),durationTotal:p.number().min(0),mode:Go.nullable().optional(),cacheCost:p.number().min(0).optional(),cacheSavings:p.number().optional(),cacheCreation:p.object({ephemeral_5m_input_tokens:p.number().optional(),ephemeral_1h_input_tokens:p.number().optional()}).nullable().optional(),cacheCreationInputTokens:p.number().min(0).nullable().optional(),cacheReadInputTokens:p.number().min(0).nullable().optional(),threadId:p.string().nullable().optional(),messageInId:p.string().nullable().optional(),messageOutId:p.string().nullable().optional()}),p.object({success:p.boolean(),instanceId:p.string().optional(),error:p.string().optional()}),p.object({userId:p.string().min(1),orgId:p.string().nullable()}),p.object({credits:p.object({freeCredits:p.number(),belowThreshold:p.boolean(),monthlyCredits:p.number(),creditThreshold:p.number(),availableCredits:p.number(),purchasedCredits:p.number()})}),p.object({userId:p.string().min(1),orgId:p.string().nullable().optional()}),p.object({success:p.boolean(),data:p.object({id:p.string(),userId:p.uuid(),orgId:p.string().nullable(),stripeCustomerId:p.string(),autoCharge:p.boolean(),creditThreshold:p.string(),rechargeAmount:p.string(),monthlyCreditThreshold:p.string()}).optional(),error:p.string().optional()}),p.object({userId:p.string().min(1),orgId:p.string().nullable().optional(),autoCharge:p.boolean().optional(),rechargeAmount:p.number().min(0).optional(),creditThreshold:p.number().min(0).optional(),monthlyCreditThreshold:p.number().min(0).optional(),stripeCustomerId:p.string().optional()}),p.object({success:p.boolean(),data:p.object({id:p.string(),userId:p.uuid(),orgId:p.string().nullable(),stripeCustomerId:p.string(),autoCharge:p.boolean(),creditThreshold:p.string(),rechargeAmount:p.string()}).optional(),error:p.string().optional()}),p.object({userId:p.string().min(1),userEmail:p.email(),orgId:p.string().nullable().optional()}),p.object({success:p.boolean(),data:p.object({clientSecret:p.string(),customerId:p.string()}).optional(),error:p.string().optional(),message:p.string().optional()}),p.object({userId:p.string().min(1),orgId:p.string().nullable().optional()}),p.object({success:p.boolean(),data:p.object({hasPaymentMethod:p.boolean(),paymentMethods:p.array(p.object({id:p.string(),brand:p.string().optional(),last4:p.string().optional(),expMonth:p.number().optional(),expYear:p.number().optional(),default:p.boolean()})),customerId:p.string().optional()}).optional(),error:p.string().optional()}),p.object({userId:p.string().min(1),paymentMethodId:p.string().min(1),orgId:p.string().nullable().optional()}),p.object({success:p.boolean(),error:p.string().optional()}),p.object({userId:p.string().min(1),orgId:p.string().nullable().optional(),customerId:p.string().min(1),paymentMethodId:p.string().min(1)}),p.object({success:p.boolean(),message:p.string().optional(),error:p.string().optional()}),p.object({body:p.string(),signature:p.string()}),p.object({success:p.boolean(),received:p.boolean().optional(),error:p.string().optional()}),p.object({orgId:p.string().nullable().optional(),amount:p.number().min(0),credits:p.number().min(0),userEmail:p.email(),creditType:Ko.optional(),invoiceType:Vo}),p.object({success:p.boolean(),message:p.string().optional(),error:p.string().optional()}),p.object({orgId:p.string().nullable(),limit:p.number().min(1).max(100).default(10),userId:p.string().min(1),startingAfter:p.string().optional()}),p.object({success:p.boolean(),data:p.object({invoices:p.array(p.object({id:p.string(),status:p.enum(["paid"]),invoicePdf:p.url().nullable(),amountPaid:p.number(),currency:p.string(),credits:p.string(),autoCharged:p.boolean(),createdAt:p.string(),invoiceType:Vo})),hasMore:p.boolean()}).optional(),error:p.string().optional()}),p.object({userId:p.uuid(),orgId:p.uuid().nullable().optional()}),p.object({success:p.boolean(),data:p.object({id:p.string(),orgId:p.string().nullable(),userId:p.string().nullable(),status:Ho,planId:p.string(),priceId:p.string(),quantity:p.number(),currentPeriodEnd:p.string(),cancelAtPeriodEnd:p.boolean(),currentPeriodStart:p.string()}).nullable(),error:p.string().optional()}),p.object({success:p.boolean(),data:p.object({totalGiven:p.number(),limit:p.number(),remaining:p.number()}).optional(),error:p.string().optional()}),p.object({amount:p.number().min(0)}),p.object({success:p.boolean(),totalGiven:p.number().optional(),exceeded:p.boolean().optional(),error:p.string().optional()}),_t(),_t(),_t(),_t(),_t(),_t();var Jo=p.object({name:p.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:p.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:p.string().optional(),compatibility:p.string().max(500,"Skill compatibility must be 500 characters or less").optional(),metadata:p.record(p.string(),p.any()).optional(),"allowed-tools":p.union([p.string(),p.array(p.string())]).optional()});p.object({name:p.string(),description:p.string(),license:p.string().optional(),compatibility:p.string().max(500).optional(),metadata:p.record(p.string(),p.any()).optional(),"allowed-tools":p.union([p.string(),p.array(p.string())]).optional(),content:p.string(),filePath:p.string()}),p.object({name:p.string(),description:p.string(),filePath:p.string()}),_t(),_t(),Ot(),Ot(),Nt(),_t(),_t(),_t(),_t(),_t();var Qo=new Map,Yo=new Map,Zo=Symbol("OriginError"),Xo={},es=class extends Promise{static{__name(this,"Query")}constructor(e,t,n,r,o={}){let s,a;super((e,t)=>{s=e,a=t}),this.tagged=Array.isArray(e.raw),this.strings=e,this.args=t,this.handler=n,this.canceller=r,this.options=o,this.state=null,this.statement=null,this.resolve=e=>(this.active=!1,s(e)),this.reject=e=>(this.active=!1,a(e)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[Zo]=this.handler.debug?new Error:this.tagged&&cachedError(this.strings)}get origin(){return(this.handler.debug?this[Zo].stack:this.tagged&&Yo.has(this.strings)?Yo.get(this.strings):Yo.set(this.strings,this[Zo].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(e=1,t){if(this.options.simple=!1,"function"==typeof e&&(t=e,e=1),this.cursorRows=e,"function"==typeof t)return this.cursorFn=t,this;let n;return{[Symbol.asyncIterator]:()=>({next:__name(()=>{if(this.executed&&!this.active)return{done:!0};n&&n();const e=new Promise((e,t)=>{this.cursorFn=t=>(e({value:t,done:!1}),new Promise(e=>n=e)),this.resolve=()=>(this.active=!1,e({done:!0})),this.reject=e=>(this.active=!1,t(e))});return this.execute(),e},"next"),return:()=>(n&&n(Xo),{done:!0})})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(e){return this.forEachFn=e,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}};function cachedError(e){if(Qo.has(e))return Qo.get(e);const t=Error.stackTraceLimit;return Error.stackTraceLimit=4,Qo.set(e,new Error),Error.stackTraceLimit=t,Qo.get(e)}__name(cachedError,"cachedError"),_t();var ts=class extends Error{static{__name(this,"PostgresError")}constructor(e){super(e.message),this.name=this.constructor.name,Object.assign(this,e)}},ns={connection:connection,postgres:postgres,generic:generic,notSupported:notSupported};function connection(e,t,n){const{host:r,port:o}=n||t,s=Object.assign(new Error("write "+e+" "+(t.path||r+":"+o)),{code:e,errno:e,address:t.path||r},t.path?{}:{port:o});return Error.captureStackTrace(s,connection),s}function postgres(e){const t=new ts(e);return Error.captureStackTrace(t,postgres),t}function generic(e,t){const n=Object.assign(new Error(e+": "+t),{code:e});return Error.captureStackTrace(n,generic),n}function notSupported(e){const t=Object.assign(new Error(e+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:e});return Error.captureStackTrace(t,notSupported),t}__name(connection,"connection"),__name(postgres,"postgres"),__name(generic,"generic"),__name(notSupported,"notSupported");var rs={string:{to:25,from:null,serialize:__name(e=>""+e,"serialize")},number:{to:0,from:[21,23,26,700,701],serialize:__name(e=>""+e,"serialize"),parse:__name(e=>+e,"parse")},json:{to:114,from:[114,3802],serialize:__name(e=>JSON.stringify(e),"serialize"),parse:__name(e=>JSON.parse(e),"parse")},boolean:{to:16,from:16,serialize:__name(e=>!0===e?"t":"f","serialize"),parse:__name(e=>"t"===e,"parse")},date:{to:1184,from:[1082,1114,1184],serialize:__name(e=>(e instanceof Date?e:new Date(e)).toISOString(),"serialize"),parse:__name(e=>new Date(e),"parse")},bytea:{to:17,from:17,serialize:__name(e=>"\\x"+Buffer.from(e).toString("hex"),"serialize"),parse:__name(e=>Buffer.from(e.slice(2),"hex"),"parse")}},os=class{static{__name(this,"NotTagged")}then(){notTagged()}catch(){notTagged()}finally(){notTagged()}},ss=class extends os{static{__name(this,"Identifier")}constructor(e){super(),this.value=ps(e)}},as=class extends os{static{__name(this,"Parameter")}constructor(e,t,n){super(),this.value=e,this.type=t,this.array=n}},cs=class extends os{static{__name(this,"Builder")}constructor(e,t){super(),this.first=e,this.rest=t}build(e,t,n,r){const o=us.map(([t,n])=>({fn:n,i:e.search(t)})).sort((e,t)=>e.i-t.i).pop();return-1===o.i?escapeIdentifiers(this.first,r):o.fn(this.first,this.rest,t,n,r)}};function handleValue(e,t,n,r){let o=e instanceof as?e.value:e;if(void 0===o&&(e instanceof as?e.value=r.transform.undefined:o=e=r.transform.undefined,void 0===o))throw ns.generic("UNDEFINED_VALUE","Undefined values are not allowed");return"$"+n.push(e instanceof as?(t.push(e.value),e.array?e.array[e.type||hs(e.value)]||e.type||firstIsString(e.value):e.type):(t.push(e),hs(e)))}__name(handleValue,"handleValue");var ls=typeHandlers(rs);function stringify(e,t,n,r,o,s){for(let a=1;a<e.strings.length;a++)t+=stringifyValue(t,n,r,o,s)+e.strings[a],n=e.args[a];return t}function stringifyValue(e,t,n,r,o){return t instanceof cs?t.build(e,n,r,o):t instanceof es?fragment(t,n,r,o):t instanceof ss?t.value:t&&t[0]instanceof es?t.reduce((e,t)=>e+" "+fragment(t,n,r,o),""):handleValue(t,n,r,o)}function fragment(e,t,n,r){return e.fragment=!0,stringify(e,e.strings[0],e.args[0],t,n,r)}function valuesBuilder(e,t,n,r,o){return e.map(e=>"("+r.map(r=>stringifyValue("values",e[r],t,n,o)).join(",")+")").join(",")}function values(e,t,n,r,o){const s=Array.isArray(e[0]);return valuesBuilder(s?e:[e],n,r,t.length?t.flat():Object.keys(s?e[0]:e),o)}function select2(e,t,n,r,o){if("string"==typeof e&&(e=[e].concat(t)),Array.isArray(e))return escapeIdentifiers(e,o);let s;return(t.length?t.flat():Object.keys(e)).map(t=>(s=e[t],(s instanceof es?fragment(s,n,r,o):s instanceof ss?s.value:handleValue(s,n,r,o))+" as "+ps(o.transform.column.to?o.transform.column.to(t):t))).join(",")}__name(stringify,"stringify"),__name(stringifyValue,"stringifyValue"),__name(fragment,"fragment"),__name(valuesBuilder,"valuesBuilder"),__name(values,"values"),__name(select2,"select");var us=Object.entries({values:values,in:__name((...e)=>{const t=values(...e);return"()"===t?"(null)":t},"in"),select:select2,as:select2,returning:select2,"\\(":select2,update:(e,t,n,r,o)=>(t.length?t.flat():Object.keys(e)).map(t=>ps(o.transform.column.to?o.transform.column.to(t):t)+"="+stringifyValue("values",e[t],n,r,o)),insert(e,t,n,r,o){const s=t.length?t.flat():Object.keys(Array.isArray(e)?e[0]:e);return"("+escapeIdentifiers(s,o)+")values"+valuesBuilder(Array.isArray(e)?e:[e],n,r,s,o)}}).map(([e,t])=>[new RegExp("((?:^|[\\s(])"+e+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),t]);function notTagged(){throw ns.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}__name(notTagged,"notTagged");var ds=ls.serializers,ms=ls.parsers;function firstIsString(e){return Array.isArray(e)?firstIsString(e[0]):"string"==typeof e?1009:0}__name(firstIsString,"firstIsString");var gs=__name(function(e){const t=typeHandlers(e||{});return{serializers:Object.assign({},ds,t.serializers),parsers:Object.assign({},ms,t.parsers)}},"mergeUserTypes");function typeHandlers(e){return Object.keys(e).reduce((t,n)=>(e[n].from&&[].concat(e[n].from).forEach(r=>t.parsers[r]=e[n].parse),e[n].serialize&&(t.serializers[e[n].to]=e[n].serialize,e[n].from&&[].concat(e[n].from).forEach(r=>t.serializers[r]=e[n].serialize)),t),{parsers:{},serializers:{}})}function escapeIdentifiers(e,{transform:{column:t}}){return e.map(e=>ps(t.to?t.to(e):e)).join(",")}__name(typeHandlers,"typeHandlers"),__name(escapeIdentifiers,"escapeIdentifiers");var ps=__name(function escape(e){return'"'+e.replace(/"/g,'""').replace(/\./g,'"."')+'"'},"escape"),hs=__name(function inferType2(e){return e instanceof as?e.type:e instanceof Date?1184:e instanceof Uint8Array?17:!0===e||!1===e?16:"bigint"==typeof e?20:Array.isArray(e)?inferType2(e[0]):0},"inferType"),fs=/\\/g,ys=/"/g;function arrayEscape(e){return e.replace(fs,"\\\\").replace(ys,'\\"')}__name(arrayEscape,"arrayEscape");var ws=__name(function arraySerializer2(e,t,n,r){if(!1===Array.isArray(e))return e;if(!e.length)return"{}";const o=e[0],s=1020===r?";":",";return Array.isArray(o)&&!o.type?"{"+e.map(e=>arraySerializer2(e,t,n,r)).join(s)+"}":"{"+e.map(e=>{if(void 0===e&&void 0===(e=n.transform.undefined))throw ns.generic("UNDEFINED_VALUE","Undefined values are not allowed");return null===e?"null":'"'+arrayEscape(t?t(e.type?e.value:e):""+e)+'"'}).join(s)+"}"},"arraySerializer"),Es={i:0,char:null,str:"",quoted:!1,last:0},bs=__name(function arrayParser2(e,t,n){return Es.i=Es.last=0,arrayParserLoop(Es,e,t,n)},"arrayParser");function arrayParserLoop(e,t,n,r){const o=[],s=1020===r?";":",";for(;e.i<t.length;e.i++){if(e.char=t[e.i],e.quoted)"\\"===e.char?e.str+=t[++e.i]:'"'===e.char?(o.push(n?n(e.str):e.str),e.str="",e.quoted='"'===t[e.i+1],e.last=e.i+2):e.str+=e.char;else if('"'===e.char)e.quoted=!0;else if("{"===e.char)e.last=++e.i,o.push(arrayParserLoop(e,t,n,r));else{if("}"===e.char){e.quoted=!1,e.last<e.i&&o.push(n?n(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1;break}e.char===s&&"}"!==e.p&&'"'!==e.p&&(o.push(n?n(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1)}e.p=e.char}return e.last<e.i&&o.push(n?n(t.slice(e.last,e.i+1)):t.slice(e.last,e.i+1)),o}__name(arrayParserLoop,"arrayParserLoop");var Ss=__name(e=>{let t=e[0];for(let n=1;n<e.length;n++)t+="_"===e[n]?e[++n].toUpperCase():e[n];return t},"toCamel"),vs=__name(e=>{let t=e[0].toUpperCase();for(let n=1;n<e.length;n++)t+="_"===e[n]?e[++n].toUpperCase():e[n];return t},"toPascal"),Cs=__name(e=>e.replace(/_/g,"-"),"toKebab"),ks=__name(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase(),"fromCamel"),Ps=__name(e=>(e.slice(0,1)+e.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),"fromPascal"),Ts=__name(e=>e.replace(/-/g,"_"),"fromKebab");function createJsonTransform(e){return __name(function jsonTransform(t,n){return"object"!=typeof t||null===t||114!==n.type&&3802!==n.type?t:Array.isArray(t)?t.map(e=>jsonTransform(e,n)):Object.entries(t).reduce((t,[r,o])=>Object.assign(t,{[e(r)]:jsonTransform(o,n)}),{})},"jsonTransform")}__name(createJsonTransform,"createJsonTransform"),Ss.column={from:Ss},Ss.value={from:createJsonTransform(Ss)},ks.column={to:ks};var As={...Ss};As.column.to=ks,vs.column={from:vs},vs.value={from:createJsonTransform(vs)},Ps.column={to:Ps};var xs={...vs};xs.column.to=Ps,Cs.column={from:Cs},Cs.value={from:createJsonTransform(Cs)},Ts.column={to:Ts};var Is={...Cs};Is.column.to=Ts,_t(),_t();var _s=class extends Array{static{__name(this,"Result")}constructor(){super(),Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}};_t();var Ns=Queue;function Queue(e=[]){let t=e.slice(),n=0;return{get length(){return t.length-n},remove:__name(e=>{const n=t.indexOf(e);return-1===n?null:(t.splice(n,1),e)},"remove"),push:__name(e=>(t.push(e),e),"push"),shift:__name(()=>{const e=t[n++];return n===t.length?(n=0,t=[]):t[n-1]=void 0,e},"shift")}}__name(Queue,"Queue"),_t();var $s=Buffer.allocUnsafe(256),Rs="BCcDdEFfHPpQSX".split("").reduce((e,t)=>{const n=t.charCodeAt(0);return e[t]=()=>($s[0]=n,Ds.i=5,Ds),e},{}),Ds=Object.assign(reset,Rs,{N:String.fromCharCode(0),i:0,inc:e=>(Ds.i+=e,Ds),str(e){const t=Buffer.byteLength(e);return fit(t),Ds.i+=$s.write(e,Ds.i,t,"utf8"),Ds},i16:e=>(fit(2),$s.writeUInt16BE(e,Ds.i),Ds.i+=2,Ds),i32:(e,t)=>t||0===t?($s.writeUInt32BE(e,t),Ds):(fit(4),$s.writeUInt32BE(e,Ds.i),Ds.i+=4,Ds),z:e=>(fit(e),$s.fill(0,Ds.i,Ds.i+e),Ds.i+=e,Ds),raw:e=>($s=Buffer.concat([$s.subarray(0,Ds.i),e]),Ds.i=$s.length,Ds),end(e=1){$s.writeUInt32BE(Ds.i-e,e);const t=$s.subarray(0,Ds.i);return Ds.i=0,$s=Buffer.allocUnsafe(256),t}}),Os=Ds;function fit(e){if($s.length-Ds.i<e){const t=$s,n=t.length;$s=Buffer.allocUnsafe(n+(n>>1)+e),t.copy($s)}}function reset(){return Ds.i=0,Ds}__name(fit,"fit"),__name(reset,"reset");var Ls=Connection,Ms=1,Fs=Os().S().end(),Us=Os().H().end(),js=Os().i32(8).i32(80877103).end(8),Bs=Buffer.concat([Os().E().str(Os.N).i32(0).end(),Fs]),qs=Os().D().str("S").str(Os.N).end(),zs=__name(()=>{},"noop"),Ws=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Hs={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function Connection(e,t={},{onopen:n=zs,onend:r=zs,onclose:o=zs}={}){const{sslnegotiation:s,ssl:a,max:i,user:l,host:u,port:d,database:m,parsers:g,transform:p,onnotice:h,onnotify:f,onparameter:y,max_pipeline:w,keep_alive:E,backoff:b,target_session_attrs:S}=e,v=Ns(),C=Ms++,k={pid:null,secret:null},P=timer(end,e.idle_timeout),T=timer(end,e.max_lifetime),A=timer(function connectTimedOut(){errored(ns.connection("CONNECT_TIMEOUT",e,I)),I.destroy()},e.connect_timeout);let x,I=null,_=null,N=new _s,$=Buffer.alloc(0),R=e.fetch_types,D={},O={},L=Math.random().toString(36).slice(2),M=1,F=0,U=0,B=0,q=0,z=0,W=0,H=0,V=null,G=null,K=!1,J=null,Q=null,Y=null,Z=null,X=null,ee=null,te=null,ne=null,re=null,oe=null;const se={queue:t.closed,idleTimer:P,connect(e){Y=e,reconnect()},terminate:terminate,execute:execute,cancel:async function cancel5({pid:e,secret:t},n,r){try{x=Os().i32(16).i32(80877102).i32(e).i32(t).end(16),await connect(),I.once("error",r),I.once("close",n)}catch(e){r(e)}},end:end,count:0,id:C};return t.closed&&t.closed.push(se),se;function execute(t){if(K)return queryError(t,ns.connection("CONNECTION_DESTROYED",e));if(X)return queryError(t,ns.generic("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(!t.cancelled)try{return t.state=k,re?v.push(t):(re=t,re.active=!0),function build(t){const n=[],r=[],o=stringify(t,t.strings[0],t.args[0],n,r,e);!t.tagged&&t.args.forEach(t=>handleValue(t,n,r,e)),t.prepare=e.prepare&&(!("prepare"in t.options)||t.options.prepare),t.string=o,t.signature=t.prepare&&r+o,t.onlyDescribe&&delete O[t.signature],t.parameters=t.parameters||n,t.prepared=t.prepare&&t.signature in O,t.describeFirst=t.onlyDescribe||n.length&&!t.prepared,t.statement=t.prepared?O[t.signature]:{string:o,types:r,name:t.prepare?L+M++:""},"function"==typeof e.debug&&e.debug(C,o,n,r)}(t),write(function toBuffer(e){if(e.parameters.length>=65534)throw ns.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return e.options.simple?Os().Q().str(e.statement.string+Os.N).end():e.describeFirst?Buffer.concat([describe(e),Us]):e.prepare?e.prepared?prepared(e):Buffer.concat([describe(e),prepared(e)]):function unnamed(e){return Buffer.concat([Parse(e.statement.string,e.parameters,e.statement.types),qs,prepared(e)])}(e)}(t))&&!t.describeFirst&&!t.cursorFn&&v.length<w&&(!t.options.onexecute||t.options.onexecute(se))}catch(e){return 0===v.length&&write(Fs),errored(e),!0}}function describe(e){return Buffer.concat([Parse(e.statement.string,e.parameters,e.statement.types,e.statement.name),Describe("S",e.statement.name)])}function prepared(e){return Buffer.concat([Bind(e.parameters,e.statement.types,e.statement.name,e.cursorName),e.cursorFn?Execute("",e.cursorRows):Bs])}function write(e,t){return ee=ee?Buffer.concat([ee,e]):Buffer.from(e),ee.length>=1024?nextWrite(t):(null===G&&(G=setImmediate(nextWrite)),!0)}function nextWrite(e){const t=I.write(ee,e);return null!==G&&clearImmediate(G),ee=G=null,t}async function secure(){if("direct"!==s&&(write(js),!await new Promise(e=>I.once("data",t=>e(83===t[0])))&&"prefer"===a))return connected();const e={socket:I,servername:ye.isIP(I.host)?void 0:I.host};"direct"===s&&(e.ALPNProtocols=["postgresql"]),"require"===a||"allow"===a||"prefer"===a?e.rejectUnauthorized=!1:"object"==typeof a&&Object.assign(e,a),I.removeAllListeners(),I=Le.connect(e),I.on("secureConnect",connected),I.on("error",error),I.on("close",closed),I.on("drain",drain)}function drain(){!re&&n(se)}function data(e){if(!(J&&(J.push(e),U-=e.length,U>0)))for($=J?Buffer.concat(J,z-U):0===$.length?e:Buffer.concat([$,e],$.length+e.length);$.length>4;){if(z=$.readUInt32BE(1),z>=$.length){U=z-$.length,J=[$];break}try{handle($.subarray(0,z+1))}catch(e){re&&(re.cursorFn||re.describeFirst)&&write(Fs),errored(e)}$=$.subarray(z+1),U=0,J=null}}async function connect(){if(K=!1,D={},I||(I=await async function createSocket(){let t;try{t=e.socket?await Promise.resolve(e.socket(e)):new ye.Socket}catch(e){return void error(e)}return t.on("error",error),t.on("close",closed),t.on("drain",drain),t}()),I){if(A.start(),e.socket)return a?secure():connected();if(I.on("connect",a?secure:connected),e.path)return I.connect(e.path);I.ssl=a,I.connect(d[B],u[B]),I.host=u[B],I.port=d[B],B=(B+1)%d.length}}function reconnect(){setTimeout(connect,F?Math.max(0,F+W-Fe.now()):0)}function connected(){try{O={},R=e.fetch_types,L=Math.random().toString(36).slice(2),M=1,T.start(),I.on("data",data),E&&I.setKeepAlive&&I.setKeepAlive(!0,1e3*E),write(function StartupMessage(){return x||Os().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:l,database:m,client_encoding:"UTF8"},e.connection)).filter(([,e])=>e).map(([e,t])=>e+Os.N+t).join(Os.N)).z(2).end(0)}())}catch(e){error(e)}}function error(n){if(se.queue!==t.connecting||!e.host[q+1])for(errored(n);v.length;)queryError(v.shift(),n)}function errored(e){X&&(X.destroy(e),X=null),re&&queryError(re,e),Y&&(queryError(Y,e),Y=null)}function queryError(t,n){if(t.reserve)return t.reject(n);n&&"object"==typeof n||(n=new Error(n)),"query"in n||"parameters"in n||Object.defineProperties(n,{stack:{value:n.stack+t.origin.replace(/.*\n/,"\n"),enumerable:e.debug},query:{value:t.string,enumerable:e.debug},parameters:{value:t.parameters,enumerable:e.debug},args:{value:t.args,enumerable:e.debug},types:{value:t.statement&&t.statement.types,enumerable:e.debug}}),t.reject(n)}function end(){return Z||(!se.reserved&&r(se),se.reserved||Y||re||0!==v.length?Z=new Promise(e=>te=e):(terminate(),new Promise(e=>I&&"closed"!==I.readyState?I.once("close",e):e())))}function terminate(){K=!0,(X||re||Y||v.length)&&error(ns.connection("CONNECTION_DESTROYED",e)),clearImmediate(G),I&&(I.removeListener("data",data),I.removeListener("connect",connected),"open"===I.readyState&&I.end(Os().X().end())),te&&(te(),Z=te=null)}async function closed(t){if($=Buffer.alloc(0),U=0,J=null,clearImmediate(G),I.removeListener("data",data),I.removeListener("connect",connected),P.cancel(),T.cancel(),A.cancel(),I.removeAllListeners(),I=null,Y)return reconnect();!t&&(re||v.length)&&error(ns.connection("CONNECTION_CLOSED",e,I)),F=Fe.now(),t&&e.shared.retries++,W=1e3*("function"==typeof b?b(e.shared.retries):b),o(se,ns.connection("CONNECTION_CLOSED",e,I))}function handle(e,t=e[0]){(68===t?DataRow:100===t?CopyData:65===t?NotificationResponse:83===t?ParameterStatus:90===t?ReadyForQuery:67===t?CommandComplete:50===t?BindComplete:49===t?ParseComplete:116===t?ParameterDescription:84===t?RowDescription:82===t?Authentication:110===t?NoData:75===t?BackendKeyData:69===t?ErrorResponse:115===t?PortalSuspended:51===t?CloseComplete:71===t?CopyInResponse:78===t?NoticeResponse:72===t?CopyOutResponse:99===t?CopyDone:73===t?EmptyQueryResponse:86===t?FunctionCallResponse:118===t?NegotiateProtocolVersion:87===t?CopyBothResponse:UnknownMessage)(e)}function DataRow(e){let t,n,r,o=7;const s=re.isRaw?new Array(re.statement.columns.length):{};for(let a=0;a<re.statement.columns.length;a++)n=re.statement.columns[a],t=e.readInt32BE(o),o+=4,r=-1===t?null:!0===re.isRaw?e.subarray(o,o+=t):void 0===n.parser?e.toString("utf8",o,o+=t):!0===n.parser.array?n.parser(e.toString("utf8",o+1,o+=t)):n.parser(e.toString("utf8",o,o+=t)),re.isRaw?s[a]=!0===re.isRaw?r:p.value.from?p.value.from(r,n):r:s[n.name]=p.value.from?p.value.from(r,n):r;re.forEachFn?re.forEachFn(p.row.from?p.row.from(s):s,N):N[H++]=p.row.from?p.row.from(s):s}function ParameterStatus(t){const[n,r]=t.toString("utf8",5,t.length-1).split(Os.N);D[n]=r,e.parameters[n]!==r&&(e.parameters[n]=r,y&&y(n,r))}function ReadyForQuery(t){if(re?_?re.retried?errored(re.retried):re.prepared&&Ws.has(_.routine)?function retry(e,t){delete O[e.signature],e.retried=t,execute(e)}(re,_):errored(_):re.resolve(Q||N):_&&errored(_),re=Q=_=null,N=new _s,A.cancel(),Y){if(S){if(!D.in_hot_standby||!D.default_transaction_read_only)return function fetchState(){const e=new es(["\n show transaction_read_only;\n select pg_catalog.pg_is_in_recovery()\n "],[],execute,null,{simple:!0});e.resolve=([[e],[t]])=>{D.default_transaction_read_only=e.transaction_read_only,D.in_hot_standby=t.pg_is_in_recovery?"on":"off"},e.execute()}();if(function tryNext(t,n){return"read-write"===t&&"on"===n.default_transaction_read_only||"read-only"===t&&"off"===n.default_transaction_read_only||"primary"===t&&"on"===n.in_hot_standby||"standby"===t&&"off"===n.in_hot_standby||"prefer-standby"===t&&"off"===n.in_hot_standby&&e.host[q]}(S,D))return terminate()}return R?(Y.reserve&&(Y=null),async function fetchArrayTypes(){R=!1,(await new es(["\n select b.oid, b.typarray\n from pg_catalog.pg_type a\n left join pg_catalog.pg_type b on b.oid = a.typelem\n where a.typcategory = 'A'\n group by b.oid, b.typarray\n order by b.oid\n "],[],execute)).forEach(({oid:t,typarray:n})=>function addArrayType(t,n){if(e.parsers[n]&&e.serializers[n])return;const r=e.parsers[t];e.shared.typeArrayMap[t]=n,e.parsers[n]=e=>bs(e,r,n),e.parsers[n].array=!0,e.serializers[n]=r=>ws(r,e.serializers[t],e,n)}(t,n))}()):(Y&&!Y.reserve&&execute(Y),e.shared.retries=q=0,void(Y=null))}for(;v.length&&(re=v.shift())&&(re.active=!0,re.cancelled);)Connection(e).cancel(re.state,re.cancelled.resolve,re.cancelled.reject);re||(se.reserved?se.reserved.release||73!==t[5]?se.reserved():Z?terminate():(se.reserved=null,n(se)):Z?terminate():n(se))}function CommandComplete(e){H=0;for(let t=e.length-1;t>0;t--)if(32===e[t]&&e[t+1]<58&&null===N.count&&(N.count=+e.toString("utf8",t+1,e.length-1)),e[t-1]>=65){N.command=e.toString("utf8",5,t),N.state=k;break}return oe&&(oe(),oe=null),"BEGIN"!==N.command||1===i||se.reserved?re.options.simple?BindComplete():void(re.cursorFn&&(N.count&&re.cursorFn(N),write(Fs))):errored(ns.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"))}function ParseComplete(){re.parsing=!1}function BindComplete(){!N.statement&&(N.statement=re.statement),N.columns=re.statement.columns}function ParameterDescription(e){const t=e.readUInt16BE(5);for(let n=0;n<t;++n)!re.statement.types[n]&&(re.statement.types[n]=e.readUInt32BE(7+4*n));re.prepare&&(O[re.signature]=re.statement),re.describeFirst&&!re.onlyDescribe&&(write(prepared(re)),re.describeFirst=!1)}function RowDescription(e){N.command&&(Q=Q||[N],Q.push(N=new _s),N.count=null,re.statement.columns=null);const t=e.readUInt16BE(5);let n,r=7;re.statement.columns=Array(t);for(let o=0;o<t;++o){for(n=r;0!==e[r++];);const t=e.readUInt32BE(r),s=e.readUInt16BE(r+4),a=e.readUInt32BE(r+6);re.statement.columns[o]={name:p.column.from?p.column.from(e.toString("utf8",n,r-1)):e.toString("utf8",n,r-1),parser:g[a],table:t,number:s,type:a},r+=18}if(N.statement=re.statement,re.onlyDescribe)return re.resolve(re.statement),write(Fs)}async function Authentication(e,t=e.readUInt32BE(5)){(3===t?AuthenticationCleartextPassword:5===t?AuthenticationMD5Password:10===t?SASL:11===t?SASLContinue:12===t?SASLFinal:0!==t?UnknownAuth:zs)(e,t)}async function AuthenticationCleartextPassword(){const e=await Pass();write(Os().p().str(e).z(1).end())}async function AuthenticationMD5Password(e){const t="md5"+await md5(Buffer.concat([Buffer.from(await md5(await Pass()+l)),e.subarray(9)]));write(Os().p().str(t).z(1).end())}async function SASL(){ne=(await j.randomBytes(18)).toString("base64"),Os().p().str("SCRAM-SHA-256"+Os.N);const e=Os.i;write(Os.inc(4).str("n,,n=*,r="+ne).i32(Os.i-e-4,e).end())}async function SASLContinue(e){const t=e.toString("utf8",9).split(",").reduce((e,t)=>(e[t[0]]=t.slice(2),e),{}),n=await j.pbkdf2Sync(await Pass(),Buffer.from(t.s,"base64"),parseInt(t.i),32,"sha256"),r=await hmac(n,"Client Key"),o="n=*,r="+ne+",r="+t.r+",s="+t.s+",i="+t.i+",c=biws,r="+t.r;V=(await hmac(await hmac(n,"Server Key"),o)).toString("base64");const s="c=biws,r="+t.r+",p="+xor(r,Buffer.from(await hmac(await sha256(r),o))).toString("base64");write(Os().p().str(s).end())}function SASLFinal(e){e.toString("utf8",9).split(Os.N,1)[0].slice(2)!==V&&(errored(ns.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),I.destroy())}function Pass(){return Promise.resolve("function"==typeof e.pass?e.pass():e.pass)}function NoData(){if(N.statement=re.statement,N.statement.columns=[],re.onlyDescribe)return re.resolve(re.statement),write(Fs)}function BackendKeyData(e){k.pid=e.readUInt32BE(5),k.secret=e.readUInt32BE(9)}function ErrorResponse(e){re?((re.cursorFn||re.describeFirst)&&write(Fs),_=ns.postgres(parseError(e))):errored(ns.postgres(parseError(e)))}function NotificationResponse(e){if(!f)return;let t=9;for(;0!==e[t++];);f(e.toString("utf8",9,t-1),e.toString("utf8",t,e.length-1))}async function PortalSuspended(){try{const e=await Promise.resolve(re.cursorFn(N));H=0,e===Xo?write(function Close(e=""){return Buffer.concat([Os().C().str("P").str(e+Os.N).end(),Os().S().end()])}(re.portal)):(N=new _s,write(Execute("",re.cursorRows)))}catch(e){write(Fs),re.reject(e)}}function CloseComplete(){N.count&&re.cursorFn(N),re.resolve(N)}function CopyInResponse(){X=new Me.Writable({autoDestroy:!0,write(e,t,n){I.write(Os().d().raw(e).end(),n)},destroy(e,t){t(e),I.write(Os().f().str(e+Os.N).end()),X=null},final(e){I.write(Os().c().end()),oe=e,X=null}}),re.resolve(X)}function CopyOutResponse(){X=new Me.Readable({read(){I.resume()}}),re.resolve(X)}function CopyBothResponse(){X=new Me.Duplex({autoDestroy:!0,read(){I.resume()},write(e,t,n){I.write(Os().d().raw(e).end(),n)},destroy(e,t){t(e),I.write(Os().f().str(e+Os.N).end()),X=null},final(e){I.write(Os().c().end()),oe=e}}),re.resolve(X)}function CopyData(e){X&&(X.push(e.subarray(5))||I.pause())}function CopyDone(){X&&X.push(null),X=null}function NoticeResponse(e){h?h(parseError(e)):console.log(parseError(e))}function EmptyQueryResponse(){}function FunctionCallResponse(){errored(ns.notSupported("FunctionCallResponse"))}function NegotiateProtocolVersion(){errored(ns.notSupported("NegotiateProtocolVersion"))}function UnknownMessage(e){console.error("Postgres.js : Unknown Message:",e[0])}function UnknownAuth(e,t){console.error("Postgres.js : Unknown Auth:",t)}function Bind(t,n,r="",o=""){let s,a;return Os().B().str(o+Os.N).str(r+Os.N).i16(0).i16(t.length),t.forEach((r,o)=>{if(null===r)return Os.i32(4294967295);a=n[o],t[o]=r=a in e.serializers?e.serializers[a](r):""+r,s=Os.i,Os.inc(4).str(r).i32(Os.i-s-4,s)}),Os.i16(0),Os.end()}function Parse(e,t,n,r=""){return Os().P().str(r+Os.N).str(e+Os.N).i16(t.length),t.forEach((e,t)=>Os.i32(n[t]||0)),Os.end()}function Describe(e,t=""){return Os().D().str(e).str(t+Os.N).end()}function Execute(e="",t=0){return Buffer.concat([Os().E().str(e+Os.N).i32(t).end(),Us])}}function parseError(e){const t={};let n=5;for(let r=5;r<e.length-1;r++)0===e[r]&&(t[Hs[e[n]]]=e.toString("utf8",n+1,r),n=r+1);return t}function md5(e){return j.createHash("md5").update(e).digest("hex")}function hmac(e,t){return j.createHmac("sha256",e).update(t).digest()}function sha256(e){return j.createHash("sha256").update(e).digest()}function xor(e,t){const n=Math.max(e.length,t.length),r=Buffer.allocUnsafe(n);for(let o=0;o<n;o++)r[o]=e[o]^t[o];return r}function timer(e,t){if(!(t="function"==typeof t?t():t))return{cancel:zs,start:zs};let n;return{cancel(){n&&(clearTimeout(n),n=null)},start(){n&&clearTimeout(n),n=setTimeout(done,1e3*t,arguments)}};function done(t){e.apply(null,t),n=null}}__name(Connection,"Connection"),__name(parseError,"parseError"),__name(md5,"md5"),__name(hmac,"hmac"),__name(sha256,"sha256"),__name(xor,"xor"),__name(timer,"timer"),_t();var Vs=__name(()=>{},"noop");function Subscribe(e,t){const n=new Map,r="postgresjs_"+Math.random().toString(36).slice(2),o={};let s,a,i=!1;const l=subscribe.sql=e({...t,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...t.connection,replication:"database"},onclose:__name(async function(){i||(a=null,o.pid=o.secret=void 0,connected(await init(l,r,t.publications)),n.forEach(e=>e.forEach(({onsubscribe:e})=>e())))},"onclose"),no_subscribe:!0}),u=l.end,d=l.close;return l.end=async()=>(i=!0,a&&await new Promise(e=>(a.once("close",e),a.end())),u()),l.close=async()=>(a&&await new Promise(e=>(a.once("close",e),a.end())),d()),subscribe;async function subscribe(e,i,u=Vs,d=Vs){e=parseEvent(e),s||(s=init(l,r,t.publications));const m={fn:i,onsubscribe:u},g=n.has(e)?n.get(e).add(m):n.set(e,new Set([m])).get(e),p=__name(()=>{g.delete(m),0===g.size&&n.delete(e)},"unsubscribe");return s.then(e=>(connected(e),u(),a&&a.on("error",d),{unsubscribe:p,state:o,sql:l}))}function connected(e){a=e.stream,o.pid=e.state.pid,o.secret=e.state.secret}async function init(e,n,r){if(!r)throw new Error("Missing publication names");const o=await e.unsafe(`CREATE_REPLICATION_SLOT ${n} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[s]=o,a=await e.unsafe(`START_REPLICATION SLOT ${n} LOGICAL ${s.consistent_point} (proto_version '1', publication_names '${r}')`).writable(),i={lsn:Buffer.concat(s.consistent_point.split("/").map(e=>Buffer.from(("00000000"+e).slice(-8),"hex")))};return a.on("data",function data(n){119===n[0]?parse(n.subarray(25),i,e.options.parsers,handle,t.transform):107===n[0]&&n[17]&&(i.lsn=n.subarray(1,9),function pong(){const e=Buffer.alloc(34);e[0]="r".charCodeAt(0),e.fill(i.lsn,1),e.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2e3,0,1))*BigInt(1e3),25),a.write(e)}())}),a.on("error",function error(e){console.error("Unexpected error during logical streaming - reconnecting",e)}),a.on("close",e.close),{stream:a,state:o.state};function handle(e,t){const n=t.relation.schema+"."+t.relation.table;call("*",e,t),call("*:"+n,e,t),t.relation.keys.length&&call("*:"+n+"="+t.relation.keys.map(t=>e[t.name]),e,t),call(t.command,e,t),call(t.command+":"+n,e,t),t.relation.keys.length&&call(t.command+":"+n+"="+t.relation.keys.map(t=>e[t.name]),e,t)}}function call(e,t,r){n.has(e)&&n.get(e).forEach(({fn:n})=>n(t,r,e))}}function Time(e){return new Date(Date.UTC(2e3,0,1)+Number(e/BigInt(1e3)))}function parse(e,t,n,r,o){const s=__name((e,[t,n])=>(e[t.charCodeAt(0)]=n,e),"char");Object.entries({R:__name(e=>{let r=1;const s=t[e.readUInt32BE(r)]={schema:e.toString("utf8",r+=4,r=e.indexOf(0,r))||"pg_catalog",table:e.toString("utf8",r+1,r=e.indexOf(0,r+1)),columns:Array(e.readUInt16BE(r+=2)),keys:[]};r+=2;let a,i=0;for(;r<e.length;)a=s.columns[i++]={key:e[r++],name:o.column.from?o.column.from(e.toString("utf8",r,r=e.indexOf(0,r))):e.toString("utf8",r,r=e.indexOf(0,r)),type:e.readUInt32BE(r+=1),parser:n[e.readUInt32BE(r)],atttypmod:e.readUInt32BE(r+=4)},a.key&&s.keys.push(a),r+=4},"R"),Y:__name(()=>{},"Y"),O:__name(()=>{},"O"),B:__name(e=>{t.date=Time(e.readBigInt64BE(9)),t.lsn=e.subarray(1,9)},"B"),I:__name(e=>{let n=1;const s=t[e.readUInt32BE(n)],{row:a}=tuples(e,s.columns,n+=7,o);r(a,{command:"insert",relation:s})},"I"),D:__name(e=>{let n=1;const s=t[e.readUInt32BE(n)];n+=4;const a=75===e[n];r(a||79===e[n]?tuples(e,s.columns,n+=3,o).row:null,{command:"delete",relation:s,key:a})},"D"),U:__name(e=>{let n=1;const s=t[e.readUInt32BE(n)];n+=4;const a=75===e[n],i=a||79===e[n]?tuples(e,s.columns,n+=3,o):null;i&&(n=i.i);const{row:l}=tuples(e,s.columns,n+3,o);r(l,{command:"update",relation:s,key:a,old:i&&i.row})},"U"),T:__name(()=>{},"T"),C:__name(()=>{},"C")}).reduce(s,{})[e[0]](e)}function tuples(e,t,n,r){let o,s,a;const i=r.raw?new Array(t.length):{};for(let l=0;l<t.length;l++)o=e[n++],s=t[l],a=110===o?null:117===o?void 0:void 0===s.parser?e.toString("utf8",n+4,n+=4+e.readUInt32BE(n)):!0===s.parser.array?s.parser(e.toString("utf8",n+5,n+=4+e.readUInt32BE(n))):s.parser(e.toString("utf8",n+4,n+=4+e.readUInt32BE(n))),r.raw?i[l]=!0===r.raw?a:r.value.from?r.value.from(a,s):a:i[s.name]=r.value.from?r.value.from(a,s):a;return{i:n,row:r.row.from?r.row.from(i):i}}function parseEvent(e){const t=e.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!t)throw new Error("Malformed subscribe pattern: "+e);const[,n,r,o]=t;return(n||"*")+(r?":"+(-1===r.indexOf(".")?"public."+r:r):"")+(o?"="+o:"")}function largeObject(e,t,n=393216){return new Promise(async(r,o)=>{await e.begin(async e=>{let o;!t&&([{oid:t}]=await(e`select lo_creat(-1) as oid`));const[{fd:s}]=await(e`select lo_open(${t}, ${n}) as fd`),a={writable:async function writable({highWaterMark:e=16384,start:t=0}={}){return t&&await a.seek(t),new Me.Writable({highWaterMark:e,write(e,t,n){a.write(e).then(()=>n(),n)}})},readable:async function readable({highWaterMark:e=16384,start:t=0,end:n=1/0}={}){let r=n-t;return t&&await a.seek(t),new Me.Readable({highWaterMark:e,async read(e){const t=e>r?e-r:e;r-=e;const[{data:n}]=await a.read(t);this.push(n),n.length<e&&this.push(null)}})},close:__name(()=>e`select lo_close(${s})`.then(o),"close"),tell:__name(()=>e`select lo_tell64(${s})`,"tell"),read:__name(t=>e`select loread(${s}, ${t}) as data`,"read"),write:__name(t=>e`select lowrite(${s}, ${t})`,"write"),truncate:__name(t=>e`select lo_truncate64(${s}, ${t})`,"truncate"),seek:__name((t,n=0)=>e`select lo_lseek64(${s}, ${t}, ${n})`,"seek"),size:__name(()=>e`
|
|
5
5
|
select
|
|
6
6
|
lo_lseek64(${s}, location, 0) as position,
|
|
7
7
|
seek.size
|
|
@@ -226,4 +226,4 @@ import*as e from"path";import t,{join as n,dirname as r,relative as o,isAbsolute
|
|
|
226
226
|
WHERE user_id = ${fl}
|
|
227
227
|
AND role IN ('owner')
|
|
228
228
|
)
|
|
229
|
-
`}),index("subscriptions_owner_idx").on(e.userId,e.orgId)]);c(bl),b2(bl),_t();var Sl=sql`(SELECT NULLIF(current_setting('app.current_user_id', true), '')::uuid)`,vl=sql`users`,Cl=sc("free_credits_audit",{id:uuid("id").defaultRandom().primaryKey(),date:date("date").notNull().unique(),totalCreditsGiven:numeric("total_credits_given").notNull(),syncedAt:timestamp("synced_at",{withTimezone:!0}).notNull()},e=>[index("free_credits_audit_date_idx").on(e.date),pgPolicy("free_credits_audit_select_admin",{as:"permissive",to:"app_user",for:"select",using:sql`(SELECT admin FROM ${vl} WHERE id = ${Sl})`}),pgPolicy("free_credits_audit_insert_admin",{as:"permissive",to:"app_user",for:"insert",withCheck:sql`(SELECT admin FROM ${vl} WHERE id = ${Sl})`}),pgPolicy("free_credits_audit_update_admin",{as:"permissive",to:"app_user",for:"update",using:sql`(SELECT admin FROM ${vl} WHERE id = ${Sl})`}),pgPolicy("free_credits_audit_delete_admin",{as:"permissive",to:"app_user",for:"delete",using:sql`(SELECT admin FROM ${vl} WHERE id = ${Sl})`})]);c(Cl),b2(Cl),_t();var kl=sql`(SELECT NULLIF(current_setting('app.current_user_id', true), '')::uuid)`,Pl=sc("follows",{id:uuid("id").defaultRandom().primaryKey(),followerId:uuid("follower_id").references(()=>$c.id,{onUpdate:"cascade",onDelete:"cascade"}).notNull(),followedUserId:uuid("followed_user_id").references(()=>$c.id,{onUpdate:"cascade",onDelete:"cascade"}),followedOrgId:uuid("followed_org_id").references(()=>Dc.id,{onUpdate:"cascade",onDelete:"cascade"}),createdAt:timestamp("created_at",{withTimezone:!0}).defaultNow().notNull()},e=>[check("follows_exactly_one_target",sql`(followed_user_id IS NOT NULL AND followed_org_id IS NULL) OR (followed_user_id IS NULL AND followed_org_id IS NOT NULL)`),check("follows_no_self_follow",sql`follower_id != followed_user_id OR followed_user_id IS NULL`),uniqueIndex("follows_user_unique").on(e.followerId,e.followedUserId).where(sql`followed_user_id IS NOT NULL`),uniqueIndex("follows_org_unique").on(e.followerId,e.followedOrgId).where(sql`followed_org_id IS NOT NULL`),index("follows_follower_idx").on(e.followerId),index("follows_followed_user_idx").on(e.followedUserId),index("follows_followed_org_idx").on(e.followedOrgId),pgPolicy("follows_select_all",{for:"select",to:"app_user",using:sql`true`}),pgPolicy("follows_insert_own",{for:"insert",to:"app_user",withCheck:sql`follower_id = ${kl}`}),pgPolicy("follows_delete_own",{for:"delete",to:"app_user",using:sql`follower_id = ${kl}`}),pgPolicy("follows_select_public",{for:"select",to:"public_user",using:sql`true`})]);c(Pl),b2(Pl);var Tl=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=trackAPICallStart({method:e.method,endpoint:t}),o=await this.buildHeaders({headers:e.headers,span:r.span});let s;try{s=await this.makeRequest({url:n,options:e,headers:o})}catch(e){const t=new Oo({cause:e instanceof Error?e:void 0});throw r.end({statusCode:0,error:t}),t}if(!s.ok){const{error:e}=await this.handleErrorResponse({response:s});throw r.end({statusCode:s.status,error:e}),e}return r.end({statusCode:s.status}),e.stream?s.body:s.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e,span:t}){const n=await getAuthKey(),r=getTraceId(),o=t?.spanContext(),s=r&&o?.spanId?`00-${r}-${o.spanId}-01`:void 0,a=getTelemetryEnv(),i="prod"===a?"production":a;return{"Content-Type":"application/json",[yt.CLI_ENVIRONMENT]:i,...n?{Authorization:`Bearer ${n}`}:{},...s?{traceparent:s}:{},...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:Do.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"})}};function getPersonalSkillsDir(){return t.join(f.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return t.join(process.cwd(),".commandcode","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await D.access(r),r}catch{}const o=t.join(n,"skill.md");try{return await D.access(o),o}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await D.access(n);const e=await D.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await D.stat(t.join(n,e.name))).isDirectory()?e:null}catch{return null}return null}))).filter(e=>null!==e);return(await Promise.all(r.map(async e=>{try{const r=await resolveSkillFilePath({skillDir:t.join(n,e.name)});if(!r)return null;const o=await D.readFile(r,"utf-8"),{data:s}=Ue(o),a=Jo.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)}ln(),_t(),ln(),_t(),_t(),_t(),Ot(),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),_t(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),_t(),_t(),_t(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath"),_t();var Al=p.object({absolutePath:p.string().describe("The absolute path to the file to read"),offset:p.preprocess(e=>"string"==typeof e?parseInt(e,10):e,p.number().optional()).describe("Optional line number to start reading from (0-based index)"),limit:p.preprocess(e=>"string"==typeof e?parseInt(e,10):e,p.number().optional()).describe("Optional number of lines to read")});p.object({content:p.union([p.string(),p.instanceof(Buffer)]),contentType:p.enum(["text","binary"]),fileType:p.string(),size:p.number(),linesRead:p.number().optional()});var xl=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 xl("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=e.normalize(n);try{await R.access(s,w.constants.F_OK|w.constants.R_OK)}catch{throw new xl(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await R.stat(s)).isFile())throw new xl("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 xl("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new xl("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new xl("Limit must be > 0","INVALID_LIMIT");try{if(i){const e=await R.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 R.readFile(s,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof xl)throw e;throw new xl(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var Il={".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",...Il}[n]||"unknown"}function isBinaryFile(e){return Object.values(Il).includes(e)}async function readTextFileLines(e,t,n){const r=(await R.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),l=e.relative(process.cwd(),t),u=1e5;if(i.length>u){n.push({token:o,resolvedPath:t,content:"",tooLarge:!0});const e=`${l}`;r=r.replace(o,e);continue}n.push({token:o,resolvedPath:t,content:i});const d=`{${l}: ${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"),_t(),_t();var _l="read_file",Nl="edit_file",$l="write_file",Rl="read_directory",Dl="read_multiple_files",Ol="grep",Ll="shell_command",Ml="think",Fl="todo_write",Ul="ask_user_question",jl="kill_shell",Bl="web_search",ql="web_fetch",zl=__name(e=>e===Bl,"isWebSearchTool"),Wl=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],Hl=__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 Wl.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:zl(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),Vl=["create_file","delete_file",Nl,$l,Ll],Gl=[Ll];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}_t(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText"),_t(),_t(),_t();var Kl="2025-03-26",Jl={name:"command-code",version:"1.0.0"};Promise.resolve().then(()=>(Wn(),Mn)).then(({getPackageJson:e})=>{Jl.version=e().version??"1.0.0"}).catch(()=>{}),_t(),_t();var Ql=p.object({authorizationUrl:p.string(),tokenUrl:p.string(),clientId:p.string(),clientSecret:p.string().optional(),scopes:p.array(p.string()).optional()}),Yl=p.object({transport:p.enum(["stdio","http"]),enabled:p.boolean().default(!0),command:p.string().optional(),args:p.array(p.string()).optional(),url:p.string().optional(),headers:p.record(p.string(),p.string()).optional(),oauth:Ql.optional(),env:p.record(p.string(),p.string()).optional()}),Zl=p.object({mcpServers:p.record(p.string(),Yl)});_t(),Ot();var Xl="mcp.json";function getUserMcpConfigPath(){return e.join(f.homedir(),".commandcode",Xl)}function getLocalMcpConfigPath(t=process.cwd()){const n=Be(t);return e.join(f.homedir(),".commandcode","projects",n,Xl)}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 R.readFile(n,"utf-8"),o=JSON.parse(r),s=Zl.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 R.mkdir(s,{recursive:!0}),await R.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"),xn(),Cr(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers"),_t();var eu=class _StdioTransport extends je{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=I(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)}};_t(),Cr(),Tr();var tu=class _HttpTransport extends je{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":`${Jl.name}/${Jl.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(()=>(zr(),Ar));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(),vr);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(),vr);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}},nu=class extends je{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 eu?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?eu.fromConfig(e):tu.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:Kl,capabilities:{roots:{}},clientInfo:Jl});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}},ru=null;function getMcpConnectionManager(){return ru||(ru=new nu),ru}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"),gr();var ou=p.object({id:p.string(),timestamp:p.number(),type:p.literal("image"),source:p.object({type:p.enum(["base64","url"]),media_type:p.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:p.string()})}),su=p.object({id:p.string(),timestamp:p.number(),input:p.string(),output:p.string().optional(),metadata:p.record(p.string(),p.any()).optional(),images:p.array(ou).optional().default([])}),au=su.extend({role:p.literal("user")}),iu=su.extend({role:p.literal("assistant")}),cu=su.extend({role:p.literal("tool"),name:p.string(),description:p.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),lu=su.extend({role:p.literal("bash"),command:p.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),uu=su.extend({role:p.literal("system")}),du=su.extend({role:p.literal("error")}),mu=su.extend({role:p.literal("info")}),gu=su.extend({role:p.literal("taste-onboarding")}),pu=su.extend({role:p.literal("command-result"),hasError:p.boolean().optional(),details:p.string().optional()}),hu=su.extend({role:p.literal("ide-status"),status:p.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:p.string().nullable(),details:p.array(p.string()).optional()}),fu=p.discriminatedUnion("role",[au,iu,cu,lu,uu,du,mu,gu,pu,hu]),yu=__name((e,t)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),wu=__name((e,t)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),Eu=__name(e=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),bu=__name((e,t,n)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Su=__name(e=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),vu=__name(e=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Cu=__name(e=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),ku=__name(()=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Pu=__name((e,t=!1,n)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),Tu=__name((e,t,n)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),Au=__name(({name:e,input:t})=>{const n=Date.now();return fu.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"),xu=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return fu.parse(n)},"updateEntryWithOutput"),Iu=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),_u=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),Nu=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),$u=["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…"],Ru=__name(()=>$u[Math.floor(Math.random()*$u.length)],"getRandomLLMStatus"),Du=__name(e=>{switch(e){case _l:return"Read";case Nl:return"Edit";case $l:return"Write";case Rl:return"List";case Dl:return"Read Multiple";case Ol:return"Search";case Ll:return"Shell";case Fl:return"Todos";case Ml:return"Thinking…";case Bl:return"Web Search";case ql:return"Web Fetch";case Ul:return"Question";case"explore":return"Explore";case jl: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"),Ou=__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:ar})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),Lu=__name((e,t)=>{try{switch(e){case _l:case $l:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case Nl:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Rl:return toRelativePath(t.path||"directory");case Ol:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Ll: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 Fl:let o;try{o="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=Mu(o);return`${e?e.length:0} items`}catch{return"items"}case Ml:return t.content||"planning";case Dl:const s=t.include||[];return Array.isArray(s)?s.join(", "):"multiple files";case Bl:return t.query||"search";case ql:return t.url||"fetch";case Ul:return"User answered questions";case jl: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 Ou(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:ir})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),Mu=__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")}_t(),_t(),_t(),__name(formatOutput,"formatOutput");var Fu={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=Al.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")};_t(),_t();var Uu=p.object({filePath:p.string().describe("The absolute path to the file to edit"),oldValue:p.string().describe("The text to replace"),newValue:p.string().describe("The new text to insert"),replacementCount:p.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:p.boolean().optional().describe("Whether to replace all occurrences (default: false)")});p.object({path:p.string(),replacementsCount:p.number(),oldContent:p.string(),newContent:p.string()}),p.object({name:p.string(),message:p.string(),code:p.string().optional()}),_t(),_t(),_t();var ju=p.object({backupFileName:p.string().nullable(),version:p.number().int().positive(),backupTime:p.string().datetime()}),Bu=p.object({messageId:p.string().uuid(),trackedFileBackups:p.record(p.string(),ju),timestamp:p.string().datetime()});p.object({type:p.literal("file-history-snapshot"),messageId:p.string().uuid(),snapshot:Bu,isSnapshotUpdate:p.boolean()}),p.object({maxFileSize:p.number().int().positive().default(10485760),retentionDays:p.number().int().positive().default(30)});var qu=class extends Error{static{__name(this,"CheckpointError")}code;constructor(e,t){super(e),this.name="CheckpointError",this.code=t}};function getPathHash(e){const{filePath:t}=e;return`${j.createHash("sha256").update(t).digest("hex").slice(0,16)}-${t.length}`}function getBackupFileName(e){const{filePath:t,version:n}=e;return`${getPathHash({filePath:t})}@v${n}`}function getCommandCodeBasePath(){return t.join(f.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:n}=e;return t.join(getCommandCodeBasePath(),"file-history",n)}function getBackupFilePath(e){const{sessionId:n,backupFileName:r}=e;return t.join(getFileHistoryPath({sessionId:n}),r)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await D.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 D.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await D.writeFile(r,n);const e=await D.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 D.rename(r,t)}catch(e){try{await D.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await D.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await D.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}_t(),_t(),Ot(),__name(getPathHash,"getPathHash"),__name(getBackupFileName,"getBackupFileName"),__name(getCommandCodeBasePath,"getCommandCodeBasePath"),__name(getFileHistoryPath,"getFileHistoryPath"),__name(getBackupFilePath,"getBackupFilePath"),__name(getAvailableDiskSpace,"getAvailableDiskSpace"),__name(hasEnoughDiskSpace,"hasEnoughDiskSpace"),__name(ensureDirectoryExists,"ensureDirectoryExists"),__name(atomicWriteFile,"atomicWriteFile"),__name(getFileSizeBytes,"getFileSizeBytes"),__name(fileExists,"fileExists"),__name(getCurrentTimestamp,"getCurrentTimestamp"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod"),Sr();var zu={maxFileSize:10485760,retentionDays:30},Wu=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...zu,...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 D.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:hr.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 D.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new qu(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:hr.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await D.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 D.access(t,D.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 D.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await D.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await D.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}};_t(),gr(),Sr();var Hu=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new Wu({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:hr.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}};_t();var Vu=null;function initializeCheckpointService(e){const{sessionId:t}=e;return Vu=new Hu({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return Vu?Vu.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 v.access(n,C.F_OK|C.R_OK|C.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 l=(i.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===l)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let u,d;if(s)u=l;else if(u=a,u>l)throw createFileEditError(`Expected ${u} replacements, but only found ${l} occurrences`,"INSUFFICIENT_MATCHES");let m=0;if(s||u===l)d=i.split(r).join(o),m=l;else{d=i;for(let e=0;e<u;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+o+d.substring(e+r.length),m++)}}if(0===m)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await v.writeFile(n,d,"utf-8"),{path:n,replacementsCount:m,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"),_t(),__name(formatOutput2,"formatOutput");var Gu={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=Uu.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")};_t(),_t();var Ku=p.object({path:p.string().describe("The absolute path to the directory to read"),exclude:p.array(p.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:p.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});p.object({files:p.array(p.string()),directories:p.array(p.string())});var Ju=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 Ju("Path must be absolute, not relative","INVALID_PATH");try{if(!(await R.stat(n)).isDirectory())throw new Ju("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Ju)throw e;throw new Ju(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await R.readdir(n);let s=[];o&&(s=await loadGitIgnorePatterns(n));const a=[...r,...s],i=[],l=[];for(const r of t){if(shouldIgnoreEntry(r,a))continue;const t=e.join(n,r);try{const e=await R.stat(t);e.isDirectory()?l.push(r):e.isFile()&&i.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:i.sort(),directories:l.sort()}}catch(e){if(e instanceof Ju)throw e;throw new Ju(`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 R.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 R.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(qe(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")}_t(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),_t(),__name(formatOutput3,"formatOutput");var Qu={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=Ku.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")};_t(),_t();var Yu=p.object({filePath:p.string().describe("The absolute path where the file should be written"),content:p.string().describe("The content to write to the file")});async function writeFile4({filePath:e,content:n}){const o=e.startsWith("~/")?t.join(f.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 b(e)||await O(e,{recursive:!0}),await backupFileBeforeEdit({filePath:o}),await L(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}`}p.object({success:p.boolean(),message:p.string(),path:p.string().optional()}),_t(),__name(writeFile4,"writeFile"),_t(),__name(formatOutput4,"formatOutput");var Zu={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=Yu.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")};_t(),_t();var Xu=p.object({include:p.array(p.string()).describe("Array of glob patterns to include files"),exclude:p.array(p.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:p.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:p.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:p.string().optional().describe("Base directory for relative paths. Default: current working directory")}),ed=p.object({filePath:p.string(),content:p.string(),fileType:p.string(),size:p.number()});p.object({content:p.string(),filesRead:p.array(p.string()),errors:p.array(p.object({file:p.string(),error:p.string()})),fileDetails:p.array(ed)});var td=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}};_t();var nd=["**/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 ze(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 td("At least one include pattern must be provided","NO_PATTERNS");const i=t.resolve(a),l={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];s&&e.push(...nd);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});l.fileDetails.push(o),l.content+=`\n// File: ${e} (${r.fileType})\n`,l.content+=o.content,l.content+="\n",l.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);l.errors.push({file:e,error:n}),l.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return l}catch(e){if(e instanceof td)throw e;throw new td(`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"),_t(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var rd={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=Xu.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")};_t(),_t();var od=p.object({pattern:p.string().min(1,"Pattern is required"),include:p.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},p.array(p.string()).optional()),directory:p.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=I(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>cr)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>lr)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")}_t(),gr(),__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),_t(),__name(formatGrepResults,"formatGrepResults");var sd={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=od.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")};_t(),_t();var ad=p.object({pattern:p.string().min(1,"Pattern is required"),path:p.string().optional()}),id=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 id("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new id("Search path must be within the current working directory or an added directory","INVALID_PATH");const o=await ze(n,{cwd:e,ignore:Tt,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 D.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 id)throw e;if(e instanceof Error)throw new id(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new id("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")}_t(),Ot(),jt(),__name(globSearch,"globSearch"),_t(),__name(formatGlobResults,"formatGlobResults");var cd={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=ad.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")};_t(),_t();var ld=p.object({command:p.string().min(1,"Command cannot be empty"),args:p.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},p.array(p.string()).optional()),directory:p.string().optional(),timeout:p.preprocess(e=>"string"==typeof e?parseInt(e,10):e,p.number().optional())}),ud=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 ud("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(e.isAbsolute(o))throw new ud("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=e.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await D.stat(i)).isDirectory())throw new ud(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof ud)throw e;throw new ud(`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="",l="",u=!1;const d=r.length>0?We([n,...r]):n,m=setTimeout(()=>{if(!u){g.kill("SIGTERM");const e=Date.now()-a;o(new ud(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",i,l,e))}},s),g=I(d,[],e);g.stdout?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>cr)return l="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void g.kill("SIGTERM");i+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,g.kill("SIGTERM")}}),g.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>lr)return void(l+="\n[Error output truncated: too large]");l+=t}catch(e){l+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),g.on("close",(e,n)=>{u=!0,clearTimeout(m);const r=Date.now()-a;0===e?t({stdout:i.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):o(new ud(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,i.trim(),l.trim(),r))}),g.on("error",e=>{u=!0,clearTimeout(m);const t=Date.now()-a;o(new ud(`Failed to start command: ${e.message}`,"START_FAILED",null,null,i.trim(),l.trim(),t))})})}catch(e){if(e instanceof ud)throw e;throw new ud(`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")}_t(),gr(),__name(executeShellCommand,"executeShellCommand"),_t(),__name(formatShellCommandResult,"formatShellCommandResult");var dd={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=ld.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}`}_t(),_t(),__name(think,"think");var md={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)}_t(),_t(),__name(todoWrite,"todoWrite");var gd={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")}_t(),_t(),__name(askUserQuestion,"askUserQuestion"),_t(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var pd={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")};_t(),_t();var hd=p.object({port:p.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:p.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"}),fd=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=I(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 fd(`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 fd("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 fd(`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")}_t(),__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"),_t(),__name(formatKillshellResult,"formatKillshellResult");var yd={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=hd.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")};_t();var wd={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")};_t();var Ed={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")};_t(),_t(),_t(),_t(),_t(),Ot(),_t(),_t();var bd=["explore","plan","review","general"],Sd=[{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&&bd.includes(e.toLowerCase())}function getRootAgentDir(){return t.join(f.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await D.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await D.readFile(o,"utf-8"),{data:a,content:i}=Ue(s),l=a.name||r.replace(".md","");if(isReservedAgentName(l))return null;let u=a.tools||"";return"*"!==u&&'"*"'!==u||(u="*"),{name:l,description:a.description||"",tools:u,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"),_t(),Ot(),ln(),Dn(),Zt(),_t(),Ot(),ln(),_t(),Ot(),Sr(),xn(),_t();var vd=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext"),Cd=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(f.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Be(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=_("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await D.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:hr.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await D.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 D.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 D.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=vd(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=Lu(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=Lu(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 D.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 D.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await D.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 D.access(n)}catch{return[]}const e=(await D.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 D.stat(s),o=(await D.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=vd(s);const l=await _SessionManager.loadSessionMetaForId(e,n),u=l?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:s||"No messages",title:u||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 D.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 D.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 D.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await D.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 D.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 D.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 D.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 D.writeFile(r,s)}else await D.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 D.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 D.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 D.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=vd(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}};Zt(),Nn(),Dn(),xn();var kd=new Map,Pd=null;function getRequest(){return Pd||(Pd=new Tl({baseUrl:getApiBaseUrl()})),Pd}function stableStringify(e){return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map(stableStringify).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+stableStringify(e[t])).join(",")+"}"}function generateCacheKey(e,t){return`${e}:${stableStringify(t)}`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:vt,max_tokens:80,temperature:.3,stream:!0},threadId:crypto.randomUUID()}}async function getAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced();let n;e===St.ANTHROPIC&&(n=await rn.getValidAccessToken(),validateOAuthToken({token:n,provider:e}));const r={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(r[yt.OAUTH_TOKEN]=`Bearer ${n}`),r}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=kd.get(n);if(r)return kd.delete(n),kd.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 ${wt.ALPHA.GENERATE} with model: ${vt}`);const s=e.post({endpoint:wt.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=He.fromReadableStream(a);let l="",u=null;if(i.on("text",e=>{l+=e}),i.on("error",e=>{u=e}),await i.finalMessage(),u)throw u;dlog(`[ToolDescription] raw response: "${l}"`);const d=cleanDescription(l);if(d){if(kd.size>=100){const e=kd.keys().next().value;void 0!==e&&kd.delete(e)}kd.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=f.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"),_t(),_t(),Ot(),__name(isPlanPath,"isPlanPath");var Td=["edit_file","delete_file","shell_command","todo_write","kill_shell"],Ad=["exit_plan_mode"],xd=["enter_plan_mode"];function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!Ad.includes(e.name)):"plan"===n?t.filter(e=>!Td.includes(e.name)&&!xd.includes(e.name)):t.filter(e=>!Ad.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 Td.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"),_t(),gr();var Id=ur,_d=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)>Id}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"),_t(),__name(sleep,"sleep"),_t(),xn();var Nd=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(h.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return e.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const t=h.homedir();return e.join(t,".commandcode","AGENTS.md")}function getProjectMemoryPaths(t){return[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:b(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(b(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:b(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return b(e)&&A(e).isFile()?await R.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 l=a;for(const t of i){const s=t[1];let a=s;s.startsWith("~/")?a=e.join(h.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);l=l.replace(t[0],`\n# Imported from ${s}\n${e}\n`)}}return l=l.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>s[parseInt(t)]),l}async function loadAllMemories(t,n){const r=new Map,o=getEnterpriseMemoryPath();if(b(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const s=getUserMemoryPath();if(b(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(b(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(b(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 b(r)||await R.mkdir(r,{recursive:!0}),b(t)||await R.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const o=I(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 b(n)||await R.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}}_t(),Ot(),__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"),Nn();var $d=new Nd("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 l=null;const u=Date.now();let d=null;try{const m=i?.permissionMode||"standard",g=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}),clientTools:r,serverTools:o,mode:m});let p=Date.now();const h=10,f=[];if(i?.onFeedUpdate){const e=Lu(t.name,n);l=Au({name:t.name,input:e}),i.onFeedUpdate(l)}d=setInterval(()=>{if(i?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},i.onFeedUpdate(l)}},1e3);const y=await getConfiguredProvider(),w=await isOAuthEnforced();let E;y===St.ANTHROPIC&&(E=await rn.getValidAccessToken(),validateOAuthToken({token:E,provider:y}));const b=getApiBaseUrl(),S=new Tl({baseUrl:b});let v=0;const C=[];let k=n?.messages;if("string"==typeof k)try{k=JSON.parse(k)}catch(e){k=[]}if(Array.isArray(k)&&k.length>0)for(const e of k)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&C.push({role:"user",content:t})}const P={stream:!0,messages:C,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:g,model:`anthropic:${getConfiguredModel()}`},T=await isTasteLearningEnabled(),A={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.TASTE_LEARNING]:T.toString(),[yt.INTERNAL_TEAM_FLAG_HEADER]:w.toString()};E&&(A[yt.OAUTH_TOKEN]=`Bearer ${E}`);const x=getEnvironmentContext(),I=await getMemoryContent([]),_=crypto.randomUUID();let N="",$=!0;const R=__name(()=>{$d.debug("[Agent] Abort signal triggered, stopping immediately"),$=!1,d&&(clearInterval(d),d=null)},"abortHandler");i?.abortSignal&&i.abortSignal.addEventListener("abort",R);try{for(;$;){if(i?.abortSignal?.aborted)throw $d.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:S,body:{mode:"custom-agent",config:x,memory:I,threadId:_,params:{...P,messages:C}},headers:A,abortSignal:i?.abortSignal,onTextDelta:__name(e=>{v+=estimateTokens(e);const t=Date.now();if(i?.onFeedUpdate&&l&&t-p>=h){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:v,elapsedSeconds:e}},i.onFeedUpdate(l),p=t}},"onTextDelta")});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(v=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if(N=t.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(t,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&&C.push({role:"assistant",content:e}),$=!1;break}const r=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);r.length>0&&C.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=Vl.includes(t.name),g=Gl.includes(t.name)?generateToolDescription(t.name,n).catch(()=>null):Promise.resolve(null);if(r&&i?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await g;if(!await i.onPermissionRequest(t.name,n,e)){$d.debug(`Permission denied for tool: ${t.name}`),a=!0;break}d=setInterval(()=>{if(i?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},i.onFeedUpdate(l)}},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,$d.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,$d.debug(`Resolved input for ${t.name}: ${Lu(t.name,n)}`)):$d.debug(`No path resolution needed for ${t.name}: ${Lu(t.name,n)}`)}if(i?.onFeedUpdate&&l){const e=Lu(t.name,n);f.push({name:t.name,input:e}),f.length>3&&f.shift();const r=Date.now(),o=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:v,elapsedSeconds:o,recentTools:[...f]}},$d.debug(`Updating agent with recentTools (${f.length} tools): ${JSON.stringify(f)}`),i.onFeedUpdate(l)}const p=await executeTool(t.name,n,{abortSignal:i?.abortSignal,permissionMode:m});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");const h=checkToolOutputTokensLimit(p,t.name);if(o.push({type:"tool_result",tool_use_id:t.id,content:h}),s.add(t.id),i?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:v,elapsedSeconds:t,recentTools:[...f]}},i.onFeedUpdate(l)}$d.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),$d.error(`Tool execution failed: ${t.name} - ${n}`)}}if(a){const e=C[C.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:C.pop()}$=!1;break}const g=[...o];C.push({role:"user",content:g})}}finally{i?.abortSignal&&i.abortSignal.removeEventListener("abort",R)}if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:N||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:v,elapsedSeconds:t}},i.onFeedUpdate(l)}return N||"DONE"}catch(e){if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&l){const t=Date.now(),n=(t-u)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||i?.abortSignal?.aborted;l={...l,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:u,endTime:t,tokensUsed:l?.metadata?.tokensUsed||0,elapsedSeconds:n}},i.onFeedUpdate(l)}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:wt.ALPHA.GENERATE,signal:o,headers:r}),a=He.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 l=await a.finalMessage();if(i)throw i;return l}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);$d.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 Lo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof Fo||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 Lo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof Fo||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}=Hl({serverToolBlock:e,contentBlocks:r}),s=Lu(e.name,e.input),a={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:s,output:o?Iu(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 Rd=new Map,Dd=null;function initializeAgentManager(e){Dd=e}async function loadAgentTools(){if(!Dd)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Rd.clear();for(const e of Sd){const t=agentToTool(e,Dd);Rd.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Dd);Rd.set(t.name,t)}}async function getAgentTools(){return 0===Rd.size&&await loadAgentTools(),Array.from(Rd.values())}async function getAgentTool(e){return 0===Rd.size&&await loadAgentTools(),Rd.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(h.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"),_t(),Ot(),__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"),Sr();var Od=[Fu,Gu,Qu,Zu,rd,sd,cd,dd,md,gd,pd,yd,wd,Ed],Ld=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],Md=new Map(Od.map(e=>[e.name,e])),Fd=new Set([...Od.map(e=>e.name),...Ld.map(e=>e.name)]);function isAgentTool(e){return!Fd.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=Md.get(e);if(s||(s=await getAgentTool(e)),!s){const t=await getAgentTools(),n=[...Array.from(Md.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=(!Md.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=[...Od],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,...Ld]}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 Ud={};Od.forEach(e=>{Ud[e.name]=toPascalCase(e.name)}),Ld.forEach(e=>{Ud[e.name]=toPascalCase(e.name)});var jd={};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(Ud).forEach(([e,t])=>{jd[t]=e}),initializeAgentManager({clientTools:Od,serverTools:Ld,toolsMap:Md,displayNameToToolName:jd}),_t(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors"),Sr(),Ot(),Zt(),Nn(),Dn(),_t(),Ot(),ln(),xn(),_t();var Bd=new class extends je{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:l,categories:u,storage:d}=e,m={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:l,categories:u,storage:d};this.events.unshift(m),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",m)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}};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=[],l=[];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&&l.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:a,upgraded:i,downgraded:l}}_t(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings"),Nn(),Dn(),Sr();var qd=new Nd("LearningAgent"),zd=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:hr.LEARNING_AGENT,heading:"Learning pass failed"}}),Bd.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)];Bd.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),l=t.slice(i);let u=0,d=!1;dlog(`[LearningAgent] analyzing ${s} new messages for patterns`);const m=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(l,null,2)}`}];for(;u<this.maxTurns;){const e=await this.callLearningAPI({conversation:m}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.name).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),m.push({role:"assistant",content:e.content}),m.push({role:"user",content:n}),u++}u>=this.maxTurns&&qd.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Bd.addEvent({type:"no_learnings",message:"no changes to taste"}),Bd.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 w.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 w.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=>{Bd.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Bd.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Bd.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(!w.existsSync(this.tasteDir)){w.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");w.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!w.existsSync(t))return!1;const n=w.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let 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");w.mkdirSync(r,{recursive:!0}),Bd.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const a=`# ${t.name}\n${t.learnings.join("\n")}\n`;w.writeFileSync(s,a,"utf-8");const i=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;o=o.replace(t.fullSection,i)}return w.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 w.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(t){const{dir:n,prefix:r}=t,o=w.readdirSync(n,{withFileTypes:!0});let s="";for(let t=0;t<o.length;t++){const a=o[t],i=t===o.length-1,l=i?"└── ":"├── ";if(a.isDirectory()){s+=`${r}${l}${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=(w.readFileSync(e.join(n,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;s+=`${r}${l}${a.name} (${t} learnings)\n`}else s+=`${r}${l}${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===St.ANTHROPIC&&(o=await rn.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[yt.OAUTH_TOKEN]=`Bearer ${o}`);const a=await this.getTasteTools(),i=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${i})`);const l={conversation:t,tools:a,model:i,threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:wt.ALPHA.TASTE.LEARN,body:l,headers:s,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),u++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${d.message}`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_client_error"}),context:{component:hr.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(u>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:hr.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":u}}),d;const n=1e3*Math.pow(2,u);dlog(`[LearningAgent] retrying API call (${u}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw d||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return w.existsSync(r)}};_t(),Ot(),ln(),Zt(),Nn(),Dn(),xn();var Wd="claude-haiku-4-5-20251001",Hd=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===St.ANTHROPIC&&(o=await rn.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[yt.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:${Wd}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let l=0,u=null;for(;l<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${wt.ALPHA.GENERATE} with model: ${Wd}`);const e=await this.request.post({endpoint:wt.ALPHA.GENERATE,body:i,headers:s,stream:!0});if(!e)throw new Error("No response stream received");const t=He.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){u=e instanceof Error?e:new Error(String(e)),l++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${u.message}`),u;if(l>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),u;const n=1e3*Math.pow(2,l);dlog(`[CompactAgent] retrying API call (${l}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}throw u||new Error("Compact API call failed")}};async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!b(n))return null;const r=await R.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={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};if(e===St.ANTHROPIC){const e=await rn.getValidAccessToken();e&&(n[yt.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:vt,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},l=await buildAuthHeaders(),u=await r.post({endpoint:wt.ALPHA.GENERATE,body:i,headers:l,stream:!0}),d=He.fromReadableStream(u);let m="";d.on("text",e=>{m+=e}),await d.finalMessage(),m=m.trim(),m&&(await n.saveSessionTitle(m),dlog("Session",`Title generated: ${m}`))}_t(),Ot(),__name(getTasteContent,"getTasteContent"),xn(),_t(),ln(),Zt(),Nn(),Dn(),xn(),Ot(),__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle");var Vd=new Nd("ContextEngine"),Gd=200,Kd=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 Tl({baseUrl:n}),this.callbacks=e,this.sessionManager=new Cd(t),this.learningAgent=new zd({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new Hd({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new Tl({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,Vd.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),Vd.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=yu("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>Vd.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n,r){let o=e,s=[];try{const t=await processFileReferences(e);if(o=t.processedContent,s=t.fileReferences,s.length>0){const e=s.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(o=`${n}\n\n${o}`);const a=yu(r??e);t&&t.length>0&&(a.metadata={...a.metadata,images:t}),s&&s.length>0&&(a.metadata={...a.metadata,fileReferences:s}),this.callbacks.onFeedUpdate(a);const i=[];t&&t.length>0&&t.forEach(e=>{i.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),o.trim()&&i.push({type:"text",text:o});const l={role:"user",content:i},u=crypto.randomUUID(),d=this.createMessageWithMeta(l,{messageId:u});this.addMessageAndSync(d),this.checkpointManager.createSnapshot({messageId:u}).catch(e=>Vd.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,a).catch(e=>Vd.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const m=await this.processMessages();return this.triggerTitleGeneration(),m}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){Vd.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=Eu(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>Vd.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>Vd.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=yu(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>Vd.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=Eu(e);this.callbacks.onFeedUpdate(t)}const l=await this.executeToolBlocks({toolBlocks:s}),{toolResults:u,executedToolIds:d,permissionDenied:m}=l;if(m){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const g=[...u];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){g.push({type:"text",text:t});const e=yu(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:g})),this.sessionManager.saveMessages(this.messages).catch(e=>Vd.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&Vd.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){Vd.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return Vd.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.sanitizeMessagesForAPI(this.messages.map(e=>e.message))}sanitizeMessagesForAPI(e){const t=[];for(const n of e){if("user"===n.role&&Array.isArray(n.content)){const e=t.length>0?t[t.length-1]:null,r=new Set;if("assistant"===e?.role&&Array.isArray(e.content))for(const t of e.content)"tool_use"===t.type&&r.add(t.id);const o=n.content.filter(e=>"tool_result"!==e.type||r.has(e.tool_use_id));o.length>0&&t.push({...n,content:o});continue}const e=t.length>0?t[t.length-1]:null;if(e&&e.role===n.role){const t=Array.isArray(e.content)?e.content:[{type:"text",text:e.content}],r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];e.content=[...t,...r];continue}t.push({...n})}return t}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};Vd.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:_d}),{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=Ro.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:wt.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===St.ANTHROPIC&&(o=await rn.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};Vd.debug(`calling API (${s.model}, ${this.messages.length} msgs, ${t.length} tools)`);const i=await isTasteLearningEnabled(),l={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.TASTE_LEARNING]:i.toString(),[yt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(l[yt.OAUTH_TOKEN]=`Bearer ${o}`),{body:a,headers:l}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++){let r;try{const t=interceptStreamErrors({responseStream:await this.request.post({body:e.body,stream:!0,endpoint:wt.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const o=He.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:hr.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:hr.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:hr.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),l=Math.max(i,1e3),u=Math.min(l,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:u,signal:this.abortController?.signal})}}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){const{message:t}=this.extractErrorMessage(e),n=t?.toLowerCase()||"",r="Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")||this.requestInterrupted||this.abortController?.signal.aborted,o="Insufficient credits"===t||n.includes("insufficient credits"),s=e instanceof Mo||401===e?.status||e instanceof Fo||403===e?.status,a=e?.type||e?.error?.type,i="rate_limit_error"===a||429===e?.status||n.includes("rate limit"),l="overloaded_error"===a||529===e?.status||n.includes("overloaded");return r||o||s||i||l}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.error?.message){const n=parseEmbeddedErrorJSON(e.error.message);return n?{...n,status:n.status||t}:{status:t,type:e.error.type||null,message:e.error.message}}const n=e?.message;if("string"==typeof n){const e=parseEmbeddedErrorJSON(n);if(e)return{...e,status:e.status||t}}return{status:t,type:e?.type||null,message:e?.message||null}}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.requestInterrupted||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=this.extractErrorMessage(e),n=t.status,r=t.type,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 Fo||403===e?.status)return e;if(e instanceof Mo||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 l="";if(o)if(o.includes("Invalid 'Authorization' header"))l='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>Gd&&(t=t.substring(0,Gd)+"..."),l=`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"),u="rate_limit_error"===r||s.includes("rate limit");l+=a?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":u?'\n\nYou can wait a moment and try again, or type "continue" to retry.':'\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==i&&(l+=`\nRequest ID: ${i}`)}else if(e.toString){const t=e.toString();l=t.length>Gd?t.substring(0,Gd)+"...":t}else l="Error: Unknown error occurred";return new Error(l)}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=Vl.includes(s.name),i=Gl.includes(s.name)?this.getToolDescription(s):Promise.resolve(null);let l=null;try{a&&this.callbacks.onPermissionRequest&&(l=await i);const t=await this.checkToolPermission(s,l);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,l),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===l&&(l=await i),r.push({toolBlock:s,entryId:e,description:l})}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:l}=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,l))}}}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 Vd.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 Vl.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=Lu(e.name,e.input),r={..."edit_file"===e.name?e.input:{},permissionDenied:!0},o={...bu(e.name,n,r),id:t},s=xu(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=Lu(e.name,s),i={...bu(e.name,a,o),id:n,...r?{description:r}:{}},l=xu(i,t);this.callbacks.onFeedUpdate(l)}showToolError(e,t,n,r){const o=Lu(e.name,e.input),s="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,a={...bu(e.name,o,s),id:n,...r?{description:r}:{}},i=xu(a,Iu(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=Eu(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:o}=Hl({serverToolBlock:e,contentBlocks:n}),s=Lu(e.name,e.input),a=bu(e.name,s),i=xu(a,o?Iu(r):r);this.callbacks.onFeedUpdate(i)}if(t.trim()){const e=Eu(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:_d})}async checkAndCompactIfNeeded(){const e=Math.floor(_d*At.TIER_1_THRESHOLD),t=Math.floor(_d*At.TIER_2_THRESHOLD),n=Math.floor(_d*At.TIER_3_THRESHOLD);try{if(this.contextTokensUsed>n){Vd.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){Vd.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${At.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT);return Vd.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void this.emitAutoCompactInfo(e.tokensSaved)}if(this.contextTokensUsed>e){const t=this.countToolCalls(),n=At.TIER_1_KEEP_COUNT;if(t>n){Vd.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);Vd.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){Vd.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){e>0&&this.callbacks.onFeedUpdate(wu(`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:_d}),{toolsRemoved:s.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return Vd.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT);Vd.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});Vd.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),l=Math.max(0,s-a+i);this.contextTokensUsed=l,this.callbacks.onContextUsageUpdate?.({current:l,limit:_d}),Vd.debug(`Tier 3 summarization complete: reduced from ${s} to ~${l} tokens`)}catch(e){Vd.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=At.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const 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:_d})),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}}_t(),_t(),gr(),_t(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var Jd=["no job control","cannot set terminal process group"],Qd=null;function getShellInfo(){return Qd||(Qd=detectUserShell()),Qd}__name(getShellInfo,"getShellInfo");var Yd=__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(),l="bash"===i.type||"zsh"===i.type,u=l?i.path:"/bin/bash",d=I(u,l?["-i","-c",e]:["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let m="",g="",p=null;n>0&&(p=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),a({stdout:m,stderr:g+(g?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(m.length+n.length>cr){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void a({stdout:m,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}m+=n}catch(e){g+=`\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(g.length+t.length>lr)return void(g+="\n[Error output truncated: too large]");g+=t}catch(e){g+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{p&&clearTimeout(p);const n=l?g.split("\n").filter(e=>!Jd.some(t=>e.includes(t))).join("\n"):g;a({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{p&&clearTimeout(p),a({stdout:m,stderr:g+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),Zd=__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"),Xd=__name(()=>{const[e,t]=z({isExecuting:!1,currentCommand:null});return{executeBash:V(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Yd(e,{timeout:3e4,cwd:process.cwd()}),o=Zd(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]=xu(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]=xu(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");_t(),_t(),Ot();var em=class extends je{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 D.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 D.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await D.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 D.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 D.mkdir(n,{recursive:!0});try{const t=await D.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 D.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},tm=__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 em(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:V(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:V(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:V(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),a(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),a(!1)}},[t]),clearSessionPermissions:V(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:V(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:V((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:V(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting: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)}_t(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),_t();var nm=__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(f.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,o=""){if(E.existsSync(n))try{const s=E.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=E.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===T(process.cwd()).length}catch{return!1}}_t(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),cn(),_t(),Ot(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),_t(),__name(isDirectoryEmpty,"isDirectoryEmpty"),_t();var rm='You are an expert code reviewer. Do follow these steps:\n\nGather PR context using the GitHub CLI:\n1. When no PR number is given, list open PRs with `gh pr list` and ask which one to review\n2. Fetch PR metadata via `gh pr view <number>`\n3. Retrieve the changeset with `gh pr diff <number>`\n4. One go gather context: Run gh pr view <number> && echo "---DIFF---" && gh pr diff <number>\n5. Analyze the changes and provide a thorough code review that includes:\n\t- Overview of the PR is doing\n\t- Analysis of the code quality and style\n\t- Give specific suggestions for improvement\n\t- Highlight any potential bugs/issues or risks\n\t- Score PR on a scale of 1-5 based on overall table with quality and readiness for merging\nKeep your review concise, less wordy, but thorough.\nFocus on:\n- Correctness of code\n- Following project conventions\n- Performance issues and implications\n- Test coverage\n- Security considerations\n\nBe less wordy. If you make a table, don\'t go over 60pts.\nFormat your review in sections and bullets. Do NOT print hr rulers.\nDo NOT add separator lines or horizontal lines. "--------------------------------------------------------------------------------------------------------------------------------------\n -----------------"';function buildReviewPrompt({prNumber:e}){const t=e.trim();return t?`${rm}\n\nReview PR number: ${t}`:`${rm}\n\nReview PR number: `}async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new Tl({baseUrl:e});return await t.get({endpoint:wt.ALPHA.WHOAMI})}__name(buildReviewPrompt,"buildReviewPrompt"),_t(),Ot(),__name(getAuthenticatedEntity,"getAuthenticatedEntity"),Rn(),_t();var om=["Code","Code - Insiders","VSCodium","Cursor"],sm="Code",am={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},im=__name(e=>m(e).href,"formatPathForTerminal"),cm=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),lm=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),um=__name(({home:t,configSegments:n,variants:r})=>{for(const o of r){const r=lm({home:t,configSegments:n,variant:o});if(w.existsSync(e.dirname(r)))return o}return null},"findExistingVariant"),dm=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&mm(t.when)},"isTerminalShiftEnterBinding"),mm=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),gm=__name(e=>{const t=Ve(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),pm=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),hm=__name(({error:e,content:t})=>{const n=e.message;return pm(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"),fm=__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"),ym=__name(e=>{try{const t=Ve(e),n=fm(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:hm({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),wm=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:im(t)}),"createSuccessResult"),Em=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:im(t)}),"createErrorResult"),bm=__name(()=>{const t=h.homedir(),n=h.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=cm(n);if(!r)return lm({home:t,configSegments:[".config"],variant:sm});const o=um({home:t,configSegments:r,variants:om});return lm({home:t,configSegments:r,variant:o??sm})},"getVSCodeKeybindingsPath"),Sm=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)dm(n)&&(n.command===am.command&&n.args?.text===am.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),vm=__name(t=>{try{if(!w.existsSync(t)){const n=e.dirname(t);return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=w.readFileSync(t,"utf-8");if(gm(n))return{rawContent:n,keybindings:[]};const r=ym(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:Em({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):Em({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return Em({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),Cm=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(am,null,2);if(gm(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return Em({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?Em({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=bm();try{const t=vm(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=Sm(r);if(o.hasConflicting)return Em({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return wm({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=Cm({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(w.writeFileSync(e,s,"utf-8"),wm({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return Em({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"),_t(),Ot(),xn(),_t();var km={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return km[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Be(t);return e.join(f.homedir(),".commandcode","projects",n)}function getGlobalProjectSettingsPath(t=process.cwd()){return e.join(getGlobalProjectSettingsDir(t),"settings.json")}async function loadGlobalProjectSettings(e=process.cwd()){try{const t=getGlobalProjectSettingsPath(e),n=await R.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 R.mkdir(o,{recursive:!0}),await R.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),Bd.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 R.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"),_t(),xn(),Ot(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),_t(),xn();var Pm=e.join(h.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=x(e,{encoding:"utf8"}),n=Ge.createInterface({input:t,crlfDelay:1/0});for await(const e of n)if(e.trim()){try{const r=JSON.parse(e);if("session_meta"===r.type&&r.payload?.cwd)return n.close(),t.destroy(),{cwd:r.payload.cwd,id:r.payload.id,timestamp:r.payload.timestamp}}catch{}break}return n.close(),t.destroy(),null}catch{return null}}async function findAllSessionFiles(t,n){const r=[];try{await R.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const o=await R.readdir(t);for(const s of o){if(!/^\d{4}$/.test(s))continue;const o=e.join(t,s);if(!(await R.stat(o)).isDirectory())continue;const a=await R.readdir(o);for(const t of a){if(!/^\d{2}$/.test(t))continue;const a=e.join(o,t);if(!(await R.stat(a)).isDirectory())continue;const i=await R.readdir(a);for(const o of i){if(!/^\d{2}$/.test(o))continue;const i=e.join(a,o);if(!(await R.stat(i)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${s}/${t}/${o}`});const l=(await R.readdir(i)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(i,t));r.push(...l)}}}}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(Pm,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 l=await processFilesInBatches(a,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===o)try{const r=await R.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(...l);const u=r>0?s.slice(0,r):s;return dlog(`[Codex] matched ${u.length} sessions for project`),n?.({phase:"complete",totalFiles:a.length,processedFiles:a.length,matchedSessions:u.length}),u.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await R.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 R.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(h.homedir(),".claude","projects");await R.access(t);const o=getProjectDirName(process.cwd()),s=(await R.readdir(t)).filter(e=>e===o);for(const o of s){const s=e.join(t,o);if((await R.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"),_t(),Ot(),_t();var Tm="# Taste (Continuously Learned by CommandCode.ai)",Am=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return Am.test(t)?t.replace(Am,`$1${Tm}`):t}__name(migrateHeader,"migrateHeader");var xm=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await R.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await R.access(r);const e=await R.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await R.writeFile(r,t,"utf-8")}catch{await R.writeFile(r,Tm+"\n\n")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await R.access(n),!0}catch{return!1}}};Nn(),Dn(),sn(),_t(),_t(),Ot(),_t(),_t(),Ot();var Im=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),_m=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Nm=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=z("idle"),[a,i]=z(""),l=[...Od.map(e=>e.name),...Ld.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void i("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?Im():_m();await D.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),a=Array.from(e.selectedTools).map(e=>Ud[e]||e).join(", "),i=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(a),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${i}\n---\n\n${e.sysPrompt}\n`;await D.writeFile(s,u,"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");X((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||u()});const d=Array.from(e.selectedTools).map(e=>Ud[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return q.createElement(K,{flexDirection:"column",gap:1},q.createElement(K,{flexDirection:"column"},q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"Name:"),q.createElement(J,{color:"gray"},e.agentType)),q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"Location:"),q.createElement(J,{color:"gray"},m)),q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"Tools:"),q.createElement(J,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"Description"),q.createElement(J,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),q.createElement(J,{color:"gray"},e.ccToolDefinition),q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"System Prompt:")),q.createElement(J,{color:"gray"},e.sysPrompt),!r&&q.createElement(K,{marginTop:1},"idle"===o&&q.createElement(K,{gap:1},q.createElement(J,{color:"green",dimColor:!0},"Press"),q.createElement(J,{color:"green",bold:!0},"Enter"),q.createElement(J,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===o&&q.createElement(J,{color:"yellow"},"Saving agent..."),"saved"===o&&q.createElement(J,{color:"green"},"✓ ",a),"error"===o&&q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"red"},"✗ Error: ",a),q.createElement(J,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),$m=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=z("menu"),a=[...Od.map(e=>e.name),...Ld.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=>jd[e]||e);i=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i},u=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(X((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return q.createElement(K,{flexDirection:"column"},q.createElement(Nm,{config:l,onSaveComplete:()=>s("menu"),viewOnly:!0}),q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray"},"Press Enter to go back")));if("edit"===o)return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"yellow"},"Edit functionality coming soon..."),q.createElement(J,{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 D.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return q.createElement(K,{flexDirection:"column",gap:1},q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"red"},"Delete agent"),q.createElement(J,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),q.createElement(K,null,q.createElement(Ke,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"},` ${t}`)})))}return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"white",bold:!0},e.name),q.createElement(K,{marginTop:1},q.createElement(Ke,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"},` ${t}`)})),q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Rm=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=z([]),[s,a]=z([]),[i,l]=z([]),[u,d]=z(!0),[m,g]=z(!1),[p,h]=z(null),[y,w]=z(!1),E=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),b=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),S=__name(async(e,n)=>{try{g(!1);const r=(await D.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await D.readFile(o,"utf-8"),{data:a,content:i}=Ue(s);let l=a.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:a.name||r.replace(".md",""),description:a.description||"",tools:l,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(E(),"personal"),S(b(),"project")]),n=Sd.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),l(n),d(!1)},"loadAgents")()},[m]);const v=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{v.push({label:e.name,value:e.filePath})}),s.forEach(e=>{v.push({label:e.name,value:e.filePath})});const C=r.length+s.length,k=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(h(e),w(!0))}},"handleAgentSelect");if(u)return q.createElement(J,{color:"gray"},"Loading agents...");if(y&&p){const e=p.filePath.startsWith("__builtin__:");return q.createElement($m,{agent:p,onBack:()=>{w(!1),h(null)},setRevalidateAgent:g,isReadOnly:e})}const P=__name(({isSelected:e,label:t})=>{const n=v.find(e=>e.label===t),o=n?.value||"",a=r[0]?.filePath===o,i=s[0]?.filePath===o;return q.createElement(K,{flexDirection:"column"},a&&r.length>0&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray",bold:!0},"User agents")),i&&s.length>0&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray",bold:!0},"Project agents")),q.createElement(K,null,q.createElement(J,{color:"white"},e?">":" "),q.createElement(J,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return q.createElement(K,{flexDirection:"column"},q.createElement(K,{marginBottom:1},q.createElement(J,{color:"white",bold:!0},"Agents"),C>0?q.createElement(J,{color:"gray"}," ","(",C," agent",C>1?"s":"",")"):q.createElement(J,{color:"gray"}," (No custom agents)")),n&&q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{color:"green",dimColor:!0},"Created agent: ",n)),q.createElement(Ke,{items:v,onSelect:k,indicatorComponent:()=>null,itemComponent:P}),i.length>0&&q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(J,{color:"gray",bold:!0},"Default agents"),i.map(e=>q.createElement(J,{key:e.filePath,color:"gray"}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(J,{color:"gray"},"Create specialized subagents that Command Code can delegate to."),q.createElement(J,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");_t(),Ot(),_t(),_t(),Ot();var Dm=__name(({onSelect:e})=>q.createElement(Ke,{items:[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>q.createElement(J,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector");_t(),wn(),Ot(),Sn(),Tn();var Om=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=z(!1),[g,p]=z(!1),h=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),f=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){p(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(p(!0),t.isPasteEnd){p(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[g,a]);return"agentType"===e?q.createElement(q.Fragment,null,q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(Ud).some(e=>Be(e)===Be(t))||Object.keys(Ud).some(e=>Be(e)===Be(t)))&&q.createElement(J,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Be(t))&&q.createElement(J,{color:"red"},"⚠ This name is reserved. Reserved names:"," ",bd.join(", "))),q.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Be(t);Object.values(Ud).some(t=>Be(t)===e)||Object.keys(Ud).some(t=>Be(t)===e)||isReservedAgentName(e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?q.createElement(q.Fragment,null,q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"white"},"Enter the system prompt for your agent:"),q.createElement(J,{color:"gray"},"Be comprehensive for best results.")),q.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:h,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?q.createElement(q.Fragment,null,q.createElement(J,{color:"white"},"When should ","Command Code"," use this agent?"),q.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:f,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");_t();var Lm=__name(({onSelect:e})=>q.createElement(Ke,{items:[{label:"1. Generate with Command Code (recommended)",value:"recommended"},{label:"2. Manual configuration",value:"manual"}],onSelect:t=>{"recommended"!==t.value&&"manual"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>q.createElement(J,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector");_t(),wn(),_t();var Mm=["·","○","◇","☆","✧","☆","◇","○","⌘"],Fm=[8,5,4,4,4,4,4,5,20],Um=[5,4,4,4,4,4,5],jm=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Fm.length;e++)if(n+=Fm[e],t<n)return Mm[e];const r=t-58;n=0;for(let e=0;e<Um.length;e++)if(n+=Um[e],r<n)return Mm[7-e];return Mm[0]},"getWaveSymbol"),Bm=["#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<Bm.length?Bm[n]:"#B799E6"},"getCharColor");return q.createElement(J,null,e.split("").map((e,t)=>q.createElement(J,{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)},[]),q.createElement(J,{color:"#E4CCFF",bold:!0},jm(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var qm=__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 q.createElement(K,{width:s,height:1,paddingLeft:0,marginLeft:0},q.createElement(CMDIcon,null),q.createElement(K,{marginRight:1},q.createElement(ShimmerText,{text:e})),a?q.createElement(q.Fragment,null,q.createElement(K,{columnGap:1},q.createElement(J,{dimColor:!0},`(${formatTime3(t)}`),q.createElement(J,{dimColor:!0},"•"),q.createElement(J,{color:"gray"},Se.arrowDown),q.createElement(J,{dimColor:!0},`${formatToken(Math.round(r))}`),q.createElement(J,{dimColor:!0},"•"),q.createElement(K,{columnGap:1},q.createElement(J,{bold:!0,color:"gray"},"esc"),q.createElement(J,{dimColor:!0},"to interrupt)")))):i?q.createElement(K,{columnGap:1},q.createElement(J,{dimColor:!0},`(${formatToken(Math.round(r))})`)):q.createElement(q.Fragment,null))},"Status");Tn(),Sn();var zm=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,a]=z(!1),[i,l]=z(0),u=V(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?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(a(!0),n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[s,t]);return q.createElement(K,{flexDirection:"column"},r?q.createElement(K,null,q.createElement(CMDIcon,null),q.createElement(J,{color:"white"},"Generating agent from description...")):q.createElement(TextInput,{key:i,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:u,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"red"},`${ve.warning} ${o}`)))},"RecommendedFlow");_t();var Wm=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=z(!1),[a,i]=z(0),l=G(()=>[...Od.map(e=>e.name),...Ld.map(e=>e.name)],[]),u=G(()=>[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[l]),d=G(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),l.forEach(t=>{e.push({type:"tool",value:t})})):(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,u,e,l]),m=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=u.find(e=>e.name===t.value),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]":"[ ]"} ${Ud[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),g=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return X((e,l)=>{if(l.upArrow)i(e=>{const t=e-1;return t<0?g.length-1:t});else if(l.downArrow)i(e=>{const t=e+1;return t>=g.length?0:t});else if(l.return||" "===e){const e=g[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)}}}),q.createElement(K,{flexDirection:"column"},m.map((e,t)=>{const n=g.findIndex(t=>t.value===e.value),r=-1!==n&&n===a;if("divider"===e.type)return q.createElement(K,{key:`divider-${t}`},q.createElement(J,{color:"gray"}," ",e.label));if("spacer"===e.type)return q.createElement(K,{key:`spacer-${t}`,height:1});if("label"===e.type)return q.createElement(K,{key:`label-${t}`},q.createElement(J,{color:"gray"}," ",e.label));const o="continue"===e.type;return q.createElement(K,{key:`item-${t}`},q.createElement(J,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),q.createElement(K,{marginTop:1},e.size===l.length&&q.createElement(J,{color:"gray"},"All tools selected"),e.size>0&&e.size<l.length&&q.createElement(J,{color:"gray"},e.size," tools selected"),0===e.size&&q.createElement(J,{color:"gray"},"No tools selected")))},"ToolsSelector");Dn(),ln(),cn(),Nn();var Hm=__name(({onComplete:e})=>{const[t,n]=z("location"),[r,o]=z(!1),[s,a]=z(null),[i,l]=z("agentType"),u=G(()=>[...Od.map(e=>e.name),...Ld.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=z(d()),p=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),h=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===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"),f=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),y=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),w=__name(async()=>{try{a(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===St.ANTHROPIC&&(r=await rn.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const s={[yt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(s[yt.OAUTH_TOKEN]=`Bearer ${r}`);const i=getApiBaseUrl(),l=new Tl({baseUrl:i}),u=await l.post({headers:s,endpoint:wt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});g({...m,agentType:Be(u.agentName),sysPrompt:u.systemPrompt,ccToolDefinition:u.toolDescription}),n("tools")}catch(e){e instanceof Lo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?a(en):a("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:Be(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),b=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),S=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),v=__name(()=>{n("summary")},"handleToolsComplete"),C=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),k=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),g({...m,selectedTools:n})},"handleToggleCategory");return q.createElement(K,{flexDirection:"column",gap:1},q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"white",bold:!0},"Create new agent"),q.createElement(J,{color:"gray"},h())),q.createElement(K,null,"location"===t&&q.createElement(Dm,{onSelect:f}),"method"===t&&q.createElement(Lm,{onSelect:y}),"configuration"===t&&"recommended"===m.method&&q.createElement(zm,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:w}),"configuration"===t&&"manual"===m.method&&q.createElement(K,{flexDirection:"column",gap:1},q.createElement(Om,{step:i,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>g({...m,agentType:e}),onSysPromptChange:e=>g({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>g({...m,ccToolDefinition:e}),onAgentTypeSubmit:E,onSysPromptSubmit:b,onCCToolDefinitionSubmit:S})),"tools"===t&&q.createElement(Wm,{selectedTools:m.selectedTools,onToggleTool:C,onToggleCategory:k,onComplete:v}),"summary"===t&&q.createElement(Nm,{config:m,onSaveComplete:p})))},"AgentNew"),Vm=__name(({onCancel:e})=>{const[t,n]=z(null),[r,o]=z(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return X((t,n)=>{n.escape&&e()}),q.createElement(K,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"single",flexDirection:"column"},null===t&&q.createElement(Rm,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&q.createElement(Hm,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");_t(),Ot(),Rn(),gr();var Gm=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.MCP="/mcp",e.COMPACT="/compact",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.FEEDBACK="/feedback",e.TERMINAL_SETUP="/terminal-setup",e.IDE_SETUP="/ide",e.ADD_DIR="/add-dir",e.REVIEW="/review",e))(Gm||{}),Km=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/provider","/model","/memory","/init","/agents","/mcp","/compact","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir"]),Jm=[{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",description:"Clear the conversation history (reset, new)"},{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:"/review",description:"Review a pull request (optional PR number)"},{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"}],Qm=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[o,s]=z(0),[a,i]=z(0),{stdout:l}=Z(),u=l?.columns??80,d=Math.max(20,u-22-2-1-2),m=G(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...Jm.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!r)return e;const t=r.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let 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)},[r]),g=G(()=>{const e=a,t=Math.min(e+8,m.length);return m.slice(e,t)},[m,a]);return H(()=>{s(0),i(0)},[r]),X((r,l)=>{if(l.escape)n();else if(l.upArrow)s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t});else if(l.downArrow)s(e=>{const t=Math.min(m.length-1,e+1);return t>=a+8&&i(Math.max(0,t-8+1)),t});else{if(l.return){const t=m[o];return void(t&&e(t.command))}if(l.tab||l.rightArrow){const e=m[o];return void(e&&t(e.command))}}}),0===m.length?q.createElement(K,{flexDirection:"column",paddingLeft:2},q.createElement(J,{color:"dim"},"No commands found")):(m.length,q.createElement(K,{flexDirection:"column",paddingLeft:1},q.createElement(K,{columnGap:2},q.createElement(K,{flexDirection:"column",width:22},g.map((e,t)=>{const n=a+t;return q.createElement(J,{key:n,color:o===n?"white":"dim",wrap:"truncate"},e.command)})),q.createElement(K,{flexDirection:"column"},g.map((e,t)=>{const n=a+t;return q.createElement(J,{key:n,color:o===n?"white":"dim",wrap:"truncate"},truncateString({text:e.description,maxChars:d}))})))))},"CommandMenu");_t(),_t(),gr();var Ym=__name(({messages:e})=>0===e.length?null:q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(K,{marginBottom:0},q.createElement(J,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>q.createElement(K,{key:t},q.createElement(J,{dimColor:!0},ve.pointerSmall," "),q.createElement(J,{dimColor:!0},truncateString({text:e,maxChars:80}))))),"QueuedMessages");_t(),wn(),Ot(),Sn(),sn(),_t();var Zm=n(y(),"commandcode-images"),Xm={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{b(Zm)||k(Zm,{recursive:!0});const r=Xm[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(Zm,o),a=Buffer.from(e.data,"base64");return P(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=V((e,t)=>{o(t=>[...t,e]),r(t),a()},[o,r,a]),l=W(!1),u=W(""),d=W(null),m=W(""),g=V(async(e,t)=>{let o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectDroppedImageFile(o);if(l)return void i(l,t);const u=await detectClipboardImage();if(u)return void i(u,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]),p=V(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(l.current){const e=u.current,t=m.current;u.current="",m.current="",l.current=!1,d.current=null,e&&await g(e,t)}},500)},[g]);return{handlePaste:V(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return l.current&&(l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)),await g(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!l.current)return l.current=!0,m.current=n.textBeforePaste??t,u.current=n.pastedContent??n.cleanedContent,p(),!0;if(l.current&&!n.isPasteEnd)return void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current)),p(),!0;if(l.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current));const e=u.current,t=m.current;return u.current="",m.current="",l.current=!1,await g(e,t),!0}if(n.isPasteEnd&&!n.isPasteStart&&!l.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return i(e,t),!0}return!1},[t,g,p,i]),resetPasteState:V(()=>{l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:V(()=>l.current,[])}}__name(saveTempImage,"saveTempImage"),Dn(),_t(),Tn(),Sn(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),_t(),_t();var eg=["code --wait","cursor --wait","nano"],tg=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return tg.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 _(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of eg)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var ng=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 ng;t=ensureWaitFlag(t);const r=n(y(),`commandcode-${Date.now()}.md`);return await L(r,e),new Promise((e,n)=>{const o=t.split(" ").filter(e=>e.length>0),s=o[0],a=o.slice(1),i=I(s,[...a,r],{stdio:"inherit"});i.on("close",async()=>{try{const t=await M(r,"utf-8");await F(r),e(t.trimEnd())}catch(e){n(e)}}),i.on("error",async e=>{try{await F(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[o,s]=z(!1),[a,i]=z(null),l=V(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 ng?"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]),u=V(()=>{i(null)},[]);return{isEditorOpen:o,editorError:a,handleOpenInEditor:l,clearEditorError:u}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),_t(),_t(),_t(),_t(),Ot(),xn(),On(),Wn(),_t(),Ot();var rg=t.join(f.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(rg);E.existsSync(e)||E.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!E.existsSync(rg))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=E.readFileSync(rg,"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(),E.writeFileSync(rg,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"),On();var og=we(N),sg=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=_("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return sg.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(Je.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Je.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Je.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 og(`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(!Je.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=De(`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 _("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 ag=new Set(["OPEN","MERGED","CLOSED"]),ig=null;function getCachedPRInfo(e){if(ig&&ig.branch===e){if(!(Date.now()-ig.timestamp>3e5))return ig.result;ig=null}}function setPRCache(e,t){ig={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((o,s)=>{$(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&&ag.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 cg=__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"),lg=__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,cg().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=Qe(),r=n(e,".gitignore");if(b(r))try{const e=S(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}_t(),__name(loadGitignore,"loadGitignore");var ug=__name(({onSelectFile:e,onClose:t,searchQuery:s=""})=>{const[i,l]=z(process.cwd()),[u,d]=z([]),[m,g]=z(0),[p,h]=z(0),f=s.trim()?15:10,y=V((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const s=n(t,e);try{const e=T(s),a=[];return e.forEach(e=>{const i=n(s,e);try{const e=A(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=T(i),s=[],l=a.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!a||u.includes(l)){const a=n(i,e);try{const e=A(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,l=0)=>{if(!(l>8))try{T(e).forEach(u=>{const d=n(e,u);try{const e=A(d),n=o(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(a)||m.includes(a))&&s.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==u&&i(d,l+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()||"",l=r.split("/").pop()||"",u=i.includes(a),d=l.includes(a);if(u&&!d)return-1;if(!u&&d)return 1;const m=e.name.split("/").length,g=t.name.split("/").length;return m!==g?m-g:e.name.localeCompare(t.name)}),s.slice(0,50)},[]),w=V(e=>{try{const t=T(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=A(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),g(0),h(0)}catch{}},[]);H(()=>{if(s.trim()){const e=y(s);d(e),g(0),h(0)}else w(i)},[i,w,s,y]),X((n,r)=>{if(r.escape)t();else if(r.upArrow)g(e=>{const t=Math.max(0,e-1);return t<p&&h(t),t});else if(r.downArrow)g(e=>{const t=Math.min(u.length-1,e+1);return t>=p+f&&h(t-f+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!s.trim()&&l(a(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const E=u.slice(p,p+f);return q.createElement(K,{flexDirection:"column",paddingLeft:1},q.createElement(K,{marginBottom:1,flexDirection:"column"},q.createElement(J,{color:"dim"},s.trim()?`Searching for: "${s}"`:`Files: ${i}`),q.createElement(J,{color:"dim"},s.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===E.length?q.createElement(J,{color:"dim"},s.trim()?`No files found matching "${s}"`:"No files found in this directory"):E.map((e,t)=>{const n=p+t,r=e.name,o=n===m;return q.createElement(J,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList");_t(),Ot(),Rn(),_t();var dg=__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 q.createElement(K,{paddingRight:1},q.createElement(J,{color:r(t)},o))},"ContextUsage");_t(),gr();var mg=__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 Bd.on("new-event",e),()=>{Bd.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const a=9+e.length+9>sr;let i=e;return i=truncateString(a?{text:e,maxChars:sr}:{text:e,maxChars:sr-9-9}),q.createElement(K,null,!a&&q.createElement(J,{color:"green"},"● taste: "),q.createElement(J,null,i),!a&&q.createElement(J,{dimColor:!0}," (ctrl+t)"))},"LearningFeedMini");_t();var gg=__name(({mode:e,pendingExitKey:t})=>t?q.createElement(J,{dimColor:!0},"Press Ctrl+C again to exit"):"auto-accept"===e?q.createElement(K,{flexDirection:"row"},q.createElement(J,{color:"#E4CCFF"},"» accept edits on "),q.createElement(J,{dimColor:!0},"(shift+tab)")):"plan"===e?q.createElement(K,{flexDirection:"row"},q.createElement(J,{color:"#FFB86C"},"plan mode "),q.createElement(J,{dimColor:!0},"(shift+tab)")):q.createElement(J,{color:"dim"},"? for shortcuts"),"ModeIndicator");_t(),_t();var pg=__name(({url:e,text:t,dimColor:n=!1,color:r})=>{const o=`]8;;${e}${t}]8;;`;return q.createElement(J,{dimColor:n,color:r},o)},"TerminalLink"),hg=__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 q.createElement(q.Fragment,null,t&&q.createElement(J,{dimColor:!0}," · "),q.createElement(J,{color:n},"PR "),q.createElement(pg,{url:e.url,text:`#${e.number}`,dimColor:!0}))},"PRLinkBadge"),fg=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?q.createElement(q.Fragment,null,t&&q.createElement(J,{dimColor:!0}," · "),q.createElement(J,{color:"connected"===e.type?"green":"yellow"},e.message)):null,"ConnectionIndicatorBadge"),yg=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:a,connectionIndicator:i,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:p,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w})=>{const E=e>=60;return q.createElement(q.Fragment,null,q.createElement(K,{flexDirection:"column",paddingLeft:1},"auto-accept"!==r&&"plan"!==r||l?q.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},q.createElement(K,{flexDirection:"row",columnGap:0},n&&!l?q.createElement(J,{color:"#5FAFAF"},t):q.createElement(gg,{mode:r,pendingExitKey:l}),!l&&q.createElement(hg,{prInfo:o}),!l&&q.createElement(fg,{indicator:i})),E&&q.createElement(K,{flexDirection:"column",alignItems:"flex-end"},s&&q.createElement(mg,null),a&&q.createElement(dg,{usage:a}))):q.createElement(q.Fragment,null,q.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},q.createElement(gg,{mode:r}),E&&s&&q.createElement(mg,null)),q.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},q.createElement(K,{flexDirection:"row",columnGap:0},q.createElement(J,{color:n?"#5FAFAF":void 0,dimColor:!n},t),q.createElement(hg,{prInfo:o}),q.createElement(fg,{indicator:i})),E&&a&&q.createElement(dg,{usage:a}))),(u||d||g&&m)&&q.createElement(K,{flexDirection:"row",columnGap:1},u&&q.createElement(J,null,ve.tick," ","Command Code"," updated:"," ",q.createElement(J,{dimColor:!0},"v",u.updatedFrom),q.createElement(J,{dimColor:!0}," ",ve.arrowRight," "),q.createElement(J,null,"v",u.updatedTo)),!u&&d&&q.createElement(J,{color:"yellow",dimColor:!0},ve.info," Update available:"," ",d.currentVersion," ",ve.arrowRight," ",d.latestVersion),g&&m&&q.createElement(J,{color:"green",dimColor:!0},ve.bullet," Provider:"," ",getProviderDisplayName(m)))),p&&q.createElement(K,{paddingLeft:1},q.createElement(J,{color:"green"},"! for bash mode")),f&&h&&q.createElement(K,{paddingLeft:1},q.createElement(J,{color:"#E4CCFF"},"SHARED: ",h.url," (copied to clipboard)")),y&&q.createElement(K,{paddingLeft:1},q.createElement(J,{color:y.includes("NOT SHARED")?"red":"#E4CCFF"},y)),w&&q.createElement(K,{paddingLeft:1},q.createElement(J,{color:"#E4CCFF"},w)))},"BottomIndicator");_t(),gr();var wg=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=z([]),[o,s]=z(0),[a,i]=z(!0);H(()=>{l()},[]);const l=__name(async()=>{i(!0);const e=await Cd.listSessions();r(e.slice(0,30)),i(!1)},"loadSessions");if(X((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 q.createElement(K,{flexDirection:"column",paddingLeft:2},q.createElement(J,{color:"gray"},"Loading sessions..."));if(0===n.length)return q.createElement(K,{flexDirection:"column",paddingLeft:2},q.createElement(J,{color:"gray"},"No previous sessions found"),q.createElement(J,{color:"dim",dimColor:!0},"Press ESC to go back"));const u=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),d=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),m=__name(e=>truncateString({text:d(e),maxChars:or}),"truncateMessage"),g=__name(e=>e.title?d(e.title):m(e.firstMessage),"getSessionSummary");return q.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},q.createElement(J,{color:"cyan",bold:!0},"Resume Session"),q.createElement(J,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),q.createElement(K,{marginTop:1}),q.createElement(K,{columnGap:2,marginBottom:1},q.createElement(K,{width:5},q.createElement(J,{color:"gray"}," ")),q.createElement(K,{width:13},q.createElement(J,{color:"gray"},"Modified")),q.createElement(K,{width:20},q.createElement(J,{color:"gray"},"Git Branch")),q.createElement(K,{width:11},q.createElement(J,{color:"gray"},"# Messages")),q.createElement(K,null,q.createElement(J,{color:"gray"},"Summary"))),q.createElement(K,{columnGap:2},q.createElement(K,{flexDirection:"column",width:5},n.map((e,t)=>q.createElement(J,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${ve.pointer} ${t+1}.`:` ${t+1}.`))),q.createElement(K,{flexDirection:"column",width:13},n.map((e,t)=>q.createElement(J,{key:`mod-${e.id}`,color:o===t?"white":"gray"},u(e.lastModified)))),q.createElement(K,{flexDirection:"column",width:20},n.map((e,t)=>q.createElement(J,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),q.createElement(K,{flexDirection:"column",width:11},n.map((e,t)=>q.createElement(J,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),q.createElement(K,{flexDirection:"column"},n.map((e,t)=>q.createElement(J,{key:`summary-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},g(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 q.createElement(J,null,r?" ":"",t?q.createElement(J,{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 q.createElement(K,{flexDirection:"column",width:"100%",alignItems:"flex-end"},i.map((e,r)=>q.createElement(K,{key:r,flexDirection:"row"},q.createElement(K,{flexShrink:0,marginRight:1},0===r&&q.createElement(J,{color:"dim"},s)),q.createElement(K,{flexDirection:"row"},e.map((e,r)=>q.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}_t(),_t(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),_t(),__name(createOSC8Link,"createOSC8Link"),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),_t(),Wr();var Eg=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=z(null),[s,a]=z(!1),i=W(!1),l=W(null),[u,d]=z(!1),[m,g]=z("connected"),p=W(null),h=W(null),f=V((e,t)=>{h.current&&(clearTimeout(h.current),h.current=null),g(e),d(!0),void 0!==t&&(h.current=setTimeout(()=>{d(!1)},t))},[]),y=V(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),w=V(async(e=!1)=>{if(!i.current){i.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new Ur,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=p.current;if(null===r?n&&f("connected",3e3):r!==n&&(n?f("connected",2e3):f("disconnected",5e3)),p.current=n,a(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),o(r)}else o(null)}catch{!0===p.current&&f("disconnected",5e3),p.current=!1,a(!1),o(null),l.current?.disconnect(),l.current=null}finally{i.current=!1}}},[f]);return H(()=>{if(!t||n)return;w(!0);const e=setInterval(()=>w(!1),500);return()=>{clearInterval(e),y(),l.current?.disconnect(),l.current=null}},[t,n,w,y]),{context:r,connected:s,refresh:w,connectionIndicator:{visible:u,message:"connected"===m?"IDE ✓":"IDE disconnected",type:m}}},"useVSCodeContext");_t();var bg=__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");_t();var Sg=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),vg=__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"),Cg=["\n","\r","[13;2u","[27;2;13~","[27;2;13~","[13;2u"],kg=["","[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)||Cg.includes(t))}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isNewlineShortcutKey,"isNewlineShortcutKey"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var Pg=__name(()=>q.createElement(K,{flexDirection:"column",paddingLeft:1},q.createElement(J,{color:"dim",bold:!0},"Available Shortcuts:"),q.createElement(K,{columnGap:4},q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"dim"},"! for bash mode"),q.createElement(J,{color:"dim"},"/ for commands"),q.createElement(J,{color:"dim"},"@ for file paths"),q.createElement(J,{color:"dim"},"shift + tab to toggle auto-accept")),q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"dim"},"double tap esc to clear input"),q.createElement(J,{color:"dim"},"ctrl + j / shift + ⏎ for newline"),q.createElement(J,{color:"dim"},"ctrl + g to open in editor"),q.createElement(J,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Tg=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:s="Enter your input…",showFileList:a,setShowFileList:i,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:g=!1,tasteUsage:p=!1,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w,updateStatus:E,updateFailedInfo:b,currentProvider:S,showProviderInfo:v,permissionMode:C="standard",onToggleAutoAccept:k,hintMessage:P,historyManager:T,pendingExitKey:A=null,onOverlayVisibilityChange:x,onDoubleEscapeEmpty:I,onAltP:_,isProcessing:N=!1,ideContextEnabled:$=!0})=>{const[R,D]=z(0),[O,L]=z(!1),[M,F]=z(!1),[U,j]=z(!1),[B,Q]=z(!1),[Y,ee]=z(""),[te,ne]=z(!1),re=W(0),oe=W(0),[se,ae]=z([]),[ie,ce]=z([]),[le,ue]=z(-1),[de,me]=z(""),ge=W(!1),pe=W(!1),[he,fe]=z(-1),[ye,we]=z(""),Ee=W(0),{isEditorOpen:be,editorError:Se,handleOpenInEditor:Ce,clearEditorError:ke}=useExternalEditor({input:e,setInput:n,setInputKey:D,onEditorClose:__name(()=>{ge.current=!1},"onEditorClose")}),{handlePaste:Pe,resetPasteState:Te,isPasting:Ae}=useBracketedPaste({input:e,detectedContent:se,setInput:n,setDetectedImages:ce,setDetectedContent:ae,incrementInputKey:__name(()=>D(e=>e+1),"incrementInputKey")}),{context:xe,connected:Ie,refresh:_e,connectionIndicator:Ne}=Eg({enabled:$,paused:N}),{stdout:$e}=Z(),Re=$e?.columns??80,{pr:De}=lg();H(()=>{const e=a||B||te;x?.(e)},[a,B,te,x]);const Oe=V(()=>{ce([]),ue(-1)},[]),Le=V(()=>{n(""),F(!1),Q(!1),ee(""),ne(!1),ae([]),Oe(),me(""),Te(),fe(-1),we(""),D(e=>e+1)},[n,Te,Oe]),Me=V(()=>{ge.current=!0,n(e+"\n"),D(e=>e+1),setTimeout(()=>{ge.current=!1},0)},[e,n]);X(async(t,r)=>{if(-1!==le&&r.leftArrow)return void ue(prevImageIndex({currentIndex:le,imageCount:ie.length}));if(-1!==le&&r.rightArrow)return void ue(nextImageIndex({currentIndex:le,imageCount:ie.length}));if(r.upArrow){if(a||B||te)return;const t=e.indexOf("\n"),r=-1===t||Ee.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ie.length,selectedImageIndex:le,historyIndex:he}))return void ue(ie.length-1);if(-1!==le&&ue(-1),0!==e.length&&-1===he&&!r)return;const o=T?.count()??0;if(0===o)return;-1===he&&we(e);const s=Math.min(he+1,o-1);return void(s!==he&&(fe(s),n(T?.getAt(s)||""),D(e=>e+1)))}if(r.downArrow){if(a||B||te)return;if(-1===he)return;const t=e.lastIndexOf("\n");if(!(-1===t||Ee.current>t))return;const r=he-1;return fe(r),n(-1===r?ye:T?.getAt(r)||""),void D(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Oe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return ge.current=!0,void Ce();if(getIsExpandToolShortcut(r,t))return ge.current=!0,n(e),D(e=>e+1),void setTimeout(()=>{ge.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ae()}))return pe.current=!0,Me(),void setTimeout(()=>{pe.current=!1},0);if(r.meta&&r.backspace)return void Le();if(r.meta&&"w"===t)return ge.current=!0,void Le();const o=r.ctrl&&"v"===t||kg.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();return r&&(ce(e=>[...e,r]),n(t),D(e=>e+1)),void(ge.current=!0)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return j(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==le&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ie,index:le});return ce([...e]),void ue(t)}if(r.escape){if(-1!==le)return void ue(-1);if(B)return;if(te)return ne(!1),n(de),void D(e=>e+1);const t=Date.now();return t-re.current<500?(e.length>0?Le():I?.(),re.current=0,oe.current=0):(re.current=t,O||M||(oe.current=t)),L(!1),void F(!1)}O&&(r.backspace||r.delete)&&0===e.length&&L(!1)}});const Fe=V(async t=>{if(be)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void _?.();if(await Pe(t))return;if(ge.current)return void(ge.current=!1);-1!==he&&fe(-1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!O)return L(!0),n(""),void D(e=>e+1);if("!"===s&&!M)return L(!1),F(!0),n(""),void D(e=>e+1)}if("/"!==s||B||"/"!==t||(Q(!0),ee("")),B&&!t.startsWith("/")&&(Q(!1),ee("")),B&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(Q(!1),ee("")):ee(e)}"@"!==s||a||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(i(!0),u(""));const l=t.lastIndexOf("@");if(t.length<e.length&&-1!==l&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(l+1),n=!e.includes(" "),r=l>0?t[l-1]:"";n&&isPrecededByWhitespace(r)&&(i(!0),u(e))}if(a)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),u("");else{const n=t.substring(e+1);u(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);u(e),i(!1)}else u(n)}}O&&(t!==e||t.length<e.length)&&L(!1),Se&&ke(),0===t.length&&(F(!1),Q(!1),ee(""),ne(!1),Oe(),ae([]),u(""),me(""),Te()),n(t)},[O,e,n,a,i,B,M,ie,he,Pe,Te,_,Se,ke,be,Oe]),Ue=V(async()=>{if(_e(),oe.current=0,O)return void L(!1);let n=e.trim();if(!M&&n.startsWith("/")&&d&&"handled"===(await d(n)).status)return T?.add(n),F(!1),Q(!1),ee(""),Oe(),ae([]),fe(-1),void we("");n.length>0&&T?.add(n),fe(-1),we("");let r=[];const o=ie.length>0,s=se.length>0;if(!M&&o&&(r=[...ie]),!M&&s){let e=n;se.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:M?"bash":"user",images:r,ideContext:xe?bg(xe):void 0}),F(!1),Q(!1),ee(""),Oe(),ae([])},[t,d,O,e,M,ie,se,T,_e,Oe]),je=V(t=>{const r=o(process.cwd(),t);let s;if(a&&""!==l){const t=e.lastIndexOf("@");s=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else s=`${e}${r} `;n(s),i(!1),u(""),D(e=>e+1)},[n,i,e,a,l,u]),Be=V(()=>{i(!1),u("")},[i,u]),qe=V(t=>{if("/resume"===t)T?.add(t),fe(-1),we(""),me(e),Q(!1),ee(""),ne(!0),n(""),D(e=>e+1);else{const e=Object.values(Gm).includes(t);Q(!1),ee(""),e?(T?.add(t),fe(-1),we(""),n(""),D(e=>e+1),d&&d(t)):(n(t+" "),D(e=>e+1))}},[d,n,e,T]),ze=V(e=>{Q(!1),ee(""),n(e+" "),D(e=>e+1)},[n]),We=V(()=>{Q(!1),ee(""),n(""),fe(-1),we(""),D(e=>e+1)},[n]),He=V(e=>{ne(!1),n(""),me(""),fe(-1),we(""),D(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Ve=V(()=>{ne(!1),n(de),fe(-1),we(""),D(e=>e+1)},[de,n]),Ge=V(e=>{Ee.current=e},[]),Ke=G(()=>{const t=De&&("OPEN"===De.state||"MERGED"===De.state);return"auto-accept"===C||"plan"===C||Ie||t?!O&&!te:!O&&0===e.length&&!M&&!te},[O,e,M,te,C,Ie,De]),Je=W(new Map),Qe=G(()=>ie.map((e,t)=>{if(Je.current.has(e))return Je.current.get(e)??null;const n=saveTempImage(e,t+1);return Je.current.set(e,n),n}),[ie]),Ye=__name(()=>O||a||B||te||U?0:Ke||A||M?3:4,"getBottomMargin");return q.createElement(K,{width:"100%",flexDirection:"column",marginBottom:Ye()},!te&&q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(ImageRowsDisplay,{detectedImages:ie,selectedImageIndex:le,imageTempPaths:Qe,termWidth:Re,inHistory:-1!==he}),q.createElement(J,{color:M?"green":"gray"},ve.line.repeat(Re)),q.createElement(TextInput,{key:R,value:e,placeholder:be?"Save and close the editor to continue...":s,onChange:Fe,onSubmit:()=>{if(!pe.current)return Date.now()-oe.current<100?(oe.current=0,void Me()):void(a||B||te||be||Ue());pe.current=!1},showCursor:!be&&r&&-1===le,onCursorChange:Ge,prefix:`${M?"!":ve.pointer} `,prefixColor:M?"green":"white"}),q.createElement(J,{color:M?"green":"gray"},ve.line.repeat(Re))),O&&q.createElement(Pg,null),U&&q.createElement(K,{paddingTop:1},q.createElement(J,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),a&&q.createElement(ug,{onSelectFile:je,onClose:Be,searchQuery:l}),B&&q.createElement(Qm,{onSelectCommand:qe,onInsertCommand:ze,onClose:We,searchQuery:Y}),te&&q.createElement(wg,{onSelectSession:He,onClose:Ve}),(Ke||A)&&q.createElement(yg,{termWidth:Re,indicatorText:vg(Ie,xe,Re),isIDEIndicator:Sg(Ie,xe),permissionMode:C,prInfo:De,tasteLearning:g,contextUsage:m,connectionIndicator:Ne,pendingExitKey:A,updateStatus:E,updateFailedInfo:b,currentProvider:S,showProviderInfo:v,isBashMode:M,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w}),Se&&q.createElement(K,{paddingLeft:1,flexDirection:"column"},q.createElement(J,{color:"yellow"},Se)))},"InputBox"),Ag=q.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:a,showFileList:i,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:p,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:E,tasteNotificationMessage:b,updateStatus:S,updateFailedInfo:v,currentProvider:C,showProviderInfo:k,permissionMode:P,onToggleAutoAccept:T,hintMessage:A,historyManager:x,pendingExitKey:I,onResetPendingExitKey:_,onDoubleEscapeEmpty:N,retryAttempt:$,onAltP:R})=>{const[D,O]=z(0),L=W(o);return H(()=>{I&&o!==L.current&&o.length>0&&_?.(),L.current=o},[o,I,_]),H(()=>{if(!t)return void O(0);const e=setInterval(()=>{O(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),q.createElement(K,{flexDirection:"column"},q.createElement(Ym,{messages:e}),q.createElement(K,{flexDirection:"row",justifyContent:"space-between"},q.createElement(K,{flexDirection:"column"},(t||n.isExecuting)&&null===$&&q.createElement(qm,{tokens:g,timeElapsed:D,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),A&&q.createElement(K,{marginLeft:1},q.createElement(J,{dimColor:!0}," ","⎿"," Tip: ",A)))),q.createElement(Tg,{input:o,setInput:s,onSubmit:a,placeholder:"Ask your question...",showFileList:i,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:p,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:E,tasteNotificationMessage:b,updateStatus:S,updateFailedInfo:v,currentProvider:C,showProviderInfo:k,permissionMode:P,onToggleAutoAccept:T,hintMessage:A,historyManager:x,pendingExitKey:!I||t||n.isExecuting?null:I,onDoubleEscapeEmpty:N,onAltP:R,isProcessing:t}))});_t();var xg=__name(({onClose:e})=>{const[t,n]=z(Bd.getEvents());X((t,n)=>{n.ctrl&&"t"===t&&(nm(),e())},{isActive:!0}),H(()=>{const e=__name(()=>{n(Bd.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return Bd.on("new-event",e),Bd.on("cleared",t),()=>{Bd.off("new-event",e),Bd.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 q.createElement(K,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(Ye,{name:"vice"},q.createElement(J,null,Po()))),q.createElement(K,{marginBottom:1,width:"100%",justifyContent:"space-between"},q.createElement(K,null,q.createElement(J,{bold:!0},"Learning Feed"),q.createElement(J,{dimColor:!0}," - Real-time taste learning activity")),q.createElement(J,{dimColor:!0},"Press ctrl+t to close")),q.createElement(K,{flexDirection:"column"},0===t.length?q.createElement(K,null,q.createElement(J,{dimColor:!0},"No learning events yet...")):q.createElement(K,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:i}=o(e.message),l="moved"===t?a(e.details):null,u="upgraded"===t||"downgraded"===t?s(r):null;return q.createElement(K,{key:e.id,marginBottom:1},q.createElement(K,{flexDirection:"column"},q.createElement(K,null,q.createElement(J,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),l?q.createElement(J,{dimColor:!0}," (",l.fullPath,")"):e.details?q.createElement(J,{dimColor:!0}," (",e.details,")"):null),q.createElement(K,{marginLeft:1},q.createElement(J,{dimColor:!0},"⎿"," "),l?q.createElement(q.Fragment,null,q.createElement(J,null,l.category," package ("),q.createElement(J,{dimColor:!0},l.oldPath),q.createElement(J,null," → ",l.newPath),q.createElement(J,null,")")):u?q.createElement(q.Fragment,null,q.createElement(J,null,u.text," ("),q.createElement(J,{dimColor:!0},"confidence: "),q.createElement(J,{dimColor:!0},u.oldPercent,"%"),q.createElement(J,null," → "),q.createElement(J,{color:u.diff>0?"green":"red"},u.newPercent,"%"),q.createElement(J,null,")")):q.createElement(q.Fragment,null,q.createElement(J,null,r),i&&q.createElement(J,{dimColor:!0}," (",i,")")))))}return q.createElement(K,{key:e.id,marginBottom:1},q.createElement(J,{dimColor:!0},ve.pointerSmall," ",e.message))}))))},"LearningFeedFull");_t(),Ot(),cn();var Ig=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(0),[s,a]=z(!0),[i,l]=z(null);H(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),a(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),a(!1)}},"loadMemoryFiles")()},[]);const u=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(X((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]&&u(d[r]),"1"===t&&d[0]&&u(d[0]),"2"===t&&d[1]&&u(d[1]))}),s)return q.createElement(K,{paddingLeft:1,paddingTop:1},q.createElement(J,{color:"dim"},"Loading memory files..."));if(i)return q.createElement(K,{paddingLeft:1,paddingTop:1},q.createElement(J,{color:"red"},"❌ ",i));const m=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 q.createElement(K,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},q.createElement(K,null,q.createElement(J,{color:"white",bold:!0},"Select memory to edit:")),q.createElement(K,{columnGap:4,marginTop:1},q.createElement(K,{flexDirection:"column"},m.map((e,t)=>q.createElement(J,{key:t,color:r===t?"white":"dim"},r===t?`${nn} `:" ",e.label))),q.createElement(K,{flexDirection:"column"},m.map((e,t)=>q.createElement(J,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector");_t(),_t(),_t();var _g=class extends Xe{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}list(e,t=!1,n=""){let r=super.list(e,t,n);return r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),r}},Ng=new Ze;Ng.setOptions({renderer:new _g({strong:te.bold,em:te.italic,del:te.strikethrough,codespan:te.yellow,code:te.yellow,heading:te.bold.underline,firstHeading:te.bold.underline,link:te.cyan,href:te.cyan.underline,blockquote:te.gray.italic,table:te.reset,hr:te.reset,paragraph:te.reset,html:te.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var $g=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=G(()=>{if(!e)return"";const t=[],n=e.replace($g,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=Ng.parse(n);return"string"!=typeof r?e:r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").trim()}catch{return e}},[e]);return q.createElement(J,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return q.createElement(K,null,q.createElement(J,null,ve.nodejs),q.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},q.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage"),_t(),cn();var Rg={"Interrupted by user":"Interrupted by user","Insufficient credits":en};function UserMessage({content:e,imageCount:t=0}){const n="Interrupted by user"===e,r="Insufficient credits"===e,o=e.startsWith("Error:"),s=n||r||o,a=s&&Rg[e]||e;return q.createElement(K,{flexDirection:"column"},q.createElement(K,{paddingX:1,backgroundColor:s?void 0:"#333333"},q.createElement(J,{color:s?"red":"#AAAAAA",bold:!s},ve.pointer),q.createElement(K,{marginLeft:1},q.createElement(J,{color:s?"red":"white",wrap:"wrap"},a))),t>0&&q.createElement(K,{marginLeft:1},q.createElement(J,{dimColor:!0},"⎿"," ",Array.from({length:t},(e,t)=>`[Image #${t+1}]`).join(" "))))}__name(UserMessage,"UserMessage"),_t(),Zt(),Dn(),gr();var Dg="#6B7280";function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,dimDiff:a=!1,maxLines:i}){const l=et.diffLines(e,t);let u=0,d=0,m=0,g=0;l.forEach(e=>{e.added?(u+=e.count||1,g+=e.count||1):e.removed&&(d+=e.count||1,g+=e.count||1)});const p=[];l.forEach((e,t)=>{const n=e.value.split("\n").filter(e=>e);e.added||e.removed?n.forEach((n,r)=>{e.removed?(m++,p.push(q.createElement(K,{key:`${t}-${r}-removed`,width:"100%"},q.createElement(J,{color:"gray",dimColor:a},m.toString().padStart(3)," "),q.createElement(K,{backgroundColor:"#712F37"},q.createElement(J,{dimColor:a},"-"),q.createElement(J,{dimColor:a}," ",n.replace(/\s/g," ")))))):e.added&&(m++,p.push(q.createElement(K,{key:`${t}-${r}-added`,width:"100%"},q.createElement(J,{color:"gray",dimColor:a},m.toString().padStart(3)," "),q.createElement(K,{backgroundColor:"#325B30"},q.createElement(J,{dimColor:a},"+"),q.createElement(J,{dimColor:a}," ",n.replace(/\s/g," "))))))}):m+=n.length});const h=void 0!==i&&p.length>i,f=h?p.slice(0,i):p;return{diffContent:q.createElement(K,{flexDirection:"column"},o&&!r&&q.createElement(J,{color:"gray"},"Updated"," ",q.createElement(J,{color:"white",bold:!0},n)," ","with ",q.createElement(J,{color:"#22C55E"},u)," addition",1!==u?"s":""," and"," ",q.createElement(J,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&q.createElement(J,{color:"red"},"Rejected update to",q.createElement(J,{color:"red"},` ${n}`)),q.createElement(K,{flexDirection:"column",marginLeft:s},f)),isTruncated:h,totalLines:p.length}}function formatTodosForDisplay(e){const t=Mu(e);return t?q.createElement(K,{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 q.createElement(K,{key:e.id||t,flexDirection:"row"},q.createElement(K,{width:2},q.createElement(J,{color:r},n)),q.createElement(J,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):q.createElement(J,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,l="Todos"===e,u="Edit"===e,d=!0===s?.isTasteFile,m=s?.tasteCategory,g=!0===s?.permissionDenied,p=!i&&!l&&!d,{name:h}=detectTerminal(),f="iTerm2"===h?"shift":"ctrl",y=!0===s?.isAgent,w="Shell"===e,E=t&&y?(()=>{const e=t.split(/[.\n]/)[0];return e?e+(t.includes(".")||t.includes("\n")?".":""):t})():w&&t&&!a?truncateCommand({command:t}):t,b=!i&&E&&!d,S=s?.status,v=s?.tokensUsed||0,C="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0;let k,P;if(r)k="yellow",P="→";else if(o)k="red",P=ve.nodejs;else if(i)k=Dg,P="✻";else if(l&&n){const e=Mu(n),t=e?.every(e=>"completed"===e.status);k=t?"#22C55E":"#D4A017",P=ve.nodejs}else k="#22C55E",P=ve.nodejs;return q.createElement(K,null,i&&q.createElement(J,{color:k},P),q.createElement(K,{flexDirection:"column",marginLeft:i?1:0},q.createElement(K,null,i?q.createElement(q.Fragment,null,q.createElement(J,{color:Dg},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!a&&q.createElement(J,{dimColor:!0},"(",`${f}+o to expand`,")")):d?q.createElement(q.Fragment,null,q.createElement(J,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),q.createElement(J,null," ","Using your taste ",m?"package of ":"packages",m&&q.createElement(J,{bold:!0},m))):q.createElement(J,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),b&&q.createElement(J,null," ",q.createElement(Markdown,null,`(${E})`))),y&&("running"===S||n)&&q.createElement(K,{columnGap:1,marginLeft:p?1:0},p&&q.createElement(J,null,"⎿"," "),"running"===S?q.createElement(J,{color:"gray"},"Running (",formatTime2(C)," | ",formatTokens(v),")"):"interrupted"===S?q.createElement(J,{color:"red",wrap:"wrap"},"Interrupted by user"):"error"===S||o?q.createElement(J,{color:"red",wrap:"wrap"},n," (",formatTime2(C)," | ",formatTokens(v),")"):"Interrupted by user"===n?q.createElement(q.Fragment,null,q.createElement(J,{color:"red",wrap:"wrap"},"Interrupted by user")):q.createElement(q.Fragment,null,q.createElement(J,{wrap:"wrap"},"Done"),q.createElement(J,{color:"gray"}," ","(",formatTime2(C)," | ",formatTokens(v),")"))),n&&!d&&!y&&q.createElement(K,{columnGap:1,marginLeft:p?1:0},p&&q.createElement(J,null,"⎿"," "),l?formatTodosForDisplay(n):i?a?q.createElement(K,{width:"100%",flexDirection:"column"},q.createElement(J,null," "),q.createElement(J,{color:Dg,wrap:"wrap",italic:!0},n)):null:u&&s?.oldValue&&s?.newValue?q.createElement(K,{flexDirection:"column"},(()=>{const e=a?void 0:er,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:g,permissionDenied:g,maxLines:e});return q.createElement(q.Fragment,null,n,r&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"… (",o-er," more lines) (",`${f}+o to expand`,")")))})(),g&&n&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"red",wrap:"wrap"},n))):q.createElement(K,{width:"100%"},q.createElement(J,{color:o?"red":"",wrap:"wrap"},a||o?n:(()=>{const{text:t,isTruncated:r,remainingLines:o}=truncateToVisualLines({output:n,maxVisualLines:"Question"===e?Xn:Zn,maxChars:"Question"===e?1/0:rr});return q.createElement(q.Fragment,null,t,r&&"Question"!==e&&q.createElement(J,{dimColor:!0},"\n",o>0?`... +${o} lines (${f}+o to expand)`:`... (${f}+o to expand)`))})()))),r&&!y&&q.createElement(K,{columnGap:1,marginLeft:1},q.createElement(J,null,"⎿"," "),q.createElement(J,{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="✓"),q.createElement(K,null,q.createElement(J,{color:o},s),q.createElement(K,{flexDirection:"column",marginLeft:1},q.createElement(K,null,q.createElement(J,{color:"gray"},"$ "),q.createElement(J,{color:o,bold:!0},e)),q.createElement(K,{columnGap:1,marginLeft:1},q.createElement(J,null,"⎿"," "),q.createElement(J,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),_t(),__name(BashMessage,"BashMessage"),_t(),_t(),Ot();_t(),Ot();var Og="Coding agent that continuously learns your taste of writing code.",Lg=34,Mg=[{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"}],Fg=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume",description:"Resume a conversation"},{key:"-c, --continue",description:"Continue the last conversation"},{key:"-t, --trust",description:"Auto-trust project (skip initial permission prompt)"},{key:"-p, --print [query]",description:"Run in non-interactive mode, output response and exit"},{key:"--plan",description:"Start in plan mode"},{key:"--permission-mode <mode>",description:"Set permission mode (standard, plan, auto-accept)"},{key:"--dangerously-skip-permissions",description:"Bypass all permission prompts (use with caution)"},{key:"--add-dir <directory>",description:"Add directory to workspace context"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"--ide-setup",description:"Setup extension for editor context"},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],Ug=[{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:"/review [pr]",description:"Review a pull request (optional PR number)"},{key:"/add-dir",description:"Manage additional directory scope"},{key:"/help",description:"Display help information"},{key:"/exit",description:"Exit the REPL"}],jg=[{key:"cmd info",description:"Display system information"},{key:"cmd status",description:"Show authentication status"},{key:"cmd help",description:"Display help information"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Bg=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],qg=[{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"}],zg='Start with a prompt: cmd "fix the login bug"';_t(),Wn();var Wg="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]:[Wg]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||Wg;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||Wg}catch{return Wg}}function HelpMessage(){const e=getInvokedCommandName(),t=G(()=>Ug.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return q.createElement(K,{flexDirection:"column",paddingY:1},q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(K,null,q.createElement(J,{bold:!0},"Command Code"),q.createElement(J,{color:"gray"}," v","0.12.0")),q.createElement(J,{color:"gray"},Og)),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Usage"),q.createElement(K,{paddingLeft:2},q.createElement(J,null,e," <command> [options]"))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Options"),q.createElement(K,{flexDirection:"column",paddingLeft:2},Fg.map(t=>q.createElement(K,{key:t.key},q.createElement(J,null,t.key.replace(/^cmd/,e).padEnd(Lg)),q.createElement(J,{color:"gray"},t.description))))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Commands"),q.createElement(K,{flexDirection:"column",paddingLeft:2},jg.map(t=>q.createElement(K,{key:t.key},q.createElement(J,null,t.key.replace(/^cmd/,e).padEnd(Lg)),q.createElement(J,{color:"gray"},t.description))))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Slash Commands"),q.createElement(K,{flexDirection:"column",paddingLeft:2},t.map(e=>q.createElement(K,{key:e.key},q.createElement(J,null,e.key.padEnd(Lg)),q.createElement(J,{color:"gray"},e.description))))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Keyboard Shortcuts"),q.createElement(K,{flexDirection:"column",paddingLeft:2},Mg.map(e=>q.createElement(K,{key:e.key},q.createElement(J,null,e.key.padEnd(Lg)),q.createElement(J,{color:"gray"},e.description))))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Examples"),q.createElement(K,{flexDirection:"column",paddingLeft:2},qg.map(t=>q.createElement(K,{key:t.key},q.createElement(J,null,t.key.replace(/^cmd/,e).padEnd(Lg)),q.createElement(J,{color:"gray"},t.description))))),q.createElement(K,{marginBottom:1},q.createElement(J,{color:"cyan"},"❯"),q.createElement(J,{color:"gray"}," ",zg.replace(/cmd/,e))),q.createElement(K,{flexDirection:"column"},q.createElement(J,{bold:!0},"Links"),q.createElement(K,{flexDirection:"column",paddingLeft:2},Bg.map(e=>q.createElement(K,{key:e.key},q.createElement(J,null,e.key.padEnd(Lg)),q.createElement(J,{color:"cyan"},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?q.createElement(HelpMessage,null):q.createElement(K,{flexDirection:"column"},q.createElement(J,{wrap:"wrap"},q.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return q.createElement(K,null,q.createElement(J,{color:"red"},t?ve.pointer:ve.warning),q.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?q.createElement(J,{color:"red",wrap:"wrap"},e):q.createElement(Markdown,{color:"red"},e)))}function AutoCompactMessage({content:e}){return q.createElement(K,null,q.createElement(J,{dimColor:!0},ve.info),q.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},q.createElement(J,{dimColor:!0},e)))}function InfoMessage({content:e,metadata:t}){return t?.isAutoCompact?q.createElement(AutoCompactMessage,{content:e}):q.createElement(K,null,q.createElement(J,{dimColor:!0},ve.info),q.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},q.createElement(J,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return q.createElement(K,{flexDirection:"column",marginBottom:0,marginTop:-1},q.createElement(K,{columnGap:1},q.createElement(J,null,"⎿"," "),q.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},q.createElement(J,{color:n?"yellow":void 0},e))),t&&q.createElement(K,{marginLeft:3},q.createElement(J,{dimColor:!0},"See ",t)))}function IDEStatusMessage({status:e,ide:t,details:n}){return q.createElement(K,{flexDirection:"column"},q.createElement(K,null,"connected"===e&&q.createElement(J,null,q.createElement(J,{color:"green"},ve.tick),q.createElement(J,null," Connected to "),q.createElement(J,{color:"cyan"},t)),"installed"===e&&q.createElement(J,null,q.createElement(J,{color:"green"},ve.tick),q.createElement(J,null," Installed for "),q.createElement(J,{color:"cyan"},t)),"needs_reload"===e&&q.createElement(J,null,q.createElement(J,{color:"yellow"},ve.circle),q.createElement(J,null," "),q.createElement(J,{color:"cyan"},t),q.createElement(J,null," extension needs reload")),"failed"===e&&q.createElement(J,null,q.createElement(J,{color:"red"},ve.cross),q.createElement(J,null," Install failed")),"not_in_ide"===e&&q.createElement(J,null,q.createElement(J,{color:"yellow"},ve.circle),q.createElement(J,null," Not in IDE"))),n?.map((e,t)=>q.createElement(J,{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"),Rn(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),_t(),__name(ErrorMessage,"ErrorMessage"),_t(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(InfoMessage,"InfoMessage"),_t(),__name(CommandResultMessage,"CommandResultMessage"),_t(),__name(IDEStatusMessage,"IDEStatusMessage"),Wn(),Ot(),Rn(),__name(getModelShortName,"getModelShortName");var Hg=q.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const s=t?["header",...e]:e,a=Po();getTerminalWidth();const i=getPackageJson().version||"0.0.0",l=o?getModelShortName(o):"sonnet-4.5",u=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",m=u.replace(d,"~"),g=getGitHeaderInfo();return q.createElement(Q,{items:s,key:n,style:{width:"100%"}},e=>{if("header"===e)return q.createElement(K,{key:"header",marginBottom:1,flexDirection:"column"},q.createElement(Ye,{name:"vice"},q.createElement(J,null,a.trimEnd())),q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(K,null,q.createElement(J,{color:"gray"},"# "),q.createElement(J,{bold:!0},"Command Code"),q.createElement(J,{color:"gray"}," v",i)),q.createElement(J,{color:"gray"},"# models: ",l," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),q.createElement(K,null,q.createElement(J,{color:"gray"},"# ",m,g&&g.isLocal&&g.branch&&q.createElement(J,{color:"gray"}," (branch: ",g.branch,")")))));const t=e,n=(()=>{switch(t.role){case"user":{const e=Array.isArray(t.metadata?.images)?t.metadata.images.length:0;return q.createElement(UserMessage,{content:t.input,imageCount:e})}case"assistant":return q.createElement(AssistantMessage,{content:t.input});case"tool":return q.createElement(ToolMessage,{name:Du(t.name||""),input:t.input,output:t.output||"",isPending:Nu(t),hasError:_u(t),metadata:t.metadata,expandedOutput:r});case"bash":return q.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:Nu(t),hasError:_u(t)});case"system":return q.createElement(SystemMessage,{content:t.input});case"info":return q.createElement(InfoMessage,{content:t.input,metadata:t.metadata});case"error":return q.createElement(ErrorMessage,{content:t.input});case"command-result":return q.createElement(CommandResultMessage,{message:t.input,details:t.details,hasError:t.hasError??!1});case"ide-status":return q.createElement(IDEStatusMessage,{status:t.status,ide:t.ide,details:t.details});default:return q.createElement(q.Fragment,null)}})();return q.createElement(K,{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}))}_t(),Ot(),__name(getModelOptions,"getModelOptions");var Vg=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");X((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0;return q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(K,null,q.createElement(J,{color:"#E4CCFF",bold:!0},"Select model")),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),q.createElement(Ke,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>q.createElement(J,{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 q.createElement(K,null,q.createElement(J,{color:a},` ${(o?.label||t).padEnd(24)}`),q.createElement(J,{dimColor:!0},o?.description),s&&q.createElement(J,{color:"green"}," ✓"))}}),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press "),q.createElement(J,{dimColor:!0,bold:!0},"Esc"),q.createElement(J,{dimColor:!0}," to cancel")))},"ModelSelector");_t(),Ot();var Gg=__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"),l=__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"),u=__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 q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,color:"yellow"},`${u()} ${"edit"===e.action?l():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&q.createElement(K,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:l(),marginLeft:0}).diffContent),q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0},"Do you want to ",i()," ",q.createElement(J,{color:"cyan"},l()),"?")),q.createElement(Ke,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:o,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"cyan"},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>q.createElement(J,{color:t?"cyan":"white"},e.includes("(shift+tab)")?q.createElement(q.Fragment,null,e.split("(shift+tab)")[0],q.createElement(J,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?q.createElement(q.Fragment,null,e.split("(")[0],q.createElement(J,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt");_t(),Rn();var Kg=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");X((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,a=n&&-1===s;return q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(K,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},q.createElement(K,null,q.createElement(J,{bold:!0},"Select AI Provider")),n&&q.createElement(K,{flexDirection:"row"},q.createElement(J,{dimColor:!0},"Current: "),q.createElement(J,{color:"green"},getProviderDisplayName(n)),a&&q.createElement(J,{color:"yellow"}," [OAuth enforced]"))),q.createElement(K,{marginBottom:0},q.createElement(J,{dimColor:!0},"Available Providers:")),q.createElement(Ke,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"cyan":"gray",bold:e},` ${t}`)}),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");_t();var Jg=__name(({staticKey:e})=>q.createElement(Q,{items:[{staticKey:e}],key:e},()=>q.createElement(J,{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 q.createElement(K,{marginBottom:1},q.createElement(J,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}_t(),__name(RetryMessage,"RetryMessage"),_t(),gr(),cn();var Qg=[{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"}],Yg=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=G(()=>[...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)),[l,u]=z("checkpoint"),[d,m]=z(null),[g,p]=z(0),h=G(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),f=G(()=>h?Qg:Qg.filter(e=>"conversation"===e.mode),[h]);if(H(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),X((e,h)=>{h.escape?"mode"===l?(u("checkpoint"),m(null),p(0)):n():"checkpoint"===l?h.upArrow?s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t}):h.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(t-8+1),t}):h.return&&r.length>0&&(m(r[o]),u("mode"),p(0)):"mode"===l&&(h.upArrow?p(e=>Math.max(0,e-1)):h.downArrow?p(e=>Math.min(f.length-1,e+1)):h.return&&d&&f[g]&&t({messageId:d.messageId,mode:f[g].mode}))}),0===r.length)return q.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},q.createElement(J,{color:"#E4CCFF",bold:!0},"Rewind"),q.createElement(J,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press "),q.createElement(J,{dimColor:!0,bold:!0},"Esc"),q.createElement(J,{dimColor:!0}," to close")));if("mode"===l&&d)return q.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},q.createElement(J,{color:"#E4CCFF",bold:!0},"Rewind"),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"Restore to: "),q.createElement(J,{color:"white"},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),q.createElement(K,{flexDirection:"column"},f.map((e,t)=>{const n=g===t,r=t===f.length-1;return q.createElement(K,{key:e.mode,flexDirection:"column"},q.createElement(K,{flexDirection:"row"},q.createElement(J,{color:n?"#E4CCFF":void 0},n?`${nn} `:" "),q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:n?"#E4CCFF":"white"},e.label),q.createElement(J,{dimColor:!0},e.description))),!r&&q.createElement(J,null," "))})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press "),q.createElement(J,{dimColor:!0,bold:!0},"Enter"),q.createElement(J,{dimColor:!0}," to confirm, "),q.createElement(J,{dimColor:!0,bold:!0},"Esc"),q.createElement(J,{dimColor:!0}," to go back")));const y=r.slice(a,a+8);return q.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},q.createElement(J,{color:"#E4CCFF",bold:!0},"Rewind"),q.createElement(J,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),q.createElement(K,{marginTop:1}),q.createElement(K,{flexDirection:"column"},y.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,l=t===y.length-1,u=n===r.length-1;return q.createElement(K,{key:e.messageId,flexDirection:"column"},q.createElement(K,{flexDirection:"row"},q.createElement(J,{color:s?"#E4CCFF":void 0},s?`${nn} `:" "),q.createElement(K,{flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:s?"#E4CCFF":"white"},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),q.createElement(J,{dimColor:!0}," • "),q.createElement(J,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),q.createElement(J,{dimColor:!0},i>0?`${i} file${i>1?"s":""} changed`:"No code changes"))),!l&&q.createElement(J,null," "))})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press "),q.createElement(J,{dimColor:!0,bold:!0},"Enter"),q.createElement(J,{dimColor:!0}," to select, "),q.createElement(J,{dimColor:!0,bold:!0},"Esc"),q.createElement(J,{dimColor:!0}," to cancel")))},"RewindSelector");_t(),gr();var Zg=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=ee(),[r,o]=z([]),[s,a]=z(0),[i,l]=z(!0),[u,d]=z(0),m=30;H(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await Cd.listSessions();o(e),l(!1)},"loadSessions");if(X((t,o)=>{o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):o.downArrow?a(e=>{const t=Math.min(r.length-1,e+1);return t>=u+m&&d(t-m+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),i)return q.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},q.createElement(J,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),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"),h=__name(e=>truncateString({text:e,maxChars:or}),"truncateMessage");if(0===r.length)return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"gray"},"No sessions available"));const f=r.slice(u,u+m),y=u;return q.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&q.createElement(K,{marginBottom:1},q.createElement(J,{color:"dim"},"Showing ",u+1,"-",Math.min(u+m,r.length)," ","of ",r.length," sessions",u>0&&" (↑ for more)",u+m<r.length&&" (↓ for more)")),q.createElement(K,{columnGap:2,marginBottom:1},q.createElement(K,{width:7},q.createElement(J,{color:"gray"}," ")),q.createElement(K,{width:13},q.createElement(J,{color:"gray"},"Modified")),q.createElement(K,{width:11},q.createElement(J,{color:"gray"},"# Messages")),q.createElement(K,{width:20},q.createElement(J,{color:"gray"},"Git Branch")),q.createElement(K,null,q.createElement(J,{color:"gray"},"Summary"))),q.createElement(K,{columnGap:2},q.createElement(K,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${ve.pointer} ${n+1}.`:` ${n+1}.`)})),q.createElement(K,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`mod-${e.id}`,color:s===n?"white":"gray"},p(e.lastModified))})),q.createElement(K,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),q.createElement(K,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),q.createElement(K,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`summary-${e.id}`,color:s===n?"white":"gray"},h(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 E.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"}_t(),jt(),_t(),jt(),__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 Xg=__name(({onClose:e})=>{const[t,n]=z(""),[r,o]=z(null),[s,a]=z([]),[i,l]=z(getAdditionalDirectories()),[u,d]=z({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=z(0);H(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),H(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const p=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),h=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());o({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),l(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");X((r,a)=>{if(a.escape)e();else{if(a.return)return"active-dir"===u.zone&&i[u.activeDirIndex]?void h(i[u.activeDirIndex]):"suggestions"===u.zone&&s[u.suggestionIndex]?void p(s[u.suggestionIndex]):void p(t);if((a.delete||a.backspace)&&"active-dir"===u.zone&&i[u.activeDirIndex])h(i[u.activeDirIndex]);else{if(a.tab&&s.length>0){const e=s[u.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"===u.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"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[u,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 f=s.slice(m,m+8),y=getFooterText({focusZone:u.zone});return q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},q.createElement(J,{bold:!0,color:"cyan"},"Add directory to workspace"),q.createElement(J,{color:"gray"},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,{color:"gray"},"Added directories"),0===i.length?q.createElement(J,{color:"gray"}," None yet"):i.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return q.createElement(J,{key:e,color:n?"yellow":"green",bold:n},n?` ${ve.pointer} `:" ",formatDirectoryForDisplay(e))})),q.createElement(K,{marginTop:1},q.createElement(J,{bold:!0,color:"white"},"Path")),q.createElement(K,null,q.createElement(J,{color:"input"===u.zone?"cyan":"gray"},"input"===u.zone?ve.pointer:" "),q.createElement(J,null," "),q.createElement(J,{color:"white"},t),"input"===u.zone&&q.createElement(J,{color:"gray"},"█")),!t&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray"},"Examples: ../shared ~/docs /abs/path")),r&&q.createElement(K,{marginTop:1},q.createElement(J,{color:{error:"red",warning:"yellow",success:"green"}[r.tone]},r.text)),s.length>0&&q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(J,{color:"gray"},"Suggestions"),f.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return q.createElement(J,{key:e,color:r?"cyan":"gray",bold:r},r?` ${ve.pointer} `:" ",e)})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},y)))},"AddDirModal");_t(),Ot();var ep=__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 q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,color:"yellow"},"Execute Shell Command")),q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",q.createElement(J,{color:"cyan"},a()),".")),e.workingDirectory&&q.createElement(K,{marginBottom:1},q.createElement(J,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0,italic:!0},e.description)),q.createElement(Ke,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"cyan"},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>q.createElement(J,{color:t?"cyan":"white"},e.includes("(shift+tab)")?q.createElement(q.Fragment,null,e.split("(shift+tab)")[0],q.createElement(J,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt");_t(),Ot();var tp=__name(e=>Math.ceil(e.length/4),"estimateTokens"),np=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(!0),[s,a]=z(null),[i,l]=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 u=t.filter(e=>"project"===e.location),d=t.filter(e=>"user"===e.location),m=[...u,...d],g=__name(async t=>{try{await tt([{file:t.filePath,line:1}]),nm(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?a(p()):a(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");X((t,n)=>{if(n.escape)return nm(),void e();if(n.upArrow)l(e=>Math.max(0,e-1));else if(n.downArrow)l(e=>Math.min(m.length-1,e+1));else if(n.return){const e=m[i];e&&g(e)}});const p=__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?q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(J,{color:"#E4CCFF",bold:!0},"Agent Skills"),q.createElement(J,{dimColor:!0},"Loading skills...")):s?q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(J,{color:"red",bold:!0},"Agent Skills"),q.createElement(J,{dimColor:!0},s),q.createElement(K,{marginTop:1}),q.createElement(J,{dimColor:!0},"Press ",q.createElement(J,{bold:!0},"Esc")," to close")):0===t.length?q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(J,{color:"#E4CCFF",bold:!0},"Agent Skills"),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"No skills found")),q.createElement(J,{dimColor:!0},"Create skills in:"),q.createElement(J,{dimColor:!0}," ~/",".commandcode","/","skills","/ (user)"),q.createElement(J,{dimColor:!0}," ",".commandcode","/","skills","/ (project)"),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press ",q.createElement(J,{bold:!0},"Esc")," to close"))):q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(K,null,q.createElement(J,{color:"#E4CCFF",bold:!0},"Skills "),q.createElement(J,{dimColor:!0},m.length," skills")),u.length>0&&q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(K,null,q.createElement(J,{color:"#666666",bold:!0},"Project skills "),q.createElement(J,{color:"#666666"},"(",".commandcode","/","skills",")")),u.map((e,t)=>{const n=i===t;return q.createElement(K,{key:e.value},q.createElement(J,{color:n?"green":"white"},e.label),q.createElement(J,{dimColor:!0}," · ~",tp(e.description)," description tokens"))})),d.length>0&&q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(K,null,q.createElement(J,{color:"#666666",bold:!0},"User skills "),q.createElement(J,{color:"#666666"},"(~/",".commandcode","/","skills",")")),d.map((e,t)=>{const n=i===u.length+t;return q.createElement(K,{key:e.value},q.createElement(J,{color:n?"green":"white"},e.label),q.createElement(J,{dimColor:!0}," · ~",tp(e.description)," description tokens"))})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0,italic:!0},"Esc to close")))},"SkillsConfig");_t(),Nn();var rp=__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")()},[]),X((t,n)=>{if(!n.return&&" "!==t)return n.escape?(nm(),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?q.createElement(K,{key:n,borderStyle:"single",borderColor:"blue",padding:1,flexDirection:"column"},q.createElement(J,{color:"blue",bold:!0},"Taste Settings"),q.createElement(J,{dimColor:!0},"Loading configuration...")):q.createElement(K,{key:n,borderStyle:"single",borderColor:"gray",padding:1,flexDirection:"column"},q.createElement(J,{bold:!0},"Taste Learning"),q.createElement(J,{dimColor:!0},"Configure taste learning preferences for this project"),q.createElement(K,{marginTop:1}),q.createElement(K,{justifyContent:"space-between"},q.createElement(J,null,"Taste learning",q.createElement(J,{dimColor:!0}," - Learn from your interactions")),q.createElement(J,{color:r?"green":"gray"},r?"enabled":"disabled")),q.createElement(K,{marginTop:1}),q.createElement(J,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),q.createElement(J,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig");_t(),xn(),_t(),_t();var op=__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 Bd.on("reset",t),Bd.on("new-event",r),()=>{Bd.off("reset",t),Bd.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new Tl({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;if(n===St.ANTHROPIC)try{const e=await rn.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={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(s[yt.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}_t(),_t(),xn(),_t(),xn(),_t(),_t(),Ot(),ln(),xn(),Nn(),Dn(),__name(createRequestClient,"createRequestClient"),_t(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),_t(),_t(),Ot(),xn(),Zt(),_t();var sp="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:${sp}`,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}`),Bd.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()}`),Bd.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=He.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 ${wt.ALPHA.GENERATE} with model: ${sp}`);const r=buildRequestBody2(n);let o;try{o=await e.post({endpoint:wt.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(Bd.observerHasRun)return;Bd.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(Bd.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)}`),Bd.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 ap=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(h.homedir(),".claude","projects");await R.access(r);const o=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await R.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await R.stat(s)).isDirectory())continue;const r=(await R.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 R.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{Bd.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&Bd.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 R.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{Bd.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 l=await findNewSessions(s),u=l["claude-code"]||[],d=l.codex||[],m=u.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${u.length} new, codex=${d.length} new`),0===m){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=e.length+t.length,r=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);Bd.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(u.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>u.includes(e.id));n.push(...e)}if(d.length>0){const e=(await this.findCodexSessions()).filter(e=>d.includes(e.id));r.push(...e)}const g=n.length+r.length;dlog(`[Import] total sessions: ${g} (claude-code: ${n.length}, codex: ${r.length})`),Bd.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const p=[{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 p){Bd.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const h=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${h.length} batches`);const f=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});Bd.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${h.length} batch${1===h.length?"":"es"}`});try{const o=getApiBaseUrl(),s=new Tl({baseUrl:o});let a=!0;for(let e=0;e<h.length;e++){const t=h[e],n=e+1,r=h.length;r>1&&Bd.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),i=new zd({request:s,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await i.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),Bd.markLearningComplete(),await f,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(),l=[];if(n.length>0&&l.push(`Claude Code (${n.length})`),r.length>0&&l.push(`Codex (${r.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),Bd.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:g,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 Bd.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${l.join(" + ")}`,learningCount:i.totalLearnings,categories:i.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:g,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),Bd.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 R.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")}},ip=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),cp=__name(e=>{const[t,n]=z({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return H(()=>{Bd.reset(),Bd.markImportStarted(),(async()=>{try{const t=await Promise.race([ap.importAndLearn(),ip(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");_t();var lp=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{X((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");_t(),xn();var up=__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{Bd.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{Bd.reset(),e()}}_t(),xn(),_t(),xn(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var dp=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=W(n),o=V(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=V(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=V(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=V(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current())},[e]),l=V(async()=>{dlog("[Handler] demo complete → done"),e("done"),await markDemoShown(),await completeOnboarding(()=>r.current())},[e]),u=V(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:l,handleSkip:u}},"useOnboardingHandlers");_t(),xn();var mp=__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");_t(),_t();var gp=__name(({error:e})=>q.createElement(K,{padding:1},q.createElement(K,{flexDirection:"column",borderColor:"red",padding:1},q.createElement(K,{marginBottom:1},q.createElement(J,null,"Error initializing onboarding: ",e)),q.createElement(K,null,q.createElement(J,null,"Continuing without onboarding...")))),"OnboardingError");_t(),_t();var pp=[{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}],hp=__name(({onComplete:e})=>{const[t,n]=z(0),[r,o]=z(!1),s=t>=pp.length;H(()=>{if(t>=pp.length)return;if(r)return;const e=pp[t],o=setTimeout(()=>{n(e=>Math.min(e+1,pp.length))},e.duration);return()=>clearTimeout(o)},[t,r]),X((t,r)=>{r.escape?e():s?(r.return||" "===t)&&e():" "===t?o(e=>!e):r.return&&n(e=>Math.min(e+1,pp.length))});const a=pp.slice(0,t);return q.createElement(K,{flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:"cyan"},"Meet Your Coding Taste")),q.createElement(K,null,q.createElement(J,null,"Command Code learns your coding style as you work.")),q.createElement(K,null,q.createElement(J,null,"Here's how your preferences evolve in real-time:")),q.createElement(K,{flexDirection:"column",marginY:1},0===a.length&&!s&&q.createElement(J,{dimColor:!0},"Starting demo..."),a.map((e,t)=>"user"===e.type?q.createElement(K,{key:t},q.createElement(J,{color:"white"},`${ve.pointer} ${e.text}`)):q.createElement(K,{key:t,marginBottom:1,marginTop:0,marginLeft:1},q.createElement(K,null,q.createElement(J,null,"⎿"),q.createElement(K,{flexDirection:"column",marginLeft:2,marginTop:0},q.createElement(J,{color:"green"},e.text),e.details&&q.createElement(J,{dimColor:!0},"Saved(",e.details,")")))))),s&&q.createElement(K,{flexDirection:"column",marginY:1,width:80},q.createElement(K,null,q.createElement(J,{color:"green",bold:!0},"Demo Complete!"," ")),q.createElement(J,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."),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press Enter to get started →"))),!s&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"," ",r?"(paused)":"")))},"TasteDemoComponent");_t(),Ot();var fp=__name(()=>`(run /${Ct.LEARN_TASTE} anytime)`,"getSkipHint"),yp=__name(()=>q.createElement(J,null,"Skip for now"," ",q.createElement(J,{dimColor:!0},fp())),"SkipOptionText"),wp=__name(({sessionCount:e,agentSessions:t,onImport:n,onDemo:r,onSkip:o,demoShown:s=!1})=>{const[a,i]=z(1),l=s?2:3,u=s?2:3;return X((e,t)=>{if(t.escape)o();else if(t.upArrow)i(e=>1===e?l:e-1);else if(t.downArrow)i(e=>e===l?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()}),q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},q.createElement(J,{color:"cyan",bold:!0},"Build Your Coding Taste"),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),q.createElement(K,{marginTop:1},q.createElement(J,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:1===a?"cyan":"gray"},1===a?ve.pointer:" "," 1. Yes, learn from my sessions (recommended)")),!s&&q.createElement(K,null,q.createElement(J,{color:2===a?"cyan":"gray"},2===a?ve.pointer:" "," ","2. No, show me a demo instead")),q.createElement(K,null,q.createElement(J,{color:a===u?"cyan":"gray"},a===u?ve.pointer:" "," ",u,". ",q.createElement(yp,null)))),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice"),Ep=__name(({onDemo:e,onSkip:t})=>{const[n,r]=z(1);return X((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()}),q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",padding:1},q.createElement(J,{color:"cyan",bold:!0},"No Previous Sessions Found"),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,null,"No previous sessions found to analyze."),q.createElement(K,{marginTop:1},q.createElement(J,null,"Would you like to see how taste learning works?"))),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:1===n?"cyan":"gray"},1===n?ve.pointer:" "," 1. Yes, show me a demo")),q.createElement(K,null,q.createElement(J,{color:2===n?"cyan":"gray"},2===n?ve.pointer:" "," 2."," ",q.createElement(yp,null)))),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"NoSessionsChoice");_t(),_t();var bp=__name(({error:e})=>q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"red",paddingX:2,paddingY:1,marginBottom:2},q.createElement(J,{color:"red",bold:!0},"Oops, something went wrong:"),q.createElement(K,{marginTop:1},q.createElement(J,null,e))),"ErrorSection");_t(),_t(),_t(),_t(),_t();var Sp=[ve.bullet,ve.squareSmallFilled,ve.lozenge,ve.star,ve.triangleRight,ve.triangleUp,ve.circleFilled,ve.pointer],vp=__name(()=>q.createElement(J,{backgroundColor:"green",color:"black"}," TASTE "),"TasteBadge"),Cp=["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"],kp=__name(()=>{const[e,t]=z(()=>Math.floor(Math.random()*Cp.length));H(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*Cp.length))},2e3);return()=>clearInterval(e)},[]);const n=Cp[e];return q.createElement(J,{color:"yellow"},n,"...")},"PulsingText"),Pp=__name(e=>String(e).padStart(3," "),"padNum"),Tp=__name(e=>Sp[e%Sp.length],"getSymbol"),Ap=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${Pp(t)} ↓${Pp(n)} (↑↓ scroll)`,"buildStatusLine"),xp=__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]),X((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 l=e.slice(t,t+10),u=t,d=s-t-10;return q.createElement(K,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&q.createElement(J,{dimColor:!0},Ap(s,u,d,r)),l.map((e,n)=>{const r=t+n;return q.createElement(K,{key:r,marginBottom:0},q.createElement(J,{dimColor:!0},Tp(r)," ",e))}))},"ScrollableInsights"),Ip=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:l})=>{if(a)return q.createElement(K,{flexDirection:"column",marginBottom:0},q.createElement(vp,null),q.createElement(K,{marginTop:0},q.createElement(J,{dimColor:!0},"⎿"),q.createElement(K,{marginLeft:2},i?q.createElement(J,{color:"green"},"learned your coding taste"):q.createElement(kp,null))));const u=__name(()=>{const[e,t]=z(!0);return H(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),q.createElement(J,{color:"yellow"},e?ve.circleFilled:ve.circle)},"PulsingDot"),d=__name(()=>r?q.createElement(J,{color:"green"},ve.nodejs):n?q.createElement(u,null):q.createElement(J,{dimColor:!0},ve.circle),"getStatusIcon"),m=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||m?q.createElement(K,{flexDirection:"column",marginBottom:0},(n||r)&&q.createElement(K,{marginBottom:0},q.createElement(K,{marginRight:1},d()),q.createElement(J,{color:r?"white":n?"yellow":"dim"},e)),r&&t&&(!l||0===l.learningCount)&&q.createElement(K,{marginLeft:3,marginBottom:0},q.createElement(J,{dimColor:!0},t)),o.length>0&&q.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>q.createElement(J,{key:t,dimColor:!0},`${ve.bullet} ${e}`))),s.length>0&&q.createElement(xp,{insights:s}),r&&l&&l.learningCount>0&&q.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},q.createElement(K,{marginBottom:1,flexDirection:"row"},q.createElement(J,null,"⎿"),q.createElement(K,{marginLeft:2},q.createElement(J,{color:"green"},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),q.createElement(K,{flexDirection:"column",marginLeft:1},q.createElement(J,{dimColor:!0},ve.pointerSmall," Stored in"," ",l.storage),q.createElement(J,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),_p=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return q.createElement(K,{flexDirection:"column",marginBottom:1},e.map((e,n)=>q.createElement(K,{key:e.id,marginLeft:0===n?0:3},q.createElement(Ip,{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"),Np=__name(({steps:e})=>q.createElement(_p,{steps:e}),"ProgressSection");_t();var $p=__name(({isImporting:e=!1,waitingForInput:t=!1})=>q.createElement(q.Fragment,null,e&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"ESC to cancel")),t&&q.createElement(K,{marginTop:1},q.createElement(J,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");_t();var Rp=[{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"}}],Dp=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=op(Rp),{isImporting:s,waitingForInput:a,error:i}=cp(t);return lp({onEscape:e,onEnter:__name(()=>{a&&(i&&n?n():e())},"onEnter"),enabled:s||a}),q.createElement(K,{flexDirection:"column",padding:1},o&&q.createElement(bp,{error:o}),!o&&q.createElement(Np,{steps:r}),q.createElement($p,{isImporting:s,waitingForInput:a}))},"ImportProgress"),Op=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onDemoComplete:a,onDemo:i,onSkip:l})=>"asking"===e?"has_sessions"!==t?.reason?q.createElement(Ep,{onDemo:i,onSkip:l}):q.createElement(wp,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onDemo:i,onSkip:l,demoShown:t.demoShown}):"learning"===e?q.createElement(Dp,{onComplete:r,onError:o,onErrorDismiss:s}):"demo"===e?q.createElement(hp,{onComplete:a}):null,"OnboardingStepRenderer"),Lp=__name(({onComplete:e,autoLearn:t=!1})=>{H(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=up({autoLearn:t,onShouldSkip:e}),{step:s,setStep:a}=mp({conditions:n,autoLearn:t}),{handleImportStart:i,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleDemoComplete:m,handleSkip:g}=dp({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?q.createElement(gp,{error:r}):"done"===s?null:q.createElement(Op,{step:s,conditions:n,onImportStart:i,onImportComplete:l,onImportError:u,onErrorDismiss:d,onDemoComplete:m,onDemo:()=>a("demo"),onSkip:g})},"TasteOnboarding");_t(),Ot();var Mp=__name(({onTrust:e,onExit:t})=>{const{exit:n}=ee(),[r,o]=z(1),s=process.cwd().replace(process.env.HOME||"","~");return X((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())}),q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",padding:1},q.createElement(J,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray"},s)),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),q.createElement(K,{marginTop:1},q.createElement(J,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:1===r?"cyan":"gray"},1===r?ve.pointer:" "," 1. Yes, proceed")),q.createElement(K,null,q.createElement(J,{color:2===r?"cyan":"gray"},2===r?ve.pointer:" "," 2. No, exit"))))},"TrustPrompt");_t(),$n(),Rn();var Fp=__name(({onComplete:e,onCancel:t})=>{const[n,r]=z(!1),[o,s]=z(""),{authState:a,statusMessage:i,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:g}=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 X((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.");g()}}),n?q.createElement(In,{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}`)}}):q.createElement(to,{authState:a,statusMessage:i,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");_t(),_t(),Dn();var Up=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),jp=__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"),Bp=__name(({icon:e,label:t,children:n})=>q.createElement(J,null,q.createElement(J,{color:"cyan"},e," "),q.createElement(J,{dimColor:!0},t.padEnd(12)),n),"Row"),qp=__name(({title:e})=>q.createElement(J,null,q.createElement(J,{color:"gray"},"───"),q.createElement(J,{color:"white"}," ",e," "),q.createElement(J,{color:"gray"},"─".repeat(35))),"Header"),zp=__name(({title:e,marginTop:t=0,children:n})=>q.createElement(K,{flexDirection:"column",marginTop:t},q.createElement(qp,{title:e}),q.createElement(K,{flexDirection:"column",paddingY:1},n)),"Section"),Wp=__name(({cpuCount:e,totalMem:t})=>q.createElement(zp,{title:"System Information"},q.createElement(Bp,{icon:Se.bullet,label:"Date"},q.createElement(J,null,formatDate())),q.createElement(Bp,{icon:Se.pointer,label:"Platform"},q.createElement(J,{color:"green"},Up(h.platform())),q.createElement(J,{dimColor:!0}," ","(",h.platform(),", ",h.arch(),")")),q.createElement(Bp,{icon:Se.triangleUp,label:"Hostname"},q.createElement(J,null,h.hostname())),q.createElement(Bp,{icon:Se.bullet,label:"User"},q.createElement(J,{color:"yellow"},h.userInfo().username)),q.createElement(Bp,{icon:Se.bullet,label:"CPUs"},q.createElement(J,{color:"magenta"},e," cores")),q.createElement(Bp,{icon:Se.bullet,label:"Memory"},q.createElement(J,{color:"cyan"},t," GB")),q.createElement(Bp,{icon:Se.play,label:"Uptime"},q.createElement(J,null,jp(h.uptime()))),q.createElement(Bp,{icon:Se.arrowRight,label:"Home"},q.createElement(J,{dimColor:!0},h.homedir())),q.createElement(Bp,{icon:Se.pointer,label:"Shell"},q.createElement(J,null,process.env.SHELL||"N/A")),q.createElement(Bp,{icon:Se.bullet,label:"Node"},q.createElement(J,{color:"green"},process.version))),"SystemInfoSection"),Hp=__name(({cpus:e})=>q.createElement(zp,{title:"CPU Details",marginTop:1},e.map((e,t)=>q.createElement(Bp,{key:t,icon:Se.bullet,label:`Core ${t}`},q.createElement(J,null,e.model.trim()),q.createElement(J,{color:"yellow"}," @ ",e.speed," MHz")))),"CPUDetailsSection"),Vp=__name(({networkInterfaces:e})=>q.createElement(zp,{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)=>q.createElement(Bp,{key:`${e}-${n}`,icon:Se.bullet,label:e},q.createElement(J,{color:"green"},t.address))):null})),"NetworkSection"),Gp=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>q.createElement(K,{flexDirection:"column"},q.createElement(J,null,"System Information"),q.createElement(J,null,"─".repeat(40)),q.createElement(J,null,"Date ",formatDate()),q.createElement(J,null,"Platform ",Up(h.platform())," (",h.platform(),","," ",h.arch(),")"),q.createElement(J,null,"Hostname ",h.hostname()),q.createElement(J,null,"User ",h.userInfo().username),q.createElement(J,null,"CPUs ",e.length," cores"),q.createElement(J,null,"Memory ",t," GB"),q.createElement(J,null,"Uptime ",jp(h.uptime())),q.createElement(J,null,"Home ",h.homedir()),q.createElement(J,null,"Shell ",process.env.SHELL||"N/A"),q.createElement(J,null,"Node ",process.version),r&&q.createElement(q.Fragment,null,q.createElement(J,null,"\n","CPU Details"),q.createElement(J,null,"─".repeat(40)),e.map((e,t)=>q.createElement(J,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),q.createElement(J,null,"\n","Network"),q.createElement(J,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>q.createElement(J,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Kp=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>q.createElement(K,{flexDirection:"column"},q.createElement(Wp,{cpuCount:e.length,totalMem:t}),r&&q.createElement(Hp,{cpus:e}),r&&q.createElement(Vp,{networkInterfaces:n})),"StyledInfo"),Jp=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=ee();H(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=h.cpus(),o=h.networkInterfaces(),s=Math.round(h.totalmem()/1024/1024/1024);return t?q.createElement(Gp,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e}):q.createElement(Kp,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e})},"InfoUI"),Qp={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},Yp=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),Zp=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(Yp("__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"),Xp=__name(()=>{const e=Zp();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&Qp[t]?Qp[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),eh=__name(()=>{if("win32"===f.platform()){const e=process.env.COMSPEC;return e?l(e):process.env.SHELL?l(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=_(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=l(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?l(e):"N/A"},"getShellName"),th=__name(()=>{const e=Zp();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),nh=__name(()=>{try{const e=_("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:Up(f.platform()),terminal:Xp(),shell:eh(),version:nh(),ide:th()}}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"),_t(),_t(),xn();var rh=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(h.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await R.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 R.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await R.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 R.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await R.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await R.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 rh}__name(createHistoryManager,"createHistoryManager"),_t();var oh=__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"),sh=__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,l=n.has(a);let u,d;i?(u="●",d="cyan"):l?(u="✓",d="green"):(u="○",d="gray"),s.push(q.createElement(J,{key:a},q.createElement(J,{color:d},u),q.createElement(J,{color:i?"cyan":void 0}," ",o.header),a<e.length-1?q.createElement(J,{dimColor:!0}," | "):null))}),!o){const e=r;s.push(q.createElement(J,{key:"review"},q.createElement(J,{dimColor:!0}," | "),q.createElement(J,{color:e?"cyan":"gray"},e?"●":"○"),q.createElement(J,{color:e?"cyan":void 0,bold:e}," ","Review")))}return q.createElement(K,null,s)},"TabIndicator"),ah=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,o]=z(0),[s,a]=z(new Map),i=W(new Map),[l,u]=z(""),[d,m]=z(new Set),[g,p]=z(null),[h,f]=z(!1),[y,w]=z(!1),[E,b]=z(!1),[S,v]=z(null),[C,k]=z(!1),P=e[r],T=P?.multiSelect??!1,A=s.get(r),x=P?[...P.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],I=x.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),_=new Map(I.map((e,t)=>[e.label,x[t]])),N=__name(e=>{"submit"===e.value?M():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),$=__name(()=>{if(!A||0===A.length)return 0;const e=A[0],t=P.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),R=__name(e=>{if(!h)if(T){const t=oh(e.value,P.options.length-1);if(null===t)return;const n=P.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=oh(e.value,P.options.length-1);if(null===t)return;f(!0);const n=P.options[t]?.label||"";L([n])}},"handleSelect"),D=__name(()=>{if(h)return;f(!0);const e=Array.from(d);L(e)},"handleMultiSelectDone"),O=__name(()=>{if(!h&&l.trim())if(T){const e=new Set(P.options.map(e=>e.label));m(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(l.trim()),n})}else f(!0),L([l.trim()])},"handleOtherSubmit"),L=__name(t=>{i.current.set(r,t);const s=new Map(i.current);a(s);const l=__name(t=>{const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);u(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;l(e),o(e),f(!1),b(!1),v(null),k(!1)}else if(e.every((e,t)=>s.has(t))){if(n&&1===e.length)return void M();m(new Set),u(""),w(!0),f(!1)}else{const t=e.findIndex((e,t)=>!s.has(t));-1!==t&&(l(t),o(t)),f(!1),b(!1),v(null),k(!1)}},"finishQuestion"),M=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:i.current.get(t)||[]}));t({answers:n})},"submitAnswers"),F=__name(t=>{w(!1),o(t),k(!1),b(!1),v(null);const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}},"editQuestion"),U=__name(t=>{if(t<0||t>=e.length)return;T&&(d.size>0?i.current.set(r,Array.from(d)):i.current.delete(r),a(new Map(i.current))),f(!1),b(!1),v(null),k(!1);const n=e[t],s=i.current.get(t);if(n?.multiSelect&&s){m(new Set(s));const e=s.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==s?.length)u("");else{const e=s[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}o(t)},"navigateToQuestion"),j=__name(()=>{if(!g||!T)return;if("done"===g.value)return;const e=oh(g.value,P.options.length-1);if(null===e)return;const t=P.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return X((t,o)=>{if(" "===t&&T&&!E&&j(),"d"!==t||!T||E||y||D(),!y&&!h){if(o.downArrow&&!E&&!C&&!n&&g&&I.length>0&&g.value===I[I.length-1]?.value&&b(!0),o.upArrow&&!E&&!C&&g&&I.length>0&&g.value===I[0]?.value&&(T?k(!0):n||(b(!0),v(I.length-1))),o.upArrow&&E){b(!1),v(I.length-1);const e=I[I.length-1];e&&p(e)}if(o.downArrow&&E)if(b(!1),T)k(!0);else{v(0);const e=I[0];e&&p(e)}if(o.upArrow&&C&&(k(!1),b(!0)),o.downArrow&&C){k(!1),v(0);const e=I[0];e&&p(e)}o.return&&C&&T&&D()}if(h||E||C||(y?o.leftArrow&&F(e.length-1):o.leftArrow&&r>0?U(r-1):o.rightArrow&&(r<e.length-1?U(r+1):(T&&(d.size>0?i.current.set(r,Array.from(d)):i.current.delete(r),a(new Map(i.current))),w(!0)))),o.escape&&!h)if(y)w(!1);else if(E){b(!1);const e=S??I.length-1;v(e);const t=I[e];t&&p(t)}else if(C){k(!1);const e=I[I.length-1];e&&p(e)}}),P||y?y?q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(sh,{questions:e,currentIndex:e.length,answeredQuestions:new Set(s.keys()),isReviewPage:!0})),e.map((e,t)=>q.createElement(K,{key:t,marginBottom:1,flexDirection:"column"},q.createElement(J,{dimColor:!0},t+1,". ",e.question),q.createElement(J,{color:"green"}," ",s.get(t)?.join(", ")||"No answer"))),q.createElement(Ke,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:N,initialIndex:0,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"cyan"},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>q.createElement(J,{color:t?"cyan":"white"},e)}),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},ve.arrowLeft," to go back and edit"))):q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(sh,{questions:e,currentIndex:r,answeredQuestions:new Set(s.keys()),isReviewPage:!1,hideReview:n})),q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0},P.question)),E||C?q.createElement(K,{flexDirection:"column"},I.map((e,t)=>{const n=_.get(e.label),r=T&&n&&d.has(n.label),o=!T&&n&&A?.includes(n.label),s=r||o;return q.createElement(K,{key:t,flexDirection:"column"},q.createElement(K,null,q.createElement(J,null," "),q.createElement(J,{color:s?"green":"white"}," ",t+1,"."," "),T&&(s?q.createElement(J,{color:"green"},"[",ve.tick,"]"," "):q.createElement(J,{dimColor:!0},"[ ] ")),q.createElement(J,{color:s?"green":"white"},n?.label||""),!T&&s&&q.createElement(J,{color:"green"}," ",ve.tick)),n?.description&&q.createElement(K,null,q.createElement(J,null," "),q.createElement(J,{dimColor:!0},T?" ":" ",n.description)))})):q.createElement(Ke,{key:`${r}-${S??"default"}`,items:I,initialIndex:S??$(),onSelect:R,onHighlight:p,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"cyan"},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=_.get(e),r=T&&n&&d.has(n.label),o=!T&&n&&A?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",l=a?.[2]||e;return q.createElement(K,{flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:t?"cyan":s?"green":"white"}," ",i,"."," "),T&&(s?q.createElement(J,{color:"green"},"[",ve.tick,"]"," "):q.createElement(J,{dimColor:!0},"[ ] ")),q.createElement(J,{color:t?"cyan":s?"green":"white"},l),!T&&s&&q.createElement(J,{color:"green"}," ",ve.tick)),n?.description&&q.createElement(J,{dimColor:!0},T?" ":" ",n.description))}}),!n&&q.createElement(K,null,q.createElement(J,{color:"cyan"},E?ve.pointer:" "),q.createElement(J,{color:E?"cyan":void 0}," ",I.length+1,"."," "),T&&(d.has(l.trim())?q.createElement(J,{color:"green"},"[",ve.tick,"] "):q.createElement(J,{dimColor:!0},"[ ] ")),q.createElement(nt,{value:l,onChange:e=>{const t=l.trim();u(e),T&&m(n=>{const r=new Set(n);return t&&r.has(t)&&r.delete(t),e.trim()&&r.add(e.trim()),r})},onSubmit:O,placeholder:"Type something...",focus:E})),T&&q.createElement(K,null,q.createElement(J,{color:"cyan"},C?ve.pointer:" "),q.createElement(J,{color:C?"cyan":void 0,bold:C}," ",r===e.length-1?"Submit":"Next")),e.length>1&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function LiveAgentStatusInner({entry:e}){const t=Du(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||[],[l,u]=z(".");return H(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),q.createElement(K,{flexDirection:"column",marginBottom:1,width:"90%"},q.createElement(K,null,q.createElement(J,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${t} `),o&&q.createElement(J,null," ","(",o,")")),q.createElement(K,{columnGap:1,marginLeft:1},q.createElement(J,null,"⎿"," "),q.createElement(J,{color:"gray"},"Running (",formatTime2(a)," | ",formatTokens(s),")",l)),i.length>0&&q.createElement(K,{flexDirection:"column",marginLeft:1},i.map((e,t)=>{const n=Du(e.name);return q.createElement(K,{key:t,columnGap:1},q.createElement(J,{color:"gray"},"⎿"),q.createElement(J,{color:"gray"}," ",n),e.input&&q.createElement(J,{color:"gray"},"(",e.input,")"))})))}function LiveAgentStatus({entry:e}){return"tool"!==e.role?null:q.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:Kl,capabilities:{},clientInfo:Jl}})});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}_t(),Dn(),__name(LiveAgentStatusInner,"LiveAgentStatusInner"),__name(LiveAgentStatus,"LiveAgentStatus"),_t(),_t(),_t(),Cr(),zr(),_t(),Tr(),xn(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient");var ih=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(!0),[s,a]=z(0),[i,l]=z("list"),[u,d]=z(null);H(()=>{m()},[]);const m=__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"),g=G(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),p=g[s]??null;X((t,n)=>{n.ctrl&&"c"===t?e():n.escape?"actions"===i||"confirm-remove"===i?(l("list"),d(null)):e():"list"===i&&(n.upArrow&&(a(e=>Math.max(0,e-1)),d(null)),n.downArrow&&(a(e=>Math.min(g.length-1,e+1)),d(null)),n.return&&p&&(l("actions"),d(null)))});const h=__name(e=>{switch(e){case"connected":return q.createElement(J,{color:"green"},"✓");case"authenticated":return q.createElement(J,{color:"cyan"},"✓");case"requires_auth":return q.createElement(J,{color:"yellow"},"⚠");case"error":return q.createElement(J,{color:"red"},"✗");default:return q.createElement(J,{color:"gray"},"○")}},"getStatusIcon"),f=__name(e=>{switch(e.status){case"connected":return"connected"+(void 0!==e.toolCount?` · ${e.toolCount} tools`:"");case"authenticated":return"authenticated · not connected";case"requires_auth":return"requires authentication";case"error":return e.error||"error";default:return"not connected"}},"getStatusText"),y=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),w=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),E=__name(async e=>{if(p)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)"remove"!==e.value||l("confirm-remove");else{if(!p.config.oauth)return void d({text:"No OAuth configured for this server",color:"yellow"});d({text:`Authenticating ${p.name}...`,color:"cyan",loading:!0});try{const e={authorizationUrl:p.config.oauth.authorizationUrl,tokenUrl:p.config.oauth.tokenUrl,clientId:p.config.oauth.clientId,clientSecret:p.config.oauth.clientSecret,scopes:p.config.oauth.scopes},t=await performOAuthFlow(p.name,e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`✓ Authenticated with ${p.name}`,color:"green"});try{const e=getMcpConnectionManager();await e.reconnectServer(p.name)}catch{}await m()}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 ${p.name}...`,color:"cyan",loading:!0});try{const e=getMcpConnectionManager();await e.reconnectServer(p.name),d({text:`✓ Connected to ${p.name}`,color:"green"}),await m()}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 l("list")},"handleActionSelect"),b=__name(async e=>{if(p)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===p.status&&await e.disconnectServer(p.name),await removeMcpServer({name:p.name,scope:p.scope}),l("list"),await m(),a(e=>Math.min(e,Math.max(0,g.length-2)))}catch(e){d({text:`✗ Failed: ${e instanceof Error?e.message:String(e)}`,color:"red"}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"#E4CCFF",bold:!0},"Manage MCP servers"),q.createElement(J,{dimColor:!0},"Loading..."));if("confirm-remove"===i&&p)return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"red",bold:!0},"Remove ",p.name,"?"),q.createElement(J,{dimColor:!0},"This will remove the server from ",p.scope," config."),q.createElement(K,{marginTop:1},q.createElement(Ke,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:b,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"}," ",t)})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===i&&p){const e=[];return"connected"===p.status?e.push({label:"Connected",value:"connected"}):e.push({label:"Connect",value:"connect"}),p.config.oauth&&("authenticated"===p.status||"connected"===p.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"}),q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"#E4CCFF",bold:!0},p.name),q.createElement(K,null,h(p.status),q.createElement(J,{dimColor:!0}," ",f(p))),q.createElement(K,{marginTop:1},q.createElement(Ke,{items:e,onSelect:E,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"}," ",t)})),u&&q.createElement(K,{marginTop:1},u.loading&&q.createElement(J,{color:u.color},q.createElement(Re,{type:"dots"})," "),q.createElement(J,{color:u.color},u.text)),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to go back")))}let S=null;return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"#E4CCFF",bold:!0},"Manage MCP servers"),q.createElement(J,{dimColor:!0},t.length," ",1===t.length?"server":"servers"),0===t.length?q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,{dimColor:!0},"No MCP servers configured."),q.createElement(J,{dimColor:!0},'Use "cmd mcp add" to add a server.'),q.createElement(J,{dimColor:!0},"Docs: https://commandcode.ai/docs/mcp")):q.createElement(K,{marginTop:1,flexDirection:"column"},g.map((e,t)=>{const n=e.scope!==S;S=e.scope;const r=t===s;return q.createElement(q.Fragment,{key:e.name},n&&q.createElement(K,{marginTop:0===t?0:1},q.createElement(J,{bold:!0},y(e.scope)),q.createElement(J,{dimColor:!0}," (",w(e.scope),")")),q.createElement(K,{paddingLeft:1},q.createElement(J,{color:r?"white":"gray"},r?"› ":" "),q.createElement(J,{color:r?"white":void 0,bold:r},e.name),q.createElement(J,{dimColor:!0}," · "),h(e.status),q.createElement(J,{color:"connected"===e.status?"green":"authenticated"===e.status?"cyan":"requires_auth"===e.status?"yellow":"gray"}," ",f(e))))})),u&&q.createElement(K,{marginTop:1},u.loading&&q.createElement(J,{color:u.color},q.createElement(Re,{type:"dots"})," "),q.createElement(J,{color:u.color},u.text)),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");xn();var{setText:ch}=Oe,{runIDESetup:lh}=await Promise.resolve().then(()=>(Vr(),Hr));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 uh=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:o,updateFailedInfo:s,initialPrompt:a,skipOnboarding:i=!1,initialPermissionMode:l})=>{const{exit:u}=ee(),[d,m]=z(""),[g,p]=z("Ready..."),h=W(!1),[f,y]=z(null),[w,E]=z(o);H(()=>{if(w){const e=setTimeout(()=>{E(null)},3e4);return()=>clearTimeout(e)}},[w]);const{stdout:b}=Z(),[S,v]=z(!1),[C,k]=z(!1),[P,T]=z(!1),[A,x]=z(!1),[I,_]=z(!1),[N,$]=z(!1),[R,D]=z(!1),[O,L]=z(!1),[M,F]=z(!1),[U,j]=z(null),[B,G]=z(null),[Q,Y]=z(getConfiguredModel()),[te,ne]=z(!1),[re,oe]=z(!1),[ae,ie]=z(!1),ce=W(null),le=W(null),[ue,de]=z(0),[me,ge]=z(!1),{executeBash:pe,executionState:he}=Xd(),[fe,ye]=z(""),[we,Ee]=z([]),[be,Se]=z([]),[ve,Ce]=z(!1),[ke,Pe]=z([]),[Te,Ae]=z(crypto.randomUUID()),[xe,Ie]=z(!1),[_e,Ne]=z(!1),[$e,Re]=z(!1),De=W(null),[Oe,Le]=z(!1),[Me,Fe]=z(!1),[Ue,je]=z(!0),[Be,qe]=z(!1),[ze,We]=z(!1),[He,Ve]=z(null),[Ge,Ke]=z(!1),Je=W(!1),[Qe,Ye]=z(!1),[Ze,Xe]=z(0),[et,tt]=z(null),[nt,rt]=z(null),[ot,st]=z(null),at=W(!1),it=W(!1),ct=W(ot);H(()=>{ct.current=ot},[ot]);const[lt,ut]=z(!1),[dt,mt]=z(""),[gt,pt]=z(!1),[ht,ft]=z(()=>l||(r?"auto-accept":"standard")),yt=W(ht);H(()=>{yt.current=ht},[ht]);const[Et,bt]=z(""),St=W(null),vt=W(null),Pt=__name(()=>{St.current&&clearTimeout(St.current),vt.current&&clearTimeout(vt.current),ce.current&&clearTimeout(ce.current),le.current&&clearTimeout(le.current)},"cleanupTimers"),[Tt,At]=z(!1),[xt,It]=z(!1),_t=W(null),Nt=W(0),[$t,Dt]=z(null),Ot=V(()=>{_t.current=null,Dt(null),vt.current&&(clearTimeout(vt.current),vt.current=null)},[]);H(()=>{if(Qe){Pt();try{u()}catch{process.exit(0)}}},[Qe,u]);const Lt=V(()=>{We(!0),qe(!1),Ke(!1),nm(),de(e=>e+1),e&&Ie(!0)},[e,t]),Mt=__name(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(e=>{dlog("[MCP] Failed to initialize",e)})},"initializeMcpInBackground"),Ft=__name(async()=>{try{const e=await isTasteLearningEnabled();pt(e),e&&await xm.initializeProject()}catch(e){}},"loadTasteStatus"),Ut=__name(async()=>{const e=await getConfiguredProvider();G(e);const t=await isOAuthEnforced();ne(t)},"loadCurrentProvider"),jt=W([]),Bt=W(null),qt=W(null),[zt,Wt]=z(null),[Ht,Vt]=z(null),{requestShellPermission:Gt,service:Kt,respondToPrompt:Jt,clearSessionPermissions:Qt,setEnabled:Yt}=tm({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")}),Bt.current&&p("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Wt({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),Bt.current&&p("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?p("Permission granted"):p("Permission denied")},"onPermissionResponse")}),Zt=__name(e=>{St.current&&clearTimeout(St.current),bt(e),St.current=setTimeout(()=>{bt(""),St.current=null},5e3)},"showHintMessage");H(()=>()=>Pt(),[]),H(()=>{Kt&&applyAutoAcceptMode({enabled:ht,service:Kt})},[ht,Kt]),H(()=>{(async()=>{if(await Cd.isProjectInitialized())if(Fe(!0),je(!1),Ft(),Ut(),Mt(),t){const e=await Cd.listSessions();if(e.length>0){const t=e[0];An(t.id)}}else e&&Ie(!0);else if(n)if(await Cd.initializeProject(),Fe(!0),je(!1),Ft(),Ut(),Mt(),t){const e=await Cd.listSessions();if(e.length>0){const t=e[0];An(t.id)}}else e&&Ie(!0);else isDirectoryEmpty()?(await Cd.initializeProject(),Fe(!0),je(!1),Ft(),Ut(),Mt()):(Le(!0),je(!1))})()},[e,t,n,u]),H(()=>{i||triggerTasteOnboarding({projectTrusted:Me,onboardingComplete:ze,isOnboardingMode:Be,tasteOnboardingCheckedRef:Je,setIsOnboardingMode:qe})},[Me,ze,Be,i]),H(()=>{if(Be&&!He){const e=ku();Ve(e.id),Ee(t=>[...t,e])}else!Be&&He&&(Ee(e=>e.filter(e=>e.id!==He)),Ve(null))},[Be,He]),H(()=>{jt.current=ke},[ke]);const Xt=V(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)),Ee(t=>[...t,e])):Ee(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...jt.current];return jt.current=[],Pe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Xe(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{tt(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{y(e)},"onRetryUpdate"),onProviderChange:__name(e=>{G(e)},"onProviderChange"),onStatusUpdate:__name(e=>{h.current=!0,p(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{if("shell_command"===e&&Kt){const e={command:t.command||"",args:t.args,workingDirectory:t.directory,description:n??buildFallbackDescription(t)};return Kt.requestShellPermission(e).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)=>{Vt({params:e,resolve:t,reject:n}),p("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const t=ct.current;return t?{sessionId:e||Te,secret:t.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>yt.current,"getPermissionMode")}),[ht,Te,Kt]);H(()=>{(async()=>{if(B&&"anthropic"===B&&te)try{await rn.getValidAccessToken()||p("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){p("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[B,te]),H(()=>{if(!ve)return void(h.current=!1);if(null!==f)return;const e=setInterval(()=>{h.current||p(Ru())},7e3);return()=>clearInterval(e)},[ve,f]);const en=V(()=>{const e=!ve&&!zt&&!Ht,t=Bt.current?.hasCheckpoints()??!1;e&&t&&At(!0)},[ve,zt]),tn=V(()=>{if(!Bt.current)return;Bt.current.interrupt(!0);const e=be.length>0;if(Ce(!1),y(null),Se([]),p("Interrupted by user"),!e){const e=Cu("Interrupted by user");Ee(t=>[...t,e])}if(jt.current.length>0){const e=jt.current.join("\n");m(t=>t?e+"\n"+t:e),Pe([]),jt.current=[]}},[be]),nn=__name(()=>{ft(e=>{let t;return t="standard"===e?"auto-accept":"auto-accept"===e?"plan":"standard","auto-accept"===t&&zt&&(Jt({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}),nm(),de(e=>e+1)},"handleToggleAutoAccept");async function getBillingLink(){if(nt)return nt;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return rt(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return rt(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}X((e,t)=>{if(t.shift&&t.tab||"[Z"===e)nn();else if(P||A||I||N||R||O||U||M||Tt||xt||_e)$t&&Ot();else{if(""===e||t.ctrl&&"c"===e){if(ve&&Bt.current)return void tn();const e=Date.now(),t=e-Nt.current;return Nt.current=e,void("ctrl-c"===_t.current&&t<2e3?(vt.current&&(clearTimeout(vt.current),vt.current=null),Ye(!0)):(m(""),_t.current="ctrl-c",Dt("ctrl-c"),vt.current&&clearTimeout(vt.current),vt.current=setTimeout(()=>{_t.current=null,Dt(null),vt.current=null},2e3)))}if(t.ctrl&&"t"===e)return nm(),F(e=>!e),void de(e=>e+1);if(getIsExpandToolShortcut(t,e))return nm(),ge(e=>!e),void de(e=>e+1);if(t.meta&&"p"===e||isAltP(e))$(!0);else{if(t.escape){if(Ht)return Ht.reject(new Error("Question cancelled by user")),Vt(null),void p("Question cancelled");zt?(Jt({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),p("Permission denied")):ve&&Bt.current&&tn()}t.meta||t.ctrl}}}),H(()=>{const e=__name(()=>{nm(),de(e=>e+1)},"handleResize");if(b)return b.on("resize",e),()=>{b.off("resize",e)}},[b]),H(()=>{Bt.current||!Me||xe||$e||(Bt.current=new Kd(Xt(),Te),(async()=>{await hn()})())},[Te,xe,$e,Me]),H(()=>{if(!Me)return;const e=createHistoryManager();return De.current=e,e.init(),()=>{e.cleanup()}},[Me]),H(()=>{a&&Me&&!Ue&&Bt.current&&!xe&&!it.current&&(it.current=!0,on({role:"user",input:a}))},[a,Me,Ue,xe]),__name(getBillingLink,"getBillingLink");const on=__name(async({role:e,input:t,images:n,ideContext:r,displayMessage:o})=>{if(t.length)if(w&&E(null),Xe(0),"bash"===e){if(at.current)return;at.current=!0;const e=Su(t);Ee([...we,e]),m(""),await pe(t,e=>{Ee(e)},()=>{nm(),de(e=>e+1)}),at.current=!1}else{if(ve)return Pe(e=>[...e,o??t]),void m("");if(at.current)return;at.current=!0,Ce(!0),p(Ru()),m("");try{Bt.current&&await Bt.current.sendMessage(t,n,r,o)}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){p("Insufficient credits");const e=await getBillingLink(),t=Cu(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);Ee(e=>[...e,t])}else if(e.message.startsWith("Error:")){p("Error");const t=Cu(e.message);Ee(e=>[...e,t])}else{p("Error");const t=e.message||"An unexpected error occurred",n=Cu(t);Ee(e=>[...e,n])}}finally{Ce(!1),"Interrupted by user"!==g&&"Permission denied"!==g&&"Insufficient credits"!==g&&p("Ready..."),at.current=!1}}},"handleSubmit"),sn=__name(()=>{Ee(e=>[...e,vu("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),an=__name(()=>{const e=yu(`/${Ct.TERMINAL_SETUP}`),t=setupVSCodeTerminal(),n=Pu(t.message,!t.success,t.details);Ee(t=>[...t,e,n])},"handleTerminalSetupCommand"),cn=__name(async()=>{const e=await lh(),t=Tu(e.status,e.ide,e.details);Ee(e=>[...e,t])},"handleIDESetupCommand"),ln=__name(async()=>{if(Ee([]),Se([]),nm(),st(null),ut(!1),mt(""),Bt.current){const e=Bt.current.getSessionManager();e&&await e.deleteShareInfo(),Bt.current=null;const t=crypto.randomUUID();Ae(t),Qt(),Bt.current=new Kd(Xt(t),t)}de(e=>e+1),tt(null),Xe(0)},"handleClearCommand"),un=__name(()=>{Bt.current?Bt.current.hasCheckpoints()?At(!0):Ee(e=>[...e,wu("No checkpoints available. Start sending messages to create checkpoints.")]):Ee(e=>[...e,wu("No active conversation to rewind.")])},"handleRewindCommand"),dn=__name(async e=>{const{messageId:t,mode:n}=e;if(At(!1),Bt.current)try{const e=Bt.current.listCheckpoints().find(e=>e.messageId===t);p("Restoring checkpoint...");const r=await Bt.current.restoreToCheckpoint({messageId:t,mode:n});if(r.success){const t=Bt.current.getSessionManager(),n=Bt.current.getMessages(),o=t.reconstructFeedFromMessages(n);Ee(o),nm(),de(e=>e+1),e&&e.userPrompt&&m(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.";Ee(e=>[...e,wu(a)]),p("Ready...")}else Ee(e=>[...e,Cu(`Failed to restore: ${r.error}`)]),p("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;Ee(e=>[...e,Cu(t)]),p("Ready...")}},"handleRewindSelect"),mn=__name(()=>{At(!1)},"handleRewindCancel"),gn=__name(async()=>{if(Bt.current)if(Bt.current.isRequestInProgress())Ee(e=>[...e,wu("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{Ce(!0),p("Compacting conversation...");const e=await Bt.current.manualCompact();nm(),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.`),Ee(e=>[...e,wu(t)]),Ce(!1),p("Ready..."),tt({current:Bt.current.getContextTokensUsed()||0,limit:_d})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;Ee(e=>[...e,Cu(t)]),Ce(!1),p("Ready...")}else Ee(e=>[...e,wu("No active conversation to compact.")])},"handleCompactCommand"),pn=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return await An(t),{status:"handled"}}const t=parseCommandInput({input:e});if(!t)return{status:"unknown"};const{commandName:n,rawArguments:r,positionalArgs:o}=t;if(Km.has(n)&&r.trim().length>0)return{status:"unknown"};switch(n){case"/exit":return Ye(!0),{status:"handled"};case"/clear":return await ln(),{status:"handled"};case"/help":return sn(),{status:"handled"};case"/share":return fn(),{status:"handled"};case"/unshare":return Pn(),{status:"handled"};case"/taste":return T(!0),{status:"handled"};case"/learn-taste":return await Tn(),{status:"handled"};case"/skills":return x(!0),{status:"handled"};case"/provider":return isInternalTeamFlagEnforced()?_(!0):p("Provider selection not available"),{status:"handled"};case"/model":return $(!0),{status:"handled"};case"/memory":return D(!0),{status:"handled"};case"/resume":return Ie(!0),{status:"handled"};case"/init":return yn(),{status:"handled"};case"/agents":return k(!0),{status:"handled"};case"/mcp":return wn(),{status:"handled"};case"/compact":return await gn(),{status:"handled"};case"/rewind":return un(),{status:"handled"};case"/login":return await bn(),{status:"handled"};case"/logout":return await Cn(),{status:"handled"};case"/feedback":return await kn(),{status:"handled"};case"/terminal-setup":return an(),{status:"handled"};case"/ide":return await cn(),{status:"handled"};case"/add-dir":return Ne(!0),{status:"handled"};case"/review":{const e=r.trim();return await on({input:buildReviewPrompt({prNumber:r}),role:"user",displayMessage:e?`/review ${e}`:"/review"}),{status:"handled"}}}const s=getCustomCommandContent(n);if(s){const e=processCommandTemplate({template:s,rawArguments:r,positionalArgs:o});return await on({input:e.content,role:"user"}),{status:"handled"}}return{status:"unknown"}},"handleCommand"),hn=__name(async()=>{const e=Bt.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&st({url:t.url,secret:t.secret})}},"loadShareInfo"),fn=__name(async()=>{if(Te){if(ot)return await ch(ot.url),p(""),ut(!0),void setTimeout(()=>{ut(!1)},3e3);try{p("Creating share link...");const e=Bt.current?.getMessages()||[],t=Ro.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new Tl({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:wt.ALPHA.SHARE.CREATE,body:{sessionId:Te,messages:t}}),o={url:r.url,secret:r.secret};st(o);const s=Bt.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await ch(r.url),p(""),ut(!0),setTimeout(()=>{ut(!1)},5e3)}catch(e){p(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else p("No active session to share")},"handleShareCommand"),yn=__name(async()=>{try{const e=process.cwd(),t=`Created AGENTS.md at ${await initProjectMemory(e)}. You can now edit it with /memory or open it in your editor.`;Ee(e=>[...e,wu(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;Ee(e=>[...e,wu(t)])}},"handleInitCommand"),wn=__name(()=>{L(!0)},"handleMcpCommand"),En=__name(()=>{L(!1)},"handleMcpClose"),bn=__name(async()=>{const e=Rt();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 Ee(e=>[...e,wu(`Already logged in${t}`)])}It(!0)},"handleLoginCommand"),Sn=V((e,t)=>{It(!1),e?(Ee(e=>[...e,wu(t)]),Bt.current&&Bt.current.refreshRequest()):Ee(e=>[...e,Cu(t)]),p("Ready...")},[]),vn=V(()=>{It(!1),Ee(e=>[...e,wu("Authentication cancelled.")]),p("Ready...")},[]),Cn=__name(async()=>{const e=await performLogout();e.success?(Bt.current&&Bt.current.refreshRequest(),e.wasAuthenticated?e.warnings.length>0?Ee(t=>[...t,wu(`Successfully logged out from Command Code. Warnings: ${e.warnings.join(", ")}`)]):Ee(e=>[...e,wu("Successfully logged out from Command Code.")]):Ee(e=>[...e,wu("Not currently authenticated.")])):Ee(t=>[...t,Cu(`Logout failed: ${e.error}`)])},"handleLogoutCommand"),kn=__name(async e=>{const t=buildGitHubIssueUrl(e);try{await se(t,{wait:!1,background:!0}),Ee(e=>[...e,wu(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`)])}catch(e){Ee(e=>[...e,Cu("Failed to open browser"),vu(createOSC8Link(t,"Open GitHub issue manually"))])}},"handleFeedbackCommand"),Pn=__name(async()=>{if(Te){if(!ot)return mt("NOT SHARED: Session is not currently shared"),void setTimeout(()=>mt(""),5e3);try{p("Removing share link...");const e=new Tl({baseUrl:getApiBaseUrl()});await e.delete({endpoint:wt.ALPHA.SHARE.DELETE,body:{sessionId:Te,secret:ot.secret}});const t=Bt.current?.getSessionManager();t&&await t.deleteShareInfo(),mt("UNSHARED: Sharing has stopped"),p(""),st(null),setTimeout(()=>{mt("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;p(t),setTimeout(()=>p(""),5e3)}}else p("No active session to unshare")},"handleUnshareCommand"),Tn=__name(async()=>{Ke(!0),qe(!0);const e=ku();Ve(e.id),Ee(t=>[...t,e])},"handleLearnCommand"),An=__name(async e=>{const t=crypto.randomUUID();qt.current=t;try{Ee([]),Se([]),Bt.current=null,ft("standard"),Ae(e),Ie(!1),Re(!0),Bt.current=new Kd(Xt(e),e);const{feedEntries:n,corruptedLines:r,totalLines:o}=await Bt.current.loadSession(e);if(qt.current!==t)return;await hn();const s=[];if(0===n.length&&o>0?s.push(Cu(`Session could not be loaded. ${o} lines could not be parsed.`)):0===n.length?s.push(wu("Session loaded but contains no messages.")):(r>0&&s.push(wu(`Warning: ${r} message(s) could not be loaded.`)),s.push(...n)),qt.current!==t)return;Ee(s),nm(),de(e=>e+1)}catch(e){if(qt.current!==t)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";Ee([Cu(`Failed to load session: ${n}. Starting fresh session.`)]),Ie(!1),Re(!1),Ae(crypto.randomUUID())}},"handleSelectSession"),xn=__name(async()=>{Ee([]),Se([]),Bt.current=null,ft("standard"),Ae(crypto.randomUUID()),Ie(!1),Re(!1)},"handleNewSession"),In=__name(async()=>{try{await Cd.initializeProject(),Le(!1),e?(console.log("No conversations found to resume."),Ye(!0)):(Fe(!0),Ft(),Ut())}catch(e){console.error("Failed to initialize project:",e),Le(!1),Ye(!0)}},"handleTrust"),_n=__name(()=>{Ye(!0)},"handleNoTrust"),Nn=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void j({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),G(e),_(!1);const n=getProviderDisplayName(e);p(`Provider set to ${n}`),ce.current&&clearTimeout(ce.current),oe(!0),ce.current=setTimeout(()=>{oe(!1),ce.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),p("Failed to set provider"),_(!1)}},"handleProviderSelect"),$n=__name(()=>{_(!1)},"handleProviderCancel"),Rn=__name(e=>{const t=Object.values(kt).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),Dn=__name(async e=>{try{await setSelectedModel({model:e}),Y(e),$(!1);const t=Rn(e);p(`Model set to ${t}`),le.current&&clearTimeout(le.current),ie(!0),le.current=setTimeout(()=>{ie(!1),le.current=null},5e3)}catch(e){console.error("Failed to set model:",e),p("Failed to set model"),$(!1)}},"handleModelSelect"),On=__name(()=>{$(!1)},"handleModelCancel"),Ln=__name(()=>{if(U){j(null),_(!1),G(U.provider);const e=getProviderDisplayName(U.provider);p(`${e} authentication successful`),ce.current&&clearTimeout(ce.current),oe(!0),ce.current=setTimeout(()=>{oe(!1),ce.current=null},5e3)}},"handleAuthSuccess"),Mn=__name(()=>{j(null)},"handleAuthCancel");if(Qe)return null;if(Oe)return q.createElement(q.Fragment,null,q.createElement(Jg,{staticKey:ue}),q.createElement(Mp,{onTrust:In,onExit:_n}));if(Ue)return null;if(xe)return q.createElement(Zg,{onSelectSession:An,onNewSession:xn});if(!Me)return null;if(Ht)return q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we,showHeader:!0,expandedToolOutput:me,currentModel:Q}),q.createElement(K,{marginY:1},q.createElement(ah,{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"),nm(),de(e=>e+1)):t.startsWith("Yes, exit")&&(ft("standard"),nm(),de(e=>e+1))}if(Ht.params.enterPlanMode){const t=e.answers[0]?.selectedOptions[0];t?.startsWith("Yes")&&(ft("plan"),nm(),de(e=>e+1))}Ht.resolve(e),Vt(null),p("Answers submitted")}})));if(zt){if("shell_command"===zt.toolName){const e=zt.params;return q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we,showHeader:!0,expandedToolOutput:me,currentModel:Q}),be.map(e=>q.createElement(LiveAgentStatus,{key:e.id,entry:e})),q.createElement(K,{marginY:1},q.createElement(ep,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(p("Shell command allowed"),"standard"===ht&&Zt("Use shift+tab to enable auto-accept")):p("Shell command denied")},onToggleAutoAccept:nn})))}if("kill_shell"===zt.toolName){const e=createKillShellPermissionRequest(zt.params);return q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we,showHeader:!0,expandedToolOutput:me,currentModel:Q}),q.createElement(K,{marginY:1},q.createElement(ep,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(p("Process termination allowed"),"standard"===ht&&Zt("Use shift+tab to enable auto-accept")):p("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 q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we,showHeader:!0,expandedToolOutput:me,currentModel:Q}),be.map(e=>q.createElement(LiveAgentStatus,{key:e.id,entry:e})),q.createElement(K,{marginY:1},q.createElement(Gg,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(p("File operation allowed"),"standard"===ht&&Zt("Use shift+tab to enable auto-accept")):p("File operation denied")},onToggleAutoAccept:nn})))}}return M?q.createElement(xg,{onClose:()=>{F(!1),de(e=>e+1)}}):P?q.createElement(q.Fragment,null,q.createElement(Jg,{staticKey:ue}),q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"Press Esc to return to conversation")),q.createElement(rp,{onClose:()=>T(!1),onSettingsChange:Ft,staticKey:ue}))):A?q.createElement(q.Fragment,null,q.createElement(Jg,{staticKey:ue}),q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"Press Esc to return to conversation")),q.createElement(np,{onClose:()=>x(!1),staticKey:ue}))):q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we.filter(e=>"taste-onboarding"!==e.role),showHeader:!0,expandedToolOutput:me,currentModel:Q}),He&&q.createElement(Lp,{onComplete:Lt,autoLearn:Ge}),be.map(e=>q.createElement(LiveAgentStatus,{key:e.id,entry:e})),q.createElement(RetryMessage,{attempt:f}),!I&&!N&&!U&&!R&&!O&&!C&&!Tt&&!xt&&!_e&&!He&&q.createElement(Ag,{queuedMessages:ke,isProcessing:ve,executionState:he,status:g,input:d,setInput:m,onSubmit:on,showFileList:S,setShowFileList:v,fileSearchQuery:fe,setFileSearchQuery:ye,onCommand:pn,outputTokens:Ze,contextUsage:et,tasteLearning:gt,shareInfo:ot,showShareNotification:lt,unshareNotificationMessage:dt,updateStatus:w,updateFailedInfo:s,currentProvider:B,showProviderInfo:re,permissionMode:ht,onToggleAutoAccept:nn,hintMessage:Et,historyManager:De.current,pendingExitKey:$t,onResetPendingExitKey:Ot,onDoubleEscapeEmpty:en,retryAttempt:f,onAltP:()=>$(!0)}),I&&q.createElement(K,{marginY:1},q.createElement(Kg,{onSelect:Nn,onCancel:$n,currentProvider:B})),N&&q.createElement(K,{marginY:1},q.createElement(Vg,{onSelect:Dn,onCancel:On,currentModel:Q})),C&&q.createElement(K,{marginY:1},q.createElement(Vm,{onCancel:()=>k(!1)})),R&&q.createElement(K,{marginY:1},q.createElement(Ig,{onClose:()=>D(!1)})),O&&q.createElement(K,{marginY:1},q.createElement(ih,{onClose:En})),Tt&&Bt.current&&q.createElement(K,{marginY:1},q.createElement(Yg,{checkpoints:Bt.current.listCheckpoints(),onSelect:dn,onCancel:mn})),U&&q.createElement(K,{marginY:1},q.createElement(U.Component,{onSuccess:Ln,onCancel:Mn})),xt&&q.createElement(K,{marginY:1},q.createElement(Fp,{onComplete:Sn,onCancel:vn})),_e&&q.createElement(K,{marginY:1},q.createElement(Xg,{onClose:()=>{Ne(!1)}})))},"InteractiveCLI");Tn(),hn();var dh=__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"),mh=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),gh=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),ph=__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"),hh=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),fh=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),yh=__name(()=>{fh()},"initializeTerminal"),wh=__name(async(e={})=>{const t=dh(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),yh(),mh(e)){const e=await Cd.isProjectInitialized(),t=e?await Cd.listSessions():[],n=gh({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=ph({options:e}),r=hh();Y(q.createElement(uh,{...n}),r)},"interactiveMode");_t(),Ot(),ln(),Nn(),Dn(),Zt();var Eh=null,bh=!1,Sh=new Set([Nl,$l,Ll]);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(bh)return;bh=!0;const e=__name(e=>{Eh?.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(),Eh=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:Eh.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 Mo&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof Fo&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof qo&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Oo&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof zo&&(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 vh=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===St.ANTHROPIC&&(r=await rn.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o=getEnvironmentContext(),s=await getMemoryContent([]),a=await getTasteContent(),i=generateSkillsXML(await loadAllSkillSummaries())||null,l=crypto.randomUUID(),u=await isTasteLearningEnabled(),d={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.TASTE_LEARNING]:u.toString(),[yt.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(d[yt.OAUTH_TOKEN]=`Bearer ${r}`),{tools:e,config:o,memory:s,taste:a,skills:i,headers:d,sessionId:l}}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:wt.ALPHA.GENERATE,headers:t.headers,signal:r});return He.fromReadableStream(a).finalMessage()}async function executeToolCall(e,t,n){if(Sh.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 Mo||t instanceof Fo||t instanceof qo||t instanceof Oo||t instanceof zo)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 Tl({baseUrl:o}),a=[{role:"user",content:t}],i=await setupConversationContext();let l=0,u="";for(;l<vh;){if(l++,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&&(u+=d),0===o.length)break;const m=[];for(const e of o){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);m.push(t)}a.push({role:"assistant",content:e.content}),a.push({role:"user",content:m})}return l>=vh&&process.stderr.write(`Warning: Reached maximum conversation turns (${vh}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),u}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery"),jt();var Ch=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),kh=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),Ph=__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"),Th=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),Ah=__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=Ah(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=Ch(e);await kh();const r=Ph(t),o=Th({options:t,runtimeOptions:r,initialPrompt:n});wh(o)}__name(interactiveModeAction,"interactiveModeAction"),_t(),xn(),Sr(),Vr(),globalThis.COMMAND_CODE_CWD=process.cwd();var xh=__name(()=>process.cwd(),"getCwd"),Ih=__name(()=>process.argv.slice(2),"getArgs"),_h=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),Nh=__name(()=>{const e=xh(),t=Ih(),n=_h(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){Nh(),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"),_t(),Ot(),xn(),Wn(),Rn();var $h=getPackageJson(),Rh=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=$h.version,t=getInvokedCommandName(),n=Ug.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(te.bold("Command Code")+te.gray(` v${e}`)),console.log(te.gray(Og)),console.log(),console.log(te.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(te.bold("Options"));for(const e of Fg){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Lg)+te.gray(e.description))}console.log(),console.log(te.bold("Commands"));for(const e of jg){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Lg)+te.gray(e.description))}console.log(),console.log(te.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Lg)+te.gray(e.description));console.log(),console.log(te.bold("Keyboard Shortcuts"));for(const e of Mg)console.log(" "+e.key.padEnd(Lg)+te.gray(e.description));console.log(),console.log(te.bold("Examples"));for(const e of qg){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Lg)+te.gray(e.description))}console.log(),console.log(te.cyan("❯")+" "+te.gray(zg.replace(/cmd/,t))),console.log(),console.log(te.bold("Links"));for(const e of Bg)console.log(" "+e.key.padEnd(Lg)+te.cyan(e.description));console.log()}function createProgram(){const e=new ke;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version($h.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 Pe("--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",Rh,[]).addOption(new Pe(ht).hideHelp()).addOption(new Pe(ft).hideHelp()).addOption(new Pe("-d, --debug","Enable debug mode").hideHelp()).addOption(new Pe("--local","Use local server").hideHelp()).addOption(new Pe("--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"),_t(),Sr();var Dh=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=h.platform(),n=h.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(){Dh||(Dh=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=De("Opening GitHub issues...").start();try{await se(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"),_t(),__name(openGitHubIssue,"openGitHubIssue");var Oh=new ke("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);_t();var Lh=new ke("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});_t();var Mh=new ke("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(q.createElement(Jp,{verbose:e.verbose,text:e.text}));await t()});_t(),Ot(),xn(),Sr();var Fh=new ke(Ct.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{const{unmount:e}=Y(q.createElement(Dp,{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:hr.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 ke("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 Pe("-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(te.red(`Error: Invalid server name '${e}'`)),console.error(te.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(te.red(`Error: Invalid transport type '${n.transport}'`)),console.error(te.gray("Valid options: stdio, http")),process.exit(1));let a=!1;if("http"===n.transport){t||(console.error(te.red("Error: URL is required for http transport")),console.error(te.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(te.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(te.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(te.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(te.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(te.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${kr}/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(te.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(te.gray(` ${e}`))},"onStatus")});o.success?console.log(te.green("✓ Successfully authenticated")):(a=!0,console.log(te.yellow(`Warning: Authentication failed: ${o.error}`)),console.log(te.gray("You can retry with: cmd mcp auth "+e)),console.log(te.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,a=process.argv.indexOf("--");let i,l=[];if(-1!==a){const e=process.argv.slice(a+1);0===e.length&&(console.error(te.red("Error: Command is required for stdio transport")),console.error(te.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),i=e[0],l=e.slice(1)}else if(t){i=t;const n=o.indexOf(e);-1!==n&&o.length>n+2&&(l=o.slice(n+2))}else console.error(te.red("Error: Command is required for stdio transport")),console.error(te.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(te.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);s={transport:"stdio",enabled:!0,command:i,...l.length>0&&{args:l},...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(te.yellow(`✓ Added MCP server '${e}' to ${i} config (authentication pending)`)):console.log(te.green(`✓ Added MCP server '${e}' to ${i} config`)),"http"===s.transport)console.log(te.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(te.gray(` Command: ${e}`))}console.log(""),console.log(te.cyan("Next steps:")),console.log(te.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(te.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(te.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(te.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(te.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new ke("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(te.yellow("\nNo MCP servers configured\n")),console.log(te.gray("Add a server with:")),console.log(te.gray(" cmd mcp add --transport http <name> <url>")),console.log(te.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(te.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(te.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(te.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?te.green("enabled"):te.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?te.green("✓"):te.red("✗"):o.config.headers||o.config.env?te.green("✓"):te.gray("-"),console.log(` ${te.white(o.name.padEnd(t))} ${te.cyan(o.config.transport.padEnd(n))} ${te.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(te.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new ke("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(te.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(te.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${te.dim("Scope:")} ${r}`),console.log(` ${te.dim("Transport:")} ${n.transport}`),console.log(` ${te.dim("Status:")} ${n.enabled?te.green("enabled"):te.gray("disabled")}`),"http"===n.transport){if(console.log(` ${te.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${te.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(` ${te.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${te.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${te.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(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new ke("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Pe("-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(te.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(te.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(te.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(te.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new ke("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 Pe("-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(te.red(`Error: Invalid server name '${e}'`)),console.error(te.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(te.red("Error: Invalid JSON")),console.error(te.gray("Make sure to quote the JSON string properly")),console.error(te.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=Yl.safeParse(o);if(!a.success){console.error(te.red("Error: Invalid server configuration"));for(const e of a.error.issues)console.error(te.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const i=a.data;let l=!1;if("http"!==i.transport||i.url||(console.error(te.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==i.transport||i.command||(console.error(te.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:i,scope:n.scope}),i.oauth){console.log(te.cyan("Starting OAuth authentication...")),console.log(te.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(te.gray(` ${e}`))},"onStatus")});n.success?console.log(te.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(te.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(te.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(te.gray("Or authenticate via the /mcp menu in a session")))}const u="user"===n.scope?"global":"project"===n.scope?"project":"local";if(l?console.log(te.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(te.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===i.transport)console.log(te.gray(` URL: ${i.url}`));else{const e=[i.command,...i.args||[]].join(" ");console.log(te.gray(` Command: ${e}`))}console.log(""),console.log(te.cyan("Next steps:")),console.log(te.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new ke("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(te.yellow("No servers with stored authentication."));console.log(te.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?te.yellow("expired"):te.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(te.red("Error: Server name is required")),console.error(te.gray(`Usage: ${n} mcp auth <server>`)),console.error(te.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(te.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(te.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(te.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(te.gray(" A refresh token is available for re-authentication"));else{if(console.log(te.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(te.gray(` Expires in ${e} minutes`))}t.scope&&console.log(te.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(te.green(`✓ Cleared authentication for '${e}'`)):console.log(te.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(te.red(`Error: MCP server '${e}' not found`)),console.error(te.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(te.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(te.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(te.cyan(`Authenticating with '${e}'...`)),console.log(te.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,o,{onStatus:__name(e=>{console.log(te.gray(` ${e}`))},"onStatus")});if(s.success)return console.log(te.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(te.gray("Restart the session to connect with the authenticated server."));console.error(te.red(`\nError: Authentication failed: ${s.error}`)),console.log(te.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new ke("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(h.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${n}`)}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"taste.md")}_t(),_t(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),_t(),__name(listMcpCommand,"listMcpCommand"),_t(),__name(getMcpCommand,"getMcpCommand"),_t(),__name(removeMcpCommand,"removeMcpCommand"),_t(),__name(addJsonMcpCommand,"addJsonMcpCommand"),_t(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),_t(),Ot(),_t(),_t(),_t(),Ot(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),_t(),_t();var Uh=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||Uh.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:Uh.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(Uh.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(!Uh.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],l=parseFloat(i);if(isNaN(l))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;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==a.index?o.substring(0,a.index).trim():o.trim();return u&&0!==u.length?(u.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r)}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=t.slice(n+1,n+4),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?te.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(te.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`${te.green(e)} ${te.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?te.red(t.summary):te.yellow(t.summary),"",...formatIssueGroup(r,te.red,te.bold(te.red("Errors:"))),...formatIssueGroup(o,te.yellow,te.bold(te.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"),_t(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var jh=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;jh.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 Bh=/^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}):Bh.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 qh=__name(e=>"local-global"===e?"global":"project","locationLabel"),zh=__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 b(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${qh(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});b(o)&&r.push({path:o,displayName:"taste.md"});const s=(await R.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>b(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 R.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await R.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 zh({file:"all",error:`No taste files found in ${qh(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 zh({file:"all",error:`No taste files found in ${qh(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 b(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):zh({file:"all",error:`No taste directory found in ${qh(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"),_t(),Sr(),__name(resolveConflictStrategy,"resolveConflictStrategy");var Wh=te.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(`${te.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?`${te.dim(t[1])}${te.green(t[2])}${te.white(t[3]??"")}${t[4]?te.dim(t[4]):""}`:te.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${te.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 Hh=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return ot(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:Hh})}function getProfileLink(e){return ot(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:Hh})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return rt(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(te.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(`${te.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(te.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new ke("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 ${te.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(`${te.green(Se.tick)} All ${te.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(te.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(te.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(te.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 R.readFile(t,"utf-8");const r=migrateHeader({content:n});return r===n?n:(await R.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(Tm)?e:Tm+"\n\n"+e:Tm+"\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"),_t(),_t(),_t(),_t(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),_t(),__name(formatPackage,"formatPackage"),_t(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var Vh="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:Vh,category:e.name});return b(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await R.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:Vh});if(!b(e))return[];const t=await R.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:Vh,category:t});return b(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:Vh});await R.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:Vh,category:n.category}),s=e.dirname(o);await R.mkdir(s,{recursive:!0});const a=formatPackage({pkg:n});await R.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"),_t(),_t();var Gh="local-project";function prefixHeaderIfNeeded(e){return!e||e.trim().startsWith(Tm)?e:Tm+"\n\n"+e}async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!b(n))return null;const r=migrateHeader({content:await R.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()},l=[...s,...a].join("\n").trim();return""===l&&await R.rm(n,{force:!0}),""!==l&&await R.writeFile(n,l+"\n","utf-8"),i}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:Gh}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:Gh,category:n}),a=e.dirname(s);return b(a)&&await R.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 R.writeFile(n,e.trim()+"\n","utf-8")}let s="";b(n)&&(s=await R.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await R.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:Gh,category:n.category}),a=e.dirname(s);await R.mkdir(a,{recursive:!0});const i=formatPackage({pkg:n});await R.writeFile(s,i,"utf-8");const l=`# ${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+=l.trim()+t,void await R.writeFile(r,e.trim()+"\n","utf-8")}let u="";b(r)&&(u=await R.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await R.writeFile(r,u.trim()+"\n","utf-8")}__name(prefixHeaderIfNeeded,"prefixHeaderIfNeeded"),__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var Kh="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:Kh,category:e.name});return b(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:Kh});if(!b(e))return[];const t=[],n=getRootTasteFile({target:Kh});if(b(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await R.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:Kh});await R.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:Kh}),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:Kh});return b(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!b(n))return;const r=await R.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 l=formatPackage({pkg:r}),u=new Blob([l],{type:"text/markdown"}),d=new File([u],"taste.md",{type:"text/markdown"});if(i.append("files[taste.md]",d),"category"===s)return i;const m=getTastePath({target:"local-project"}),g=e.join(m,r.category);if(!b(g))return i;const p=getCategoryTasteFile({target:"local-project",category:r.category});if(!b(p))return i;const h=await R.readFile(p,"utf-8"),f=new Blob([h],{type:"text/markdown"}),y=new File([f],"taste.md",{type:"text/markdown"});return i.append(`files[${r.category}/taste.md]`,y),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(b(a)){const e=await R.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:hr.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}${wt.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}${wt.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:hr.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()}${wt.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:hr.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()}${wt.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()}${wt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,l=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:a});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:l.status,extra:{"package.count":t.length}}),await l.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${wt.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 R.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 ke("list").alias("ls").option("-g, --global","List global packages").addOption(new Pe("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Pe("--staging","Use staging environment").hideHelp()).description(`List available packages ${te.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"),_t(),_t(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),Ot(),_t(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),Sr(),_t(),Sr(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),_t(),Ot(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),xn(),__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 Jh={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?Jh.remote:e.global?Jh.global:Jh.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` ${te.white(e.category)}${e.isPublic?te.green(" [public]"):""}${e.isPublic&&e.starCount?te.yellow(` ${Se.star}${e.starCount}`):""}${e.downloadCount?te.gray(` ${Se.arrowDown}${e.downloadCount}`):""}${n}${te.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?De(`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${Wh} Packages`),console.log(`${te.gray("⎿")} ${te.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(te.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(te.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 R.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 tt([{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"),_t(),_t(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var Qh=new Set(["local-project","local-global","remote-project","remote-user"]);async function open7(e){const{package:t,target:n}=e;if(!Qh.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=st.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 ke("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 ${te.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 se(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${te.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(`${te.green(Se.tick)} Opened ${te.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"),_t(),_t(),_t(),_t();var Yh=null,Zh=!1;function setActiveSpinner(e){Yh=e}function stopActiveSpinner(e){Yh&&(Yh.stop(e),Yh=null)}function setPrompted(e){Zh=e}function wasPrompted(){return Zh}function beginPrompt(e,t){stopActiveSpinner(),Te.intro(te.dim(e)),t&&Te.log.message(te.dim(t)),setPrompted(!0)}function handleCancel(e){Te.isCancel(e)&&(Te.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Te.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Te.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),Te.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${te.green(`'${t}'`)} from ${n}`,s),Te.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${te.dim(`(from ${n})`)}`);const a=await Te.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),Te.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${te.green(`'${t}'`)} to global`,o),Te.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await Te.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),Te.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${te.green(`'${t}'`)} from global`,o),Te.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await Te.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),Te.log.warn("Non-interactive terminal detected, skipping push"),"skip";const a=ot(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${te.green(`'${t}'`)} to ${n}`,s),Te.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),Te.log.info(`Current package: ${te.cyan(a)} ${te.dim("(review)")}`);const i=await Te.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 l=i;return startStrategySpinner(l),l}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),Te.log.warn("Non-interactive terminal detected, skipping push"),"skip";const a=ot(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${te.green(`'${t}'`)} to ${n}`,s),Te.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),Te.log.info(`Current package: ${te.cyan(a)} ${te.dim("(review)")}`);const i=await Te.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 l=i;return startStrategySpinner(l),l}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 l=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=l}async function processPackage(e){const{tastePkg:t,result:n}=e;try{await executePackageStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullProjectPackage(e){const{files:t,packageName:n,owner:r,overwrite: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 l=t.filter(e=>"taste.md"!==e.file);for(const e of l){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 l={category:n,learnings:parseTasteContent(i.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,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"),_t(),_t(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),_t(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var Xh=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),ef=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),tf=__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 l=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=l}async function pullSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePullStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pull(e){const{packages:t,source:n,overwrite:r=!1,strategy:o}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return Xh({pkg:"all",error:`Invalid source: ${n}`});const s=tf(n);let a;try{a="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return Xh({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===a.length)return Xh({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 l=t.length>0?a.filter(e=>t.includes(e.category)):a;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=ef();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:o,overwrite:r,result:u});return u}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 Xh({pkg:n,error:"Taste package not found in remote"});const{type:i,files:l}=a,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy: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=ef();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return Xh({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Te.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?te.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${te.green(a)}Replaced ${te.green(`'${t}'`)} taste package in project`+i;if(s){const e=formatMergeParts(s);return`${te.green(a)}Pulled ${te.green(`'${t}'`)} taste package from ${n} ${te.gray(`(${e.join(", ")})`)}`+i}return`${te.green(a)}Pulled ${te.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"}`,l=[];return s.length>0&&l.push(wrapLine(`${te.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${te.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&l.push(wrapLine(`${te.dim("Skipped")} (${o.length}) ${te.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Te.log.message(l.join("\n")),Te.outro(`${i} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${te.green(Se.tick)} ${i} from ${n}`),l.length>0&&console.log(l.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(te.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new ke("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 Pe("--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 Pe("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${te.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(De("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(De("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 Tl({baseUrl:e}),n=await t.get({endpoint:wt.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 Te.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(`${te.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,l=wasPrompted()?"":`${Se.tick} `;if(!i)return logResult2(`${te.green(l)}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?` ${te.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${te.green(l)}Replaced ${s} in ${i}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${te.green(l)}Pushed ${s} to ${i}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),p=g.length>0?` ${te.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${te.green(l)}Pushed ${s} to ${i}${p}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],o=t.filePaths?.[r],s=n.remote&&o,a=s?o:"global",i=wasPrompted()?"":`${Se.tick} `,l=!s&&o?te.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${te.green(i)}Replaced ${te.green(`'${r}'`)} taste package in ${a}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${te.green(i)}Pushed ${te.green(`'${r}'`)} taste package to ${a} ${te.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${te.green(i)}Pushed ${te.green(`'${r}'`)} taste package to ${a}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",o=wasPrompted()?"":`${Se.tick} `;return logResult2(wrapLine(`${te.green(o)}Pushed ${te.green(t.packagesPushed.length)} taste packages ${te.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(te.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(`${te.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&a.push(wrapLine(`${te.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&a.push(wrapLine(`${te.dim("Skipped")} (${r.length}) ${te.dim(r.join(", "))}`,4)),a.length>0&&Te.log.message(a.join("\n"));const i=`${s} ${1===s?"package":"packages"}`;Te.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(`${te.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${te.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${te.dim("Skipped")} (${n.length}) ${te.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"),_t(),__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"),_t(),xn(),_t(),Ot(),__name(fetchUserNamespaces,"fetchUserNamespaces"),_t(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),_t(),_t();var nf=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),rf=__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",l=o.reduce((e,t)=>e+t.learnings.length,0),u=rf(r.files);return"project"!==i?promptTypeMismatchStrategy({packageName:s,owner:a,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:s,owner:a,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,isPublicExplicitlySet:a,flagStrategy:i}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l});if("skip"===await resolvePushAllStrategy({flagStrategy:i,overwrite:o,existingProject:d,packagesToPush:n,projectName:l,owner:r}))return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:a?s:d?.isPublic??!1});for(const e of n)u.packagesPushed.push(e.category),u.filePaths[e.category]=`${r}/${l}`,u.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&u.overwritten.push(...n.map(e=>e.category)),u}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return nf({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var of=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),sf=__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 af=__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,l="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),u=await resolveSinglePushStrategy({flagStrategy:r,overwrite:o,existingPkg:l,target:n,tastePkg:t});if("skip"===u)return void i.skipped.push(t.category);if("overwrite"===u&&(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"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:s,isPublic:a}),i.packagesPushed.push(t.category),i.mergeDetails[t.category]=r}const d=af({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 of({pkg:"all",error:"No taste directory found in project"});const i=await getAllPackages2();if(0===i.length)return of({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:i,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?i.filter(e=>n.includes(e.category)):i;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:a}):of({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return of({pkg:"all",error:`Invalid target: ${r}`});const m=sf();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:a,overwrite:o,userOwner:d,isPublic:s,result:m});return m}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 of({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:i}),filePath:`${i.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return of({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:a,overwrite:o,existingPkg:u,target:"remote-project",tastePkg:i}),m=t?s:u?.isPublic??!1,g=sf();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:i,owner:n,isPublic:m}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:i,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),g.packagesPushed.push(r),g.mergeDetails[r]=t}return g.filePaths[r]=`${n}/${r}`,g}async function pushRemote(e){const{packageName:t}=e;if(!exists())return of({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return of({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 Te.select({message:"Owner",options:r,initialValue:t});return Te.isCancel(o)&&(Te.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new ke("push").description(`Push taste packages to remote ${te.dim("(commandcode.ai)")} or global ${te.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 Pe("--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 Pe("--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"),_t(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var cf=__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};Te.intro(te.dim(`pushing ${t}`)),setPrompted(!0);const o=Te.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),Te.outro(te.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(te.dim(` Pushing ${s} to ${a} (remote)${i}`)),console.log(""),setActiveSpinner(De("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:cf(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}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:cf(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=Te.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(De("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"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(te.dim(` Pushing ${i} to ${l}${u}`)),console.log(""),setActiveSpinner(De("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 ke(Ct.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),e}function formatVersion(e,t,n=!1){const r=n?re.bold(re.green(t)):re.white(t);return`${re.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${re.bold(re.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(re.dim(`Run ${re.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(re.dim("Try updating manually:")),console.log(re.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(re.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=De("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.stop(),console.log(""),console.log(`${re.green(Se.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${re.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=De("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:hr.UPDATE_COMMAND,heading:"CLI update failed","update.current_version":t.currentVersion,"update.target_version":t.latestVersion}}),showManualUpdateHint(t.latestVersion),await shutdownTelemetry(),process.exit(1)),e.succeed(`Updated to v${t.latestVersion}`),showUpdateSuccessHint()):e.succeed(`Up to date ${re.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(resolveStrategyLabel,"resolveStrategyLabel"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),__name(createTasteCommand,"createTasteCommand"),_t(),Ot(),Sr(),__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 lf=new ke("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);_t();var uf=__name((e,t)=>`${Se.info} ${e}: ${re.cyan(t)}`,"formatInfoLine"),df=__name(e=>re.bold(`${e}:`),"formatSectionHeader"),mf=__name(e=>re.red(e),"formatError"),gf=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),pf=__name(e=>["",df("User Information"),uf("Name",e.name),uf("Email",e.email),uf("Username",e.userName)],"buildUserOutput"),hf=__name(e=>["",df("Organization"),uf("Name",e.name),uf("Login",e.login)],"buildOrgOutput"),ff=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),yf=__name((e,t)=>{ff(pf(e)),t&&ff(hf(t)),console.log("")},"displayUserInfo"),wf=__name(e=>null!==e&&e.length>0,"validateApiKey"),Ef=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=De("Fetching user information...").start();try{const t=await getAuthKey();wf(t)||(e.fail(mf('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();Ef(n)||(e.fail(mf("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),yf(n.user,n.org)}catch(t){e.fail(mf(`Error: ${gf(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var bf=new ke("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var Sf=createProgram();Sf.action(interactiveModeAction),Sf.addCommand(Lh),Sf.addCommand(Mh),Sf.addCommand(bf),Sf.addCommand(lf),Sf.addCommand(Oh),Sf.addCommand(createTasteCommand()),Sf.addCommand(createMcpCommand()),Sf.addCommand(Fh),Sf.addCommand(so),Sf.addCommand(uo),Sf.addCommand(wo),setupCommanderHooks(Sf),Sf.parse();
|
|
229
|
+
`}),index("subscriptions_owner_idx").on(e.userId,e.orgId)]);c(bl),b2(bl),_t();var Sl=sql`(SELECT NULLIF(current_setting('app.current_user_id', true), '')::uuid)`,vl=sql`users`,Cl=sc("free_credits_audit",{id:uuid("id").defaultRandom().primaryKey(),date:date("date").notNull().unique(),totalCreditsGiven:numeric("total_credits_given").notNull(),syncedAt:timestamp("synced_at",{withTimezone:!0}).notNull()},e=>[index("free_credits_audit_date_idx").on(e.date),pgPolicy("free_credits_audit_select_admin",{as:"permissive",to:"app_user",for:"select",using:sql`(SELECT admin FROM ${vl} WHERE id = ${Sl})`}),pgPolicy("free_credits_audit_insert_admin",{as:"permissive",to:"app_user",for:"insert",withCheck:sql`(SELECT admin FROM ${vl} WHERE id = ${Sl})`}),pgPolicy("free_credits_audit_update_admin",{as:"permissive",to:"app_user",for:"update",using:sql`(SELECT admin FROM ${vl} WHERE id = ${Sl})`}),pgPolicy("free_credits_audit_delete_admin",{as:"permissive",to:"app_user",for:"delete",using:sql`(SELECT admin FROM ${vl} WHERE id = ${Sl})`})]);c(Cl),b2(Cl),_t();var kl=sql`(SELECT NULLIF(current_setting('app.current_user_id', true), '')::uuid)`,Pl=sc("follows",{id:uuid("id").defaultRandom().primaryKey(),followerId:uuid("follower_id").references(()=>$c.id,{onUpdate:"cascade",onDelete:"cascade"}).notNull(),followedUserId:uuid("followed_user_id").references(()=>$c.id,{onUpdate:"cascade",onDelete:"cascade"}),followedOrgId:uuid("followed_org_id").references(()=>Dc.id,{onUpdate:"cascade",onDelete:"cascade"}),createdAt:timestamp("created_at",{withTimezone:!0}).defaultNow().notNull()},e=>[check("follows_exactly_one_target",sql`(followed_user_id IS NOT NULL AND followed_org_id IS NULL) OR (followed_user_id IS NULL AND followed_org_id IS NOT NULL)`),check("follows_no_self_follow",sql`follower_id != followed_user_id OR followed_user_id IS NULL`),uniqueIndex("follows_user_unique").on(e.followerId,e.followedUserId).where(sql`followed_user_id IS NOT NULL`),uniqueIndex("follows_org_unique").on(e.followerId,e.followedOrgId).where(sql`followed_org_id IS NOT NULL`),index("follows_follower_idx").on(e.followerId),index("follows_followed_user_idx").on(e.followedUserId),index("follows_followed_org_idx").on(e.followedOrgId),pgPolicy("follows_select_all",{for:"select",to:"app_user",using:sql`true`}),pgPolicy("follows_insert_own",{for:"insert",to:"app_user",withCheck:sql`follower_id = ${kl}`}),pgPolicy("follows_delete_own",{for:"delete",to:"app_user",using:sql`follower_id = ${kl}`}),pgPolicy("follows_select_public",{for:"select",to:"public_user",using:sql`true`})]);c(Pl),b2(Pl);var Tl=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=trackAPICallStart({method:e.method,endpoint:t}),o=await this.buildHeaders({headers:e.headers,span:r.span});let s;try{s=await this.makeRequest({url:n,options:e,headers:o})}catch(e){const t=new Oo({cause:e instanceof Error?e:void 0});throw r.end({statusCode:0,error:t}),t}if(!s.ok){const{error:e}=await this.handleErrorResponse({response:s});throw r.end({statusCode:s.status,error:e}),e}return r.end({statusCode:s.status}),e.stream?s.body:s.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e,span:t}){const n=await getAuthKey(),r=getTraceId(),o=t?.spanContext(),s=r&&o?.spanId?`00-${r}-${o.spanId}-01`:void 0,a=getTelemetryEnv(),i="prod"===a?"production":a;return{"Content-Type":"application/json",[yt.CLI_ENVIRONMENT]:i,...n?{Authorization:`Bearer ${n}`}:{},...s?{traceparent:s}:{},...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:Do.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"})}};function getPersonalSkillsDir(){return t.join(f.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return t.join(process.cwd(),".commandcode","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await D.access(r),r}catch{}const o=t.join(n,"skill.md");try{return await D.access(o),o}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await D.access(n);const e=await D.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await D.stat(t.join(n,e.name))).isDirectory()?e:null}catch{return null}return null}))).filter(e=>null!==e);return(await Promise.all(r.map(async e=>{try{const r=await resolveSkillFilePath({skillDir:t.join(n,e.name)});if(!r)return null;const o=await D.readFile(r,"utf-8"),{data:s}=Ue(o),a=Jo.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)}ln(),_t(),ln(),_t(),_t(),_t(),Ot(),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),_t(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),_t(),_t(),_t(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath"),_t();var Al=p.object({absolutePath:p.string().describe("The absolute path to the file to read"),offset:p.preprocess(e=>"string"==typeof e?parseInt(e,10):e,p.number().optional()).describe("Optional line number to start reading from (0-based index)"),limit:p.preprocess(e=>"string"==typeof e?parseInt(e,10):e,p.number().optional()).describe("Optional number of lines to read")});p.object({content:p.union([p.string(),p.instanceof(Buffer)]),contentType:p.enum(["text","binary"]),fileType:p.string(),size:p.number(),linesRead:p.number().optional()});var xl=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 xl("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=e.normalize(n);try{await R.access(s,w.constants.F_OK|w.constants.R_OK)}catch{throw new xl(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await R.stat(s)).isFile())throw new xl("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 xl("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new xl("Offset must be >= 0","INVALID_OFFSET");if(void 0!==o&&o<=0)throw new xl("Limit must be > 0","INVALID_LIMIT");try{if(i){const e=await R.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 R.readFile(s,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof xl)throw e;throw new xl(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var Il={".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",...Il}[n]||"unknown"}function isBinaryFile(e){return Object.values(Il).includes(e)}async function readTextFileLines(e,t,n){const r=(await R.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),l=e.relative(process.cwd(),t),u=1e5;if(i.length>u){n.push({token:o,resolvedPath:t,content:"",tooLarge:!0});const e=`${l}`;r=r.replace(o,e);continue}n.push({token:o,resolvedPath:t,content:i});const d=`{${l}: ${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"),_t(),_t();var _l="read_file",Nl="edit_file",$l="write_file",Rl="read_directory",Dl="read_multiple_files",Ol="grep",Ll="shell_command",Ml="think",Fl="todo_write",Ul="ask_user_question",jl="kill_shell",Bl="web_search",ql="web_fetch",zl=__name(e=>e===Bl,"isWebSearchTool"),Wl=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],Hl=__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 Wl.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:zl(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),Vl=["create_file","delete_file",Nl,$l,Ll],Gl=[Ll];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}_t(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText"),_t(),_t(),_t();var Kl="2025-03-26",Jl={name:"command-code",version:"1.0.0"};Promise.resolve().then(()=>(Wn(),Mn)).then(({getPackageJson:e})=>{Jl.version=e().version??"1.0.0"}).catch(()=>{}),_t(),_t();var Ql=p.object({authorizationUrl:p.string(),tokenUrl:p.string(),clientId:p.string(),clientSecret:p.string().optional(),scopes:p.array(p.string()).optional()}),Yl=p.object({transport:p.enum(["stdio","http"]),enabled:p.boolean().default(!0),command:p.string().optional(),args:p.array(p.string()).optional(),url:p.string().optional(),headers:p.record(p.string(),p.string()).optional(),oauth:Ql.optional(),env:p.record(p.string(),p.string()).optional()}),Zl=p.object({mcpServers:p.record(p.string(),Yl)});_t(),Ot();var Xl="mcp.json";function getUserMcpConfigPath(){return e.join(f.homedir(),".commandcode",Xl)}function getLocalMcpConfigPath(t=process.cwd()){const n=Be(t);return e.join(f.homedir(),".commandcode","projects",n,Xl)}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 R.readFile(n,"utf-8"),o=JSON.parse(r),s=Zl.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 R.mkdir(s,{recursive:!0}),await R.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"),xn(),Cr(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers"),_t();var eu=class _StdioTransport extends je{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=I(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)}};_t(),Cr(),Tr();var tu=class _HttpTransport extends je{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":`${Jl.name}/${Jl.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(()=>(zr(),Ar));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(),vr);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(),vr);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}},nu=class extends je{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 eu?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?eu.fromConfig(e):tu.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:Kl,capabilities:{roots:{}},clientInfo:Jl});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}},ru=null;function getMcpConnectionManager(){return ru||(ru=new nu),ru}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"),gr();var ou=p.object({id:p.string(),timestamp:p.number(),type:p.literal("image"),source:p.object({type:p.enum(["base64","url"]),media_type:p.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:p.string()})}),su=p.object({id:p.string(),timestamp:p.number(),input:p.string(),output:p.string().optional(),metadata:p.record(p.string(),p.any()).optional(),images:p.array(ou).optional().default([])}),au=su.extend({role:p.literal("user")}),iu=su.extend({role:p.literal("assistant")}),cu=su.extend({role:p.literal("tool"),name:p.string(),description:p.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),lu=su.extend({role:p.literal("bash"),command:p.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),uu=su.extend({role:p.literal("system")}),du=su.extend({role:p.literal("error")}),mu=su.extend({role:p.literal("info")}),gu=su.extend({role:p.literal("taste-onboarding")}),pu=su.extend({role:p.literal("command-result"),hasError:p.boolean().optional(),details:p.string().optional()}),hu=su.extend({role:p.literal("ide-status"),status:p.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:p.string().nullable(),details:p.array(p.string()).optional()}),fu=p.discriminatedUnion("role",[au,iu,cu,lu,uu,du,mu,gu,pu,hu]),yu=__name((e,t)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),wu=__name((e,t)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),Eu=__name(e=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),bu=__name((e,t,n)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Su=__name(e=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),vu=__name(e=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Cu=__name(e=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),ku=__name(()=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Pu=__name((e,t=!1,n)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),Tu=__name((e,t,n)=>fu.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),Au=__name(({name:e,input:t})=>{const n=Date.now();return fu.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"),xu=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return fu.parse(n)},"updateEntryWithOutput"),Iu=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),_u=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),Nu=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),$u=["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…"],Ru=__name(()=>$u[Math.floor(Math.random()*$u.length)],"getRandomLLMStatus"),Du=__name(e=>{switch(e){case _l:return"Read";case Nl:return"Edit";case $l:return"Write";case Rl:return"List";case Dl:return"Read Multiple";case Ol:return"Search";case Ll:return"Shell";case Fl:return"Todos";case Ml:return"Thinking…";case Bl:return"Web Search";case ql:return"Web Fetch";case Ul:return"Question";case"explore":return"Explore";case jl: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"),Ou=__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:ar})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),Lu=__name((e,t)=>{try{switch(e){case _l:case $l:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case Nl:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Rl:return toRelativePath(t.path||"directory");case Ol:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Ll: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 Fl:let o;try{o="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=Mu(o);return`${e?e.length:0} items`}catch{return"items"}case Ml:return t.content||"planning";case Dl:const s=t.include||[];return Array.isArray(s)?s.join(", "):"multiple files";case Bl:return t.query||"search";case ql:return t.url||"fetch";case Ul:return"User answered questions";case jl: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 Ou(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:ir})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),Mu=__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")}_t(),_t(),_t(),__name(formatOutput,"formatOutput");var Fu={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=Al.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")};_t(),_t();var Uu=p.object({filePath:p.string().describe("The absolute path to the file to edit"),oldValue:p.string().describe("The text to replace"),newValue:p.string().describe("The new text to insert"),replacementCount:p.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:p.boolean().optional().describe("Whether to replace all occurrences (default: false)")});p.object({path:p.string(),replacementsCount:p.number(),oldContent:p.string(),newContent:p.string()}),p.object({name:p.string(),message:p.string(),code:p.string().optional()}),_t(),_t(),_t();var ju=p.object({backupFileName:p.string().nullable(),version:p.number().int().positive(),backupTime:p.string().datetime()}),Bu=p.object({messageId:p.string().uuid(),trackedFileBackups:p.record(p.string(),ju),timestamp:p.string().datetime()});p.object({type:p.literal("file-history-snapshot"),messageId:p.string().uuid(),snapshot:Bu,isSnapshotUpdate:p.boolean()}),p.object({maxFileSize:p.number().int().positive().default(10485760),retentionDays:p.number().int().positive().default(30)});var qu=class extends Error{static{__name(this,"CheckpointError")}code;constructor(e,t){super(e),this.name="CheckpointError",this.code=t}};function getPathHash(e){const{filePath:t}=e;return`${j.createHash("sha256").update(t).digest("hex").slice(0,16)}-${t.length}`}function getBackupFileName(e){const{filePath:t,version:n}=e;return`${getPathHash({filePath:t})}@v${n}`}function getCommandCodeBasePath(){return t.join(f.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:n}=e;return t.join(getCommandCodeBasePath(),"file-history",n)}function getBackupFilePath(e){const{sessionId:n,backupFileName:r}=e;return t.join(getFileHistoryPath({sessionId:n}),r)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await D.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 D.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await D.writeFile(r,n);const e=await D.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 D.rename(r,t)}catch(e){try{await D.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await D.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await D.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}_t(),_t(),Ot(),__name(getPathHash,"getPathHash"),__name(getBackupFileName,"getBackupFileName"),__name(getCommandCodeBasePath,"getCommandCodeBasePath"),__name(getFileHistoryPath,"getFileHistoryPath"),__name(getBackupFilePath,"getBackupFilePath"),__name(getAvailableDiskSpace,"getAvailableDiskSpace"),__name(hasEnoughDiskSpace,"hasEnoughDiskSpace"),__name(ensureDirectoryExists,"ensureDirectoryExists"),__name(atomicWriteFile,"atomicWriteFile"),__name(getFileSizeBytes,"getFileSizeBytes"),__name(fileExists,"fileExists"),__name(getCurrentTimestamp,"getCurrentTimestamp"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod"),Sr();var zu={maxFileSize:10485760,retentionDays:30},Wu=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...zu,...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 D.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:hr.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 D.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new qu(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:hr.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await D.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 D.access(t,D.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 D.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await D.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await D.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}};_t(),gr(),Sr();var Hu=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new Wu({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:hr.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}};_t();var Vu=null;function initializeCheckpointService(e){const{sessionId:t}=e;return Vu=new Hu({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return Vu?Vu.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 v.access(n,C.F_OK|C.R_OK|C.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 l=(i.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===l)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let u,d;if(s)u=l;else if(u=a,u>l)throw createFileEditError(`Expected ${u} replacements, but only found ${l} occurrences`,"INSUFFICIENT_MATCHES");let m=0;if(s||u===l)d=i.split(r).join(o),m=l;else{d=i;for(let e=0;e<u;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+o+d.substring(e+r.length),m++)}}if(0===m)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await v.writeFile(n,d,"utf-8"),{path:n,replacementsCount:m,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"),_t(),__name(formatOutput2,"formatOutput");var Gu={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=Uu.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")};_t(),_t();var Ku=p.object({path:p.string().describe("The absolute path to the directory to read"),exclude:p.array(p.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:p.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});p.object({files:p.array(p.string()),directories:p.array(p.string())});var Ju=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 Ju("Path must be absolute, not relative","INVALID_PATH");try{if(!(await R.stat(n)).isDirectory())throw new Ju("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Ju)throw e;throw new Ju(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await R.readdir(n);let s=[];o&&(s=await loadGitIgnorePatterns(n));const a=[...r,...s],i=[],l=[];for(const r of t){if(shouldIgnoreEntry(r,a))continue;const t=e.join(n,r);try{const e=await R.stat(t);e.isDirectory()?l.push(r):e.isFile()&&i.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:i.sort(),directories:l.sort()}}catch(e){if(e instanceof Ju)throw e;throw new Ju(`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 R.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 R.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(qe(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")}_t(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),_t(),__name(formatOutput3,"formatOutput");var Qu={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=Ku.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")};_t(),_t();var Yu=p.object({filePath:p.string().describe("The absolute path where the file should be written"),content:p.string().describe("The content to write to the file")});async function writeFile4({filePath:e,content:n}){const o=e.startsWith("~/")?t.join(f.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 b(e)||await O(e,{recursive:!0}),await backupFileBeforeEdit({filePath:o}),await L(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}`}p.object({success:p.boolean(),message:p.string(),path:p.string().optional()}),_t(),__name(writeFile4,"writeFile"),_t(),__name(formatOutput4,"formatOutput");var Zu={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=Yu.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")};_t(),_t();var Xu=p.object({include:p.array(p.string()).describe("Array of glob patterns to include files"),exclude:p.array(p.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:p.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:p.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:p.string().optional().describe("Base directory for relative paths. Default: current working directory")}),ed=p.object({filePath:p.string(),content:p.string(),fileType:p.string(),size:p.number()});p.object({content:p.string(),filesRead:p.array(p.string()),errors:p.array(p.object({file:p.string(),error:p.string()})),fileDetails:p.array(ed)});var td=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}};_t();var nd=["**/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 ze(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 td("At least one include pattern must be provided","NO_PATTERNS");const i=t.resolve(a),l={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];s&&e.push(...nd);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});l.fileDetails.push(o),l.content+=`\n// File: ${e} (${r.fileType})\n`,l.content+=o.content,l.content+="\n",l.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);l.errors.push({file:e,error:n}),l.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return l}catch(e){if(e instanceof td)throw e;throw new td(`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"),_t(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var rd={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=Xu.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")};_t(),_t();var od=p.object({pattern:p.string().min(1,"Pattern is required"),include:p.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},p.array(p.string()).optional()),directory:p.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=I(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>cr)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>lr)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")}_t(),gr(),__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),_t(),__name(formatGrepResults,"formatGrepResults");var sd={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=od.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")};_t(),_t();var ad=p.object({pattern:p.string().min(1,"Pattern is required"),path:p.string().optional()}),id=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 id("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new id("Search path must be within the current working directory or an added directory","INVALID_PATH");const o=await ze(n,{cwd:e,ignore:Tt,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 D.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 id)throw e;if(e instanceof Error)throw new id(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new id("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")}_t(),Ot(),jt(),__name(globSearch,"globSearch"),_t(),__name(formatGlobResults,"formatGlobResults");var cd={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=ad.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")};_t(),_t();var ld=p.object({command:p.string().min(1,"Command cannot be empty"),args:p.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},p.array(p.string()).optional()),directory:p.string().optional(),timeout:p.preprocess(e=>"string"==typeof e?parseInt(e,10):e,p.number().optional())}),ud=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 ud("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(e.isAbsolute(o))throw new ud("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=e.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await D.stat(i)).isDirectory())throw new ud(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof ud)throw e;throw new ud(`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="",l="",u=!1;const d=r.length>0?We([n,...r]):n,m=setTimeout(()=>{if(!u){g.kill("SIGTERM");const e=Date.now()-a;o(new ud(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",i,l,e))}},s),g=I(d,[],e);g.stdout?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>cr)return l="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void g.kill("SIGTERM");i+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,g.kill("SIGTERM")}}),g.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>lr)return void(l+="\n[Error output truncated: too large]");l+=t}catch(e){l+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),g.on("close",(e,n)=>{u=!0,clearTimeout(m);const r=Date.now()-a;0===e?t({stdout:i.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):o(new ud(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,i.trim(),l.trim(),r))}),g.on("error",e=>{u=!0,clearTimeout(m);const t=Date.now()-a;o(new ud(`Failed to start command: ${e.message}`,"START_FAILED",null,null,i.trim(),l.trim(),t))})})}catch(e){if(e instanceof ud)throw e;throw new ud(`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")}_t(),gr(),__name(executeShellCommand,"executeShellCommand"),_t(),__name(formatShellCommandResult,"formatShellCommandResult");var dd={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=ld.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}`}_t(),_t(),__name(think,"think");var md={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)}_t(),_t(),__name(todoWrite,"todoWrite");var gd={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")}_t(),_t(),__name(askUserQuestion,"askUserQuestion"),_t(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var pd={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")};_t(),_t();var hd=p.object({port:p.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:p.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"}),fd=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=I(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 fd(`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 fd("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 fd(`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")}_t(),__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"),_t(),__name(formatKillshellResult,"formatKillshellResult");var yd={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=hd.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")};_t();var wd={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")};_t();var Ed={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")};_t(),_t(),_t(),_t(),_t(),Ot(),_t(),_t();var bd=["explore","plan","review","general"],Sd=[{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&&bd.includes(e.toLowerCase())}function getRootAgentDir(){return t.join(f.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await D.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await D.readFile(o,"utf-8"),{data:a,content:i}=Ue(s),l=a.name||r.replace(".md","");if(isReservedAgentName(l))return null;let u=a.tools||"";return"*"!==u&&'"*"'!==u||(u="*"),{name:l,description:a.description||"",tools:u,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"),_t(),Ot(),ln(),Dn(),Zt(),_t(),Ot(),ln(),_t(),Ot(),Sr(),xn(),_t();var vd=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext"),Cd=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(f.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Be(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=_("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await D.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:hr.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await D.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 D.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 D.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=vd(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=Lu(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=Lu(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 D.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 D.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await D.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 D.access(n)}catch{return[]}const e=(await D.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 D.stat(s),o=(await D.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=vd(s);const l=await _SessionManager.loadSessionMetaForId(e,n),u=l?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:s||"No messages",title:u||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 D.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 D.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 D.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await D.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 D.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 D.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 D.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 D.writeFile(r,s)}else await D.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 D.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 D.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 D.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=vd(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}};Zt(),Nn(),Dn(),xn();var kd=new Map,Pd=null;function getRequest(){return Pd||(Pd=new Tl({baseUrl:getApiBaseUrl()})),Pd}function stableStringify(e){return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map(stableStringify).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+stableStringify(e[t])).join(",")+"}"}function generateCacheKey(e,t){return`${e}:${stableStringify(t)}`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:vt,max_tokens:80,temperature:.3,stream:!0},threadId:crypto.randomUUID()}}async function getAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced();let n;e===St.ANTHROPIC&&(n=await rn.getValidAccessToken(),validateOAuthToken({token:n,provider:e}));const r={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(r[yt.OAUTH_TOKEN]=`Bearer ${n}`),r}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=kd.get(n);if(r)return kd.delete(n),kd.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 ${wt.ALPHA.GENERATE} with model: ${vt}`);const s=e.post({endpoint:wt.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=He.fromReadableStream(a);let l="",u=null;if(i.on("text",e=>{l+=e}),i.on("error",e=>{u=e}),await i.finalMessage(),u)throw u;dlog(`[ToolDescription] raw response: "${l}"`);const d=cleanDescription(l);if(d){if(kd.size>=100){const e=kd.keys().next().value;void 0!==e&&kd.delete(e)}kd.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,4e3)}function createPrompt(e){return`Precisely describe what this command does in active voice. Never use a word like "complex" or "risk" in description. Start with a verb, capital letter, no period. Never say you need to see more or that the command is incomplete — always describe what the command does based on what you see.\n\nFor simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):\n- ls → "List files in current directory"\n- git status → "Show working tree status"\n- npm install → "Install package dependencies"\n\nFor piped commands or obscure flags, add enough context to clarify what it does:\n- find . -name "*.tmp" -exec rm {} \\; → "Find and delete all .tmp files recursively"\n- git reset --hard origin/main → "Discard all local changes and match remote main"\n- curl -s url | jq '.data[]' → "Fetch JSON from URL and extract data array elements"\n\nCommand: ${`${sanitize(e.command||"")} ${sanitize(Array.isArray(e.args)?e.args.join(" "):e.args||"")}`.trim()}\n\nDescription:`}function cleanDescription(e){let t=e.trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim();return t.length>0&&(t=t.charAt(0).toUpperCase()+t.slice(1)),t.split(/\s+/).length<3?null:t}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=f.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"),_t(),_t(),Ot(),__name(isPlanPath,"isPlanPath");var Td=["edit_file","delete_file","shell_command","todo_write","kill_shell"],Ad=["exit_plan_mode"],xd=["enter_plan_mode"];function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!Ad.includes(e.name)):"plan"===n?t.filter(e=>!Td.includes(e.name)&&!xd.includes(e.name)):t.filter(e=>!Ad.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 Td.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"),_t(),gr();var Id=ur,_d=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)>Id}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"),_t(),__name(sleep,"sleep"),_t(),xn();var Nd=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(h.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return e.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const t=h.homedir();return e.join(t,".commandcode","AGENTS.md")}function getProjectMemoryPaths(t){return[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:b(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(b(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:b(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return b(e)&&A(e).isFile()?await R.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 l=a;for(const t of i){const s=t[1];let a=s;s.startsWith("~/")?a=e.join(h.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);l=l.replace(t[0],`\n# Imported from ${s}\n${e}\n`)}}return l=l.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>s[parseInt(t)]),l}async function loadAllMemories(t,n){const r=new Map,o=getEnterpriseMemoryPath();if(b(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const s=getUserMemoryPath();if(b(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(b(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(b(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 b(r)||await R.mkdir(r,{recursive:!0}),b(t)||await R.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const o=I(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 b(n)||await R.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}}_t(),Ot(),__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"),Nn();var $d=new Nd("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 l=null;const u=Date.now();let d=null;try{const m=i?.permissionMode||"standard",g=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:a}),clientTools:r,serverTools:o,mode:m});let p=Date.now();const h=10,f=[];if(i?.onFeedUpdate){const e=Lu(t.name,n);l=Au({name:t.name,input:e}),i.onFeedUpdate(l)}d=setInterval(()=>{if(i?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},i.onFeedUpdate(l)}},1e3);const y=await getConfiguredProvider(),w=await isOAuthEnforced();let E;y===St.ANTHROPIC&&(E=await rn.getValidAccessToken(),validateOAuthToken({token:E,provider:y}));const b=getApiBaseUrl(),S=new Tl({baseUrl:b});let v=0;const C=[];let k=n?.messages;if("string"==typeof k)try{k=JSON.parse(k)}catch(e){k=[]}if(Array.isArray(k)&&k.length>0)for(const e of k)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&C.push({role:"user",content:t})}const P={stream:!0,messages:C,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:g,model:`anthropic:${getConfiguredModel()}`},T=await isTasteLearningEnabled(),A={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.TASTE_LEARNING]:T.toString(),[yt.INTERNAL_TEAM_FLAG_HEADER]:w.toString()};E&&(A[yt.OAUTH_TOKEN]=`Bearer ${E}`);const x=getEnvironmentContext(),I=await getMemoryContent([]),_=crypto.randomUUID();let N="",$=!0;const R=__name(()=>{$d.debug("[Agent] Abort signal triggered, stopping immediately"),$=!1,d&&(clearInterval(d),d=null)},"abortHandler");i?.abortSignal&&i.abortSignal.addEventListener("abort",R);try{for(;$;){if(i?.abortSignal?.aborted)throw $d.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:S,body:{mode:"custom-agent",config:x,memory:I,threadId:_,params:{...P,messages:C}},headers:A,abortSignal:i?.abortSignal,onTextDelta:__name(e=>{v+=estimateTokens(e);const t=Date.now();if(i?.onFeedUpdate&&l&&t-p>=h){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:v,elapsedSeconds:e}},i.onFeedUpdate(l),p=t}},"onTextDelta")});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(v=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if(N=t.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(t,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&&C.push({role:"assistant",content:e}),$=!1;break}const r=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);r.length>0&&C.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=Vl.includes(t.name),g=Gl.includes(t.name)?generateToolDescription(t.name,n).catch(()=>null):Promise.resolve(null);if(r&&i?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await g;if(!await i.onPermissionRequest(t.name,n,e)){$d.debug(`Permission denied for tool: ${t.name}`),a=!0;break}d=setInterval(()=>{if(i?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},i.onFeedUpdate(l)}},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,$d.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,$d.debug(`Resolved input for ${t.name}: ${Lu(t.name,n)}`)):$d.debug(`No path resolution needed for ${t.name}: ${Lu(t.name,n)}`)}if(i?.onFeedUpdate&&l){const e=Lu(t.name,n);f.push({name:t.name,input:e}),f.length>3&&f.shift();const r=Date.now(),o=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:v,elapsedSeconds:o,recentTools:[...f]}},$d.debug(`Updating agent with recentTools (${f.length} tools): ${JSON.stringify(f)}`),i.onFeedUpdate(l)}const p=await executeTool(t.name,n,{abortSignal:i?.abortSignal,permissionMode:m});if(i?.abortSignal?.aborted)throw new Error("Interrupted by user");const h=checkToolOutputTokensLimit(p,t.name);if(o.push({type:"tool_result",tool_use_id:t.id,content:h}),s.add(t.id),i?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:v,elapsedSeconds:t,recentTools:[...f]}},i.onFeedUpdate(l)}$d.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),$d.error(`Tool execution failed: ${t.name} - ${n}`)}}if(a){const e=C[C.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:C.pop()}$=!1;break}const g=[...o];C.push({role:"user",content:g})}}finally{i?.abortSignal&&i.abortSignal.removeEventListener("abort",R)}if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:N||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:v,elapsedSeconds:t}},i.onFeedUpdate(l)}return N||"DONE"}catch(e){if(d&&(clearInterval(d),d=null),i?.onFeedUpdate&&l){const t=Date.now(),n=(t-u)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||i?.abortSignal?.aborted;l={...l,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:u,endTime:t,tokensUsed:l?.metadata?.tokensUsed||0,elapsedSeconds:n}},i.onFeedUpdate(l)}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:wt.ALPHA.GENERATE,signal:o,headers:r}),a=He.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 l=await a.finalMessage();if(i)throw i;return l}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);$d.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 Lo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof Fo||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 Lo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof Fo||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}=Hl({serverToolBlock:e,contentBlocks:r}),s=Lu(e.name,e.input),a={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:s,output:o?Iu(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 Rd=new Map,Dd=null;function initializeAgentManager(e){Dd=e}async function loadAgentTools(){if(!Dd)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Rd.clear();for(const e of Sd){const t=agentToTool(e,Dd);Rd.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Dd);Rd.set(t.name,t)}}async function getAgentTools(){return 0===Rd.size&&await loadAgentTools(),Array.from(Rd.values())}async function getAgentTool(e){return 0===Rd.size&&await loadAgentTools(),Rd.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(h.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"),_t(),Ot(),__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"),Sr();var Od=[Fu,Gu,Qu,Zu,rd,sd,cd,dd,md,gd,pd,yd,wd,Ed],Ld=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],Md=new Map(Od.map(e=>[e.name,e])),Fd=new Set([...Od.map(e=>e.name),...Ld.map(e=>e.name)]);function isAgentTool(e){return!Fd.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=Md.get(e);if(s||(s=await getAgentTool(e)),!s){const t=await getAgentTools(),n=[...Array.from(Md.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=(!Md.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=[...Od],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,...Ld]}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 Ud={};Od.forEach(e=>{Ud[e.name]=toPascalCase(e.name)}),Ld.forEach(e=>{Ud[e.name]=toPascalCase(e.name)});var jd={};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(Ud).forEach(([e,t])=>{jd[t]=e}),initializeAgentManager({clientTools:Od,serverTools:Ld,toolsMap:Md,displayNameToToolName:jd}),_t(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors"),Sr(),Ot(),Zt(),Nn(),Dn(),_t(),Ot(),ln(),xn(),_t();var Bd=new class extends je{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:l,categories:u,storage:d}=e,m={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:l,categories:u,storage:d};this.events.unshift(m),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",m)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}};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=[],l=[];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&&l.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:a,upgraded:i,downgraded:l}}_t(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings"),Nn(),Dn(),Sr();var qd=new Nd("LearningAgent"),zd=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:hr.LEARNING_AGENT,heading:"Learning pass failed"}}),Bd.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)];Bd.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),l=t.slice(i);let u=0,d=!1;dlog(`[LearningAgent] analyzing ${s} new messages for patterns`);const m=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(l,null,2)}`}];for(;u<this.maxTurns;){const e=await this.callLearningAPI({conversation:m}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.name).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),m.push({role:"assistant",content:e.content}),m.push({role:"user",content:n}),u++}u>=this.maxTurns&&qd.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Bd.addEvent({type:"no_learnings",message:"no changes to taste"}),Bd.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 w.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 w.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=>{Bd.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Bd.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Bd.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(!w.existsSync(this.tasteDir)){w.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");w.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!w.existsSync(t))return!1;const n=w.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let 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");w.mkdirSync(r,{recursive:!0}),Bd.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const a=`# ${t.name}\n${t.learnings.join("\n")}\n`;w.writeFileSync(s,a,"utf-8");const i=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;o=o.replace(t.fullSection,i)}return w.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 w.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(t){const{dir:n,prefix:r}=t,o=w.readdirSync(n,{withFileTypes:!0});let s="";for(let t=0;t<o.length;t++){const a=o[t],i=t===o.length-1,l=i?"└── ":"├── ";if(a.isDirectory()){s+=`${r}${l}${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=(w.readFileSync(e.join(n,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;s+=`${r}${l}${a.name} (${t} learnings)\n`}else s+=`${r}${l}${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===St.ANTHROPIC&&(o=await rn.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[yt.OAUTH_TOKEN]=`Bearer ${o}`);const a=await this.getTasteTools(),i=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${i})`);const l={conversation:t,tools:a,model:i,threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:wt.ALPHA.TASTE.LEARN,body:l,headers:s,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),u++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${d.message}`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_client_error"}),context:{component:hr.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(u>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:hr.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":u}}),d;const n=1e3*Math.pow(2,u);dlog(`[LearningAgent] retrying API call (${u}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw d||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return w.existsSync(r)}};_t(),Ot(),ln(),Zt(),Nn(),Dn(),xn();var Wd="claude-haiku-4-5-20251001",Hd=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===St.ANTHROPIC&&(o=await rn.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(s[yt.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:${Wd}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let l=0,u=null;for(;l<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${wt.ALPHA.GENERATE} with model: ${Wd}`);const e=await this.request.post({endpoint:wt.ALPHA.GENERATE,body:i,headers:s,stream:!0});if(!e)throw new Error("No response stream received");const t=He.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){u=e instanceof Error?e:new Error(String(e)),l++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${u.message}`),u;if(l>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),u;const n=1e3*Math.pow(2,l);dlog(`[CompactAgent] retrying API call (${l}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}throw u||new Error("Compact API call failed")}};async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!b(n))return null;const r=await R.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={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};if(e===St.ANTHROPIC){const e=await rn.getValidAccessToken();e&&(n[yt.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:vt,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},l=await buildAuthHeaders(),u=await r.post({endpoint:wt.ALPHA.GENERATE,body:i,headers:l,stream:!0}),d=He.fromReadableStream(u);let m="";d.on("text",e=>{m+=e}),await d.finalMessage(),m=m.trim(),m&&(await n.saveSessionTitle(m),dlog("Session",`Title generated: ${m}`))}_t(),Ot(),__name(getTasteContent,"getTasteContent"),xn(),_t(),ln(),Zt(),Nn(),Dn(),xn(),Ot(),__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle");var Vd=new Nd("ContextEngine"),Gd=200,Kd=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 Tl({baseUrl:n}),this.callbacks=e,this.sessionManager=new Cd(t),this.learningAgent=new zd({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new Hd({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new Tl({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,Vd.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),Vd.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=yu("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>Vd.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n,r){let o=e,s=[];try{const t=await processFileReferences(e);if(o=t.processedContent,s=t.fileReferences,s.length>0){const e=s.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(o=`${n}\n\n${o}`);const a=yu(r??e);t&&t.length>0&&(a.metadata={...a.metadata,images:t}),s&&s.length>0&&(a.metadata={...a.metadata,fileReferences:s}),this.callbacks.onFeedUpdate(a);const i=[];t&&t.length>0&&t.forEach(e=>{i.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),o.trim()&&i.push({type:"text",text:o});const l={role:"user",content:i},u=crypto.randomUUID(),d=this.createMessageWithMeta(l,{messageId:u});this.addMessageAndSync(d),this.checkpointManager.createSnapshot({messageId:u}).catch(e=>Vd.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,a).catch(e=>Vd.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const m=await this.processMessages();return this.triggerTitleGeneration(),m}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){Vd.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=Eu(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>Vd.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>Vd.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=yu(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>Vd.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=Eu(e);this.callbacks.onFeedUpdate(t)}const l=await this.executeToolBlocks({toolBlocks:s}),{toolResults:u,executedToolIds:d,permissionDenied:m}=l;if(m){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const g=[...u];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){g.push({type:"text",text:t});const e=yu(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:g})),this.sessionManager.saveMessages(this.messages).catch(e=>Vd.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&Vd.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){Vd.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return Vd.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.sanitizeMessagesForAPI(this.messages.map(e=>e.message))}sanitizeMessagesForAPI(e){const t=[];for(const n of e){if("user"===n.role&&Array.isArray(n.content)){const e=t.length>0?t[t.length-1]:null,r=new Set;if("assistant"===e?.role&&Array.isArray(e.content))for(const t of e.content)"tool_use"===t.type&&r.add(t.id);const o=n.content.filter(e=>"tool_result"!==e.type||r.has(e.tool_use_id));o.length>0&&t.push({...n,content:o});continue}const e=t.length>0?t[t.length-1]:null;if(e&&e.role===n.role){const t=Array.isArray(e.content)?e.content:[{type:"text",text:e.content}],r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];e.content=[...t,...r];continue}t.push({...n})}return t}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};Vd.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:_d}),{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=Ro.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:wt.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===St.ANTHROPIC&&(o=await rn.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};Vd.debug(`calling API (${s.model}, ${this.messages.length} msgs, ${t.length} tools)`);const i=await isTasteLearningEnabled(),l={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.TASTE_LEARNING]:i.toString(),[yt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(l[yt.OAUTH_TOKEN]=`Bearer ${o}`),{body:a,headers:l}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++){let r;try{const t=interceptStreamErrors({responseStream:await this.request.post({body:e.body,stream:!0,endpoint:wt.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const o=He.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:hr.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:hr.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:hr.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),l=Math.max(i,1e3),u=Math.min(l,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:u,signal:this.abortController?.signal})}}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){const{message:t}=this.extractErrorMessage(e),n=t?.toLowerCase()||"",r="Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")||this.requestInterrupted||this.abortController?.signal.aborted,o="Insufficient credits"===t||n.includes("insufficient credits"),s=e instanceof Mo||401===e?.status||e instanceof Fo||403===e?.status,a=e?.type||e?.error?.type,i="rate_limit_error"===a||429===e?.status||n.includes("rate limit"),l="overloaded_error"===a||529===e?.status||n.includes("overloaded");return r||o||s||i||l}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.error?.message){const n=parseEmbeddedErrorJSON(e.error.message);return n?{...n,status:n.status||t}:{status:t,type:e.error.type||null,message:e.error.message}}const n=e?.message;if("string"==typeof n){const e=parseEmbeddedErrorJSON(n);if(e)return{...e,status:e.status||t}}return{status:t,type:e?.type||null,message:e?.message||null}}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.requestInterrupted||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=this.extractErrorMessage(e),n=t.status,r=t.type,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 Fo||403===e?.status)return e;if(e instanceof Mo||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 l="";if(o)if(o.includes("Invalid 'Authorization' header"))l='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>Gd&&(t=t.substring(0,Gd)+"..."),l=`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"),u="rate_limit_error"===r||s.includes("rate limit");l+=a?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":u?'\n\nYou can wait a moment and try again, or type "continue" to retry.':'\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==i&&(l+=`\nRequest ID: ${i}`)}else if(e.toString){const t=e.toString();l=t.length>Gd?t.substring(0,Gd)+"...":t}else l="Error: Unknown error occurred";return new Error(l)}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=Vl.includes(s.name),i=Gl.includes(s.name)?this.getToolDescription(s):Promise.resolve(null);let l=null;try{a&&this.callbacks.onPermissionRequest&&(l=await i);const t=await this.checkToolPermission(s,l);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,l),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===l&&(l=await i),r.push({toolBlock:s,entryId:e,description:l})}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:l}=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,l))}}}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 Vd.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 Vl.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=Lu(e.name,e.input),r={..."edit_file"===e.name?e.input:{},permissionDenied:!0},o={...bu(e.name,n,r),id:t},s=xu(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=Lu(e.name,s),i={...bu(e.name,a,o),id:n,...r?{description:r}:{}},l=xu(i,t);this.callbacks.onFeedUpdate(l)}showToolError(e,t,n,r){const o=Lu(e.name,e.input),s="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,a={...bu(e.name,o,s),id:n,...r?{description:r}:{}},i=xu(a,Iu(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=Eu(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:o}=Hl({serverToolBlock:e,contentBlocks:n}),s=Lu(e.name,e.input),a=bu(e.name,s),i=xu(a,o?Iu(r):r);this.callbacks.onFeedUpdate(i)}if(t.trim()){const e=Eu(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:_d})}async checkAndCompactIfNeeded(){const e=Math.floor(_d*At.TIER_1_THRESHOLD),t=Math.floor(_d*At.TIER_2_THRESHOLD),n=Math.floor(_d*At.TIER_3_THRESHOLD);try{if(this.contextTokensUsed>n){Vd.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){Vd.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${At.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT);return Vd.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void this.emitAutoCompactInfo(e.tokensSaved)}if(this.contextTokensUsed>e){const t=this.countToolCalls(),n=At.TIER_1_KEEP_COUNT;if(t>n){Vd.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);Vd.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){Vd.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){e>0&&this.callbacks.onFeedUpdate(wu(`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:_d}),{toolsRemoved:s.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return Vd.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT);Vd.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});Vd.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),l=Math.max(0,s-a+i);this.contextTokensUsed=l,this.callbacks.onContextUsageUpdate?.({current:l,limit:_d}),Vd.debug(`Tier 3 summarization complete: reduced from ${s} to ~${l} tokens`)}catch(e){Vd.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(At.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=At.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const 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:_d})),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}}_t(),_t(),gr(),_t(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var Jd=["no job control","cannot set terminal process group"],Qd=null;function getShellInfo(){return Qd||(Qd=detectUserShell()),Qd}__name(getShellInfo,"getShellInfo");var Yd=__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(),l="bash"===i.type||"zsh"===i.type,u=l?i.path:"/bin/bash",d=I(u,l?["-i","-c",e]:["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let m="",g="",p=null;n>0&&(p=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),a({stdout:m,stderr:g+(g?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(m.length+n.length>cr){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void a({stdout:m,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}m+=n}catch(e){g+=`\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(g.length+t.length>lr)return void(g+="\n[Error output truncated: too large]");g+=t}catch(e){g+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{p&&clearTimeout(p);const n=l?g.split("\n").filter(e=>!Jd.some(t=>e.includes(t))).join("\n"):g;a({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{p&&clearTimeout(p),a({stdout:m,stderr:g+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),Zd=__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"),Xd=__name(()=>{const[e,t]=z({isExecuting:!1,currentCommand:null});return{executeBash:V(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Yd(e,{timeout:3e4,cwd:process.cwd()}),o=Zd(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]=xu(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]=xu(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");_t(),_t(),Ot();var em=class extends je{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 D.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 D.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await D.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 D.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 D.mkdir(n,{recursive:!0});try{const t=await D.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 D.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},tm=__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 em(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:V(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:V(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:V(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),a(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),a(!1)}},[t]),clearSessionPermissions:V(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:V(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:V((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:V(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting: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)}_t(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),_t();var nm=__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(f.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,o=""){if(E.existsSync(n))try{const s=E.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=E.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===T(process.cwd()).length}catch{return!1}}_t(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),cn(),_t(),Ot(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),_t(),__name(isDirectoryEmpty,"isDirectoryEmpty"),_t();var rm='You are an expert code reviewer. Do follow these steps:\n\nGather PR context using the GitHub CLI:\n1. When no PR number is given, list open PRs with `gh pr list` and ask which one to review\n2. Fetch PR metadata via `gh pr view <number>`\n3. Retrieve the changeset with `gh pr diff <number>`\n4. One go gather context: Run gh pr view <number> && echo "---DIFF---" && gh pr diff <number>\n5. Analyze the changes and provide a thorough code review that includes:\n\t- Overview of the PR is doing\n\t- Analysis of the code quality and style\n\t- Give specific suggestions for improvement\n\t- Highlight any potential bugs/issues or risks\n\t- Score PR on a scale of 1-5 based on overall table with quality and readiness for merging\nKeep your review concise, less wordy, but thorough.\nFocus on:\n- Correctness of code\n- Following project conventions\n- Performance issues and implications\n- Test coverage\n- Security considerations\n\nBe less wordy. If you make a table, don\'t go over 60pts.\nFormat your review in sections and bullets. Do NOT print hr rulers.\nDo NOT add separator lines or horizontal lines. "--------------------------------------------------------------------------------------------------------------------------------------\n -----------------"';function buildReviewPrompt({prNumber:e}){const t=e.trim();return t?`${rm}\n\nReview PR number: ${t}`:`${rm}\n\nReview PR number: `}async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new Tl({baseUrl:e});return await t.get({endpoint:wt.ALPHA.WHOAMI})}__name(buildReviewPrompt,"buildReviewPrompt"),_t(),Ot(),__name(getAuthenticatedEntity,"getAuthenticatedEntity"),Rn(),_t();var om=["Code","Code - Insiders","VSCodium","Cursor"],sm="Code",am={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},im=__name(e=>m(e).href,"formatPathForTerminal"),cm=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),lm=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),um=__name(({home:t,configSegments:n,variants:r})=>{for(const o of r){const r=lm({home:t,configSegments:n,variant:o});if(w.existsSync(e.dirname(r)))return o}return null},"findExistingVariant"),dm=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&mm(t.when)},"isTerminalShiftEnterBinding"),mm=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),gm=__name(e=>{const t=Ve(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),pm=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),hm=__name(({error:e,content:t})=>{const n=e.message;return pm(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"),fm=__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"),ym=__name(e=>{try{const t=Ve(e),n=fm(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:hm({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),wm=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:im(t)}),"createSuccessResult"),Em=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:im(t)}),"createErrorResult"),bm=__name(()=>{const t=h.homedir(),n=h.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=cm(n);if(!r)return lm({home:t,configSegments:[".config"],variant:sm});const o=um({home:t,configSegments:r,variants:om});return lm({home:t,configSegments:r,variant:o??sm})},"getVSCodeKeybindingsPath"),Sm=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)dm(n)&&(n.command===am.command&&n.args?.text===am.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),vm=__name(t=>{try{if(!w.existsSync(t)){const n=e.dirname(t);return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=w.readFileSync(t,"utf-8");if(gm(n))return{rawContent:n,keybindings:[]};const r=ym(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:Em({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):Em({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return Em({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),Cm=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(am,null,2);if(gm(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return Em({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?Em({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=bm();try{const t=vm(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=Sm(r);if(o.hasConflicting)return Em({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return wm({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=Cm({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(w.writeFileSync(e,s,"utf-8"),wm({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return Em({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"),_t(),Ot(),xn(),_t();var km={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return km[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Be(t);return e.join(f.homedir(),".commandcode","projects",n)}function getGlobalProjectSettingsPath(t=process.cwd()){return e.join(getGlobalProjectSettingsDir(t),"settings.json")}async function loadGlobalProjectSettings(e=process.cwd()){try{const t=getGlobalProjectSettingsPath(e),n=await R.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 R.mkdir(o,{recursive:!0}),await R.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),Bd.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 R.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"),_t(),xn(),Ot(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),_t(),xn();var Pm=e.join(h.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=x(e,{encoding:"utf8"}),n=Ge.createInterface({input:t,crlfDelay:1/0});for await(const e of n)if(e.trim()){try{const r=JSON.parse(e);if("session_meta"===r.type&&r.payload?.cwd)return n.close(),t.destroy(),{cwd:r.payload.cwd,id:r.payload.id,timestamp:r.payload.timestamp}}catch{}break}return n.close(),t.destroy(),null}catch{return null}}async function findAllSessionFiles(t,n){const r=[];try{await R.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const o=await R.readdir(t);for(const s of o){if(!/^\d{4}$/.test(s))continue;const o=e.join(t,s);if(!(await R.stat(o)).isDirectory())continue;const a=await R.readdir(o);for(const t of a){if(!/^\d{2}$/.test(t))continue;const a=e.join(o,t);if(!(await R.stat(a)).isDirectory())continue;const i=await R.readdir(a);for(const o of i){if(!/^\d{2}$/.test(o))continue;const i=e.join(a,o);if(!(await R.stat(i)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${s}/${t}/${o}`});const l=(await R.readdir(i)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(i,t));r.push(...l)}}}}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(Pm,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 l=await processFilesInBatches(a,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===o)try{const r=await R.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(...l);const u=r>0?s.slice(0,r):s;return dlog(`[Codex] matched ${u.length} sessions for project`),n?.({phase:"complete",totalFiles:a.length,processedFiles:a.length,matchedSessions:u.length}),u.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await R.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 R.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(h.homedir(),".claude","projects");await R.access(t);const o=getProjectDirName(process.cwd()),s=(await R.readdir(t)).filter(e=>e===o);for(const o of s){const s=e.join(t,o);if((await R.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"),_t(),Ot(),_t();var Tm="# Taste (Continuously Learned by CommandCode.ai)",Am=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return Am.test(t)?t.replace(Am,`$1${Tm}`):t}__name(migrateHeader,"migrateHeader");var xm=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await R.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await R.access(r);const e=await R.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await R.writeFile(r,t,"utf-8")}catch{await R.writeFile(r,Tm+"\n\n")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await R.access(n),!0}catch{return!1}}};Nn(),Dn(),sn(),_t(),_t(),Ot(),_t(),_t(),Ot();var Im=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),_m=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Nm=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=z("idle"),[a,i]=z(""),l=[...Od.map(e=>e.name),...Ld.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void i("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?Im():_m();await D.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),a=Array.from(e.selectedTools).map(e=>Ud[e]||e).join(", "),i=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(a),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${i}\n---\n\n${e.sysPrompt}\n`;await D.writeFile(s,u,"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");X((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||u()});const d=Array.from(e.selectedTools).map(e=>Ud[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return q.createElement(K,{flexDirection:"column",gap:1},q.createElement(K,{flexDirection:"column"},q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"Name:"),q.createElement(J,{color:"gray"},e.agentType)),q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"Location:"),q.createElement(J,{color:"gray"},m)),q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"Tools:"),q.createElement(J,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"Description"),q.createElement(J,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),q.createElement(J,{color:"gray"},e.ccToolDefinition),q.createElement(K,{gap:1},q.createElement(J,{color:"white",bold:!0},"System Prompt:")),q.createElement(J,{color:"gray"},e.sysPrompt),!r&&q.createElement(K,{marginTop:1},"idle"===o&&q.createElement(K,{gap:1},q.createElement(J,{color:"green",dimColor:!0},"Press"),q.createElement(J,{color:"green",bold:!0},"Enter"),q.createElement(J,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===o&&q.createElement(J,{color:"yellow"},"Saving agent..."),"saved"===o&&q.createElement(J,{color:"green"},"✓ ",a),"error"===o&&q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"red"},"✗ Error: ",a),q.createElement(J,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),$m=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=z("menu"),a=[...Od.map(e=>e.name),...Ld.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=>jd[e]||e);i=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i},u=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(X((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return q.createElement(K,{flexDirection:"column"},q.createElement(Nm,{config:l,onSaveComplete:()=>s("menu"),viewOnly:!0}),q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray"},"Press Enter to go back")));if("edit"===o)return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"yellow"},"Edit functionality coming soon..."),q.createElement(J,{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 D.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return q.createElement(K,{flexDirection:"column",gap:1},q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"red"},"Delete agent"),q.createElement(J,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),q.createElement(K,null,q.createElement(Ke,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"},` ${t}`)})))}return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"white",bold:!0},e.name),q.createElement(K,{marginTop:1},q.createElement(Ke,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"},` ${t}`)})),q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Rm=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=z([]),[s,a]=z([]),[i,l]=z([]),[u,d]=z(!0),[m,g]=z(!1),[p,h]=z(null),[y,w]=z(!1),E=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),b=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),S=__name(async(e,n)=>{try{g(!1);const r=(await D.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await D.readFile(o,"utf-8"),{data:a,content:i}=Ue(s);let l=a.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:a.name||r.replace(".md",""),description:a.description||"",tools:l,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(E(),"personal"),S(b(),"project")]),n=Sd.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),l(n),d(!1)},"loadAgents")()},[m]);const v=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{v.push({label:e.name,value:e.filePath})}),s.forEach(e=>{v.push({label:e.name,value:e.filePath})});const C=r.length+s.length,k=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(h(e),w(!0))}},"handleAgentSelect");if(u)return q.createElement(J,{color:"gray"},"Loading agents...");if(y&&p){const e=p.filePath.startsWith("__builtin__:");return q.createElement($m,{agent:p,onBack:()=>{w(!1),h(null)},setRevalidateAgent:g,isReadOnly:e})}const P=__name(({isSelected:e,label:t})=>{const n=v.find(e=>e.label===t),o=n?.value||"",a=r[0]?.filePath===o,i=s[0]?.filePath===o;return q.createElement(K,{flexDirection:"column"},a&&r.length>0&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray",bold:!0},"User agents")),i&&s.length>0&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray",bold:!0},"Project agents")),q.createElement(K,null,q.createElement(J,{color:"white"},e?">":" "),q.createElement(J,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return q.createElement(K,{flexDirection:"column"},q.createElement(K,{marginBottom:1},q.createElement(J,{color:"white",bold:!0},"Agents"),C>0?q.createElement(J,{color:"gray"}," ","(",C," agent",C>1?"s":"",")"):q.createElement(J,{color:"gray"}," (No custom agents)")),n&&q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{color:"green",dimColor:!0},"Created agent: ",n)),q.createElement(Ke,{items:v,onSelect:k,indicatorComponent:()=>null,itemComponent:P}),i.length>0&&q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(J,{color:"gray",bold:!0},"Default agents"),i.map(e=>q.createElement(J,{key:e.filePath,color:"gray"}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(J,{color:"gray"},"Create specialized subagents that Command Code can delegate to."),q.createElement(J,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");_t(),Ot(),_t(),_t(),Ot();var Dm=__name(({onSelect:e})=>q.createElement(Ke,{items:[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>q.createElement(J,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector");_t(),En(),Ot(),Tn(),dn();var Om=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=z(!1),[g,p]=z(!1),h=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),f=V(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){p(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(p(!0),t.isPasteEnd){p(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[g,a]);return"agentType"===e?q.createElement(q.Fragment,null,q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(Ud).some(e=>Be(e)===Be(t))||Object.keys(Ud).some(e=>Be(e)===Be(t)))&&q.createElement(J,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Be(t))&&q.createElement(J,{color:"red"},"⚠ This name is reserved. Reserved names:"," ",bd.join(", "))),q.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Be(t);Object.values(Ud).some(t=>Be(t)===e)||Object.keys(Ud).some(t=>Be(t)===e)||isReservedAgentName(e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?q.createElement(q.Fragment,null,q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"white"},"Enter the system prompt for your agent:"),q.createElement(J,{color:"gray"},"Be comprehensive for best results.")),q.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:h,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?q.createElement(q.Fragment,null,q.createElement(J,{color:"white"},"When should ","Command Code"," use this agent?"),q.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:f,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");_t();var Lm=__name(({onSelect:e})=>q.createElement(Ke,{items:[{label:"1. Generate with Command Code (recommended)",value:"recommended"},{label:"2. Manual configuration",value:"manual"}],onSelect:t=>{"recommended"!==t.value&&"manual"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>q.createElement(J,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector");_t(),En(),_t();var Mm=["·","○","◇","☆","✧","☆","◇","○","⌘"],Fm=[8,5,4,4,4,4,4,5,20],Um=[5,4,4,4,4,4,5],jm=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Fm.length;e++)if(n+=Fm[e],t<n)return Mm[e];const r=t-58;n=0;for(let e=0;e<Um.length;e++)if(n+=Um[e],r<n)return Mm[7-e];return Mm[0]},"getWaveSymbol"),Bm=["#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<Bm.length?Bm[n]:"#B799E6"},"getCharColor");return q.createElement(J,null,e.split("").map((e,t)=>q.createElement(J,{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)},[]),q.createElement(J,{color:"#E4CCFF",bold:!0},jm(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var qm=__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 q.createElement(K,{width:s,height:1,paddingLeft:0,marginLeft:0},q.createElement(CMDIcon,null),q.createElement(K,{marginRight:1},q.createElement(ShimmerText,{text:e})),a?q.createElement(q.Fragment,null,q.createElement(K,{columnGap:1},q.createElement(J,{dimColor:!0},`(${formatTime3(t)}`),q.createElement(J,{dimColor:!0},"•"),q.createElement(J,{color:"gray"},Se.arrowDown),q.createElement(J,{dimColor:!0},`${formatToken(Math.round(r))}`),q.createElement(J,{dimColor:!0},"•"),q.createElement(K,{columnGap:1},q.createElement(J,{bold:!0,color:"gray"},"esc"),q.createElement(J,{dimColor:!0},"to interrupt)")))):i?q.createElement(K,{columnGap:1},q.createElement(J,{dimColor:!0},`(${formatToken(Math.round(r))})`)):q.createElement(q.Fragment,null))},"Status");dn(),Tn();var zm=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,a]=z(!1),[i,l]=z(0),u=V(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?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(a(!0),n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[s,t]);return q.createElement(K,{flexDirection:"column"},r?q.createElement(K,null,q.createElement(CMDIcon,null),q.createElement(J,{color:"white"},"Generating agent from description...")):q.createElement(TextInput,{key:i,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:u,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"red"},`${ve.warning} ${o}`)))},"RecommendedFlow");_t();var Wm=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=z(!1),[a,i]=z(0),l=G(()=>[...Od.map(e=>e.name),...Ld.map(e=>e.name)],[]),u=G(()=>[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[l]),d=G(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),l.forEach(t=>{e.push({type:"tool",value:t})})):(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,u,e,l]),m=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=u.find(e=>e.name===t.value),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]":"[ ]"} ${Ud[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),g=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return X((e,l)=>{if(l.upArrow)i(e=>{const t=e-1;return t<0?g.length-1:t});else if(l.downArrow)i(e=>{const t=e+1;return t>=g.length?0:t});else if(l.return||" "===e){const e=g[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)}}}),q.createElement(K,{flexDirection:"column"},m.map((e,t)=>{const n=g.findIndex(t=>t.value===e.value),r=-1!==n&&n===a;if("divider"===e.type)return q.createElement(K,{key:`divider-${t}`},q.createElement(J,{color:"gray"}," ",e.label));if("spacer"===e.type)return q.createElement(K,{key:`spacer-${t}`,height:1});if("label"===e.type)return q.createElement(K,{key:`label-${t}`},q.createElement(J,{color:"gray"}," ",e.label));const o="continue"===e.type;return q.createElement(K,{key:`item-${t}`},q.createElement(J,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),q.createElement(K,{marginTop:1},e.size===l.length&&q.createElement(J,{color:"gray"},"All tools selected"),e.size>0&&e.size<l.length&&q.createElement(J,{color:"gray"},e.size," tools selected"),0===e.size&&q.createElement(J,{color:"gray"},"No tools selected")))},"ToolsSelector");Dn(),ln(),cn(),Nn();var Hm=__name(({onComplete:e})=>{const[t,n]=z("location"),[r,o]=z(!1),[s,a]=z(null),[i,l]=z("agentType"),u=G(()=>[...Od.map(e=>e.name),...Ld.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=z(d()),p=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),h=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===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"),f=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),y=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),w=__name(async()=>{try{a(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===St.ANTHROPIC&&(r=await rn.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const s={[yt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(s[yt.OAUTH_TOKEN]=`Bearer ${r}`);const i=getApiBaseUrl(),l=new Tl({baseUrl:i}),u=await l.post({headers:s,endpoint:wt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});g({...m,agentType:Be(u.agentName),sysPrompt:u.systemPrompt,ccToolDefinition:u.toolDescription}),n("tools")}catch(e){e instanceof Lo&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?a(en):a("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:Be(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),b=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),S=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),v=__name(()=>{n("summary")},"handleToolsComplete"),C=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),k=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),g({...m,selectedTools:n})},"handleToggleCategory");return q.createElement(K,{flexDirection:"column",gap:1},q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"white",bold:!0},"Create new agent"),q.createElement(J,{color:"gray"},h())),q.createElement(K,null,"location"===t&&q.createElement(Dm,{onSelect:f}),"method"===t&&q.createElement(Lm,{onSelect:y}),"configuration"===t&&"recommended"===m.method&&q.createElement(zm,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:w}),"configuration"===t&&"manual"===m.method&&q.createElement(K,{flexDirection:"column",gap:1},q.createElement(Om,{step:i,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>g({...m,agentType:e}),onSysPromptChange:e=>g({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>g({...m,ccToolDefinition:e}),onAgentTypeSubmit:E,onSysPromptSubmit:b,onCCToolDefinitionSubmit:S})),"tools"===t&&q.createElement(Wm,{selectedTools:m.selectedTools,onToggleTool:C,onToggleCategory:k,onComplete:v}),"summary"===t&&q.createElement(Nm,{config:m,onSaveComplete:p})))},"AgentNew"),Vm=__name(({onCancel:e})=>{const[t,n]=z(null),[r,o]=z(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return X((t,n)=>{n.escape&&e()}),q.createElement(K,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"single",flexDirection:"column"},null===t&&q.createElement(Rm,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&q.createElement(Hm,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");_t(),Ot(),Rn(),gr();var Gm=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.MCP="/mcp",e.COMPACT="/compact",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.FEEDBACK="/feedback",e.TERMINAL_SETUP="/terminal-setup",e.IDE_SETUP="/ide",e.ADD_DIR="/add-dir",e.REVIEW="/review",e))(Gm||{}),Km=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/provider","/model","/memory","/init","/agents","/mcp","/compact","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir"]),Jm=[{command:"/add-dir",description:"Add directory to workspace context"},{command:"/agents",description:"Manage agent configurations"},{command:"/clear",description:"Clear the conversation history (reset, new)"},{command:"/compact",description:"Compact the conversation history"},{command:"/exit",description:"Exit Command Code"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/help",description:"Show available shortcuts"},{command:"/ide",description:"Install extension to fetch IDE context"},{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/memory",description:"Manage Command Code memory"},{command:"/model",description:"Switch between Command Code models"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/resume",description:"Resume a past conversation"},{command:"/review",description:"Review a pull request (optional PR number)"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/unshare",description:"Stop sharing conversation"}],Qm=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[o,s]=z(0),[a,i]=z(0),{stdout:l}=Z(),u=l?.columns??80,d=Math.max(20,u-22-2-1-2),m=G(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...Jm.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!r)return e;const t=r.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let 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)},[r]),g=G(()=>{const e=a,t=Math.min(e+8,m.length);return m.slice(e,t)},[m,a]);return H(()=>{s(0),i(0)},[r]),X((r,l)=>{if(l.escape)n();else if(l.upArrow)s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t});else if(l.downArrow)s(e=>{const t=Math.min(m.length-1,e+1);return t>=a+8&&i(Math.max(0,t-8+1)),t});else{if(l.return){const t=m[o];return void(t&&e(t.command))}if(l.tab||l.rightArrow){const e=m[o];return void(e&&t(e.command))}}}),0===m.length?q.createElement(K,{flexDirection:"column",paddingLeft:2},q.createElement(J,{color:"dim"},"No commands found")):(m.length,q.createElement(K,{flexDirection:"column",paddingLeft:1},q.createElement(K,{columnGap:2},q.createElement(K,{flexDirection:"column",width:22},g.map((e,t)=>{const n=a+t;return q.createElement(J,{key:n,color:o===n?"white":"dim",wrap:"truncate"},e.command)})),q.createElement(K,{flexDirection:"column"},g.map((e,t)=>{const n=a+t;return q.createElement(J,{key:n,color:o===n?"white":"dim",wrap:"truncate"},truncateString({text:e.description,maxChars:d}))})))))},"CommandMenu");_t(),_t(),gr();var Ym=__name(({messages:e})=>0===e.length?null:q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(K,{marginBottom:0},q.createElement(J,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>q.createElement(K,{key:t},q.createElement(J,{dimColor:!0},ve.pointerSmall," "),q.createElement(J,{dimColor:!0},truncateString({text:e,maxChars:80}))))),"QueuedMessages");_t(),En(),Ot(),Tn(),sn(),_t();var Zm=n(y(),"commandcode-images"),Xm={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{b(Zm)||k(Zm,{recursive:!0});const r=Xm[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(Zm,o),a=Buffer.from(e.data,"base64");return P(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=V((e,t)=>{o(t=>[...t,e]),r(t),a()},[o,r,a]),l=W(!1),u=W(""),d=W(null),m=W(""),g=V(async(e,t)=>{let o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectDroppedImageFile(o);if(l)return void i(l,t);const u=await detectClipboardImage();if(u)return void i(u,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]),p=V(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(l.current){const e=u.current,t=m.current;u.current="",m.current="",l.current=!1,d.current=null,e&&await g(e,t)}},500)},[g]);return{handlePaste:V(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return l.current&&(l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)),await g(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!l.current)return l.current=!0,m.current=n.textBeforePaste??t,u.current=n.pastedContent??n.cleanedContent,p(),!0;if(l.current&&!n.isPasteEnd)return void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current)),p(),!0;if(l.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current));const e=u.current,t=m.current;return u.current="",m.current="",l.current=!1,await g(e,t),!0}if(n.isPasteEnd&&!n.isPasteStart&&!l.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return i(e,t),!0}return!1},[t,g,p,i]),resetPasteState:V(()=>{l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:V(()=>l.current,[])}}__name(saveTempImage,"saveTempImage"),Dn(),_t(),dn(),Tn(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),_t(),_t();var eg=["code --wait","cursor --wait","nano"],tg=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return tg.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 _(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of eg)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var ng=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 ng;t=ensureWaitFlag(t);const r=n(y(),`commandcode-${Date.now()}.md`);return await L(r,e),new Promise((e,n)=>{const o=t.split(" ").filter(e=>e.length>0),s=o[0],a=o.slice(1),i=I(s,[...a,r],{stdio:"inherit"});i.on("close",async()=>{try{const t=await M(r,"utf-8");await F(r),e(t.trimEnd())}catch(e){n(e)}}),i.on("error",async e=>{try{await F(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[o,s]=z(!1),[a,i]=z(null),l=V(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 ng?"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]),u=V(()=>{i(null)},[]);return{isEditorOpen:o,editorError:a,handleOpenInEditor:l,clearEditorError:u}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/reference/interactive#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),_t(),_t(),_t(),_t(),Ot(),xn(),On(),Wn(),_t(),Ot();var rg=t.join(f.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(rg);E.existsSync(e)||E.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!E.existsSync(rg))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=E.readFileSync(rg,"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(),E.writeFileSync(rg,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"),On();var og=we(N),sg=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=_("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return sg.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(Je.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Je.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Je.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 og(`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(!Je.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=De(`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 _("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 ag=new Set(["OPEN","MERGED","CLOSED"]),ig=null;function getCachedPRInfo(e){if(ig&&ig.branch===e){if(!(Date.now()-ig.timestamp>3e5))return ig.result;ig=null}}function setPRCache(e,t){ig={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((o,s)=>{$(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&&ag.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 cg=__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"),lg=__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,cg().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=Qe(),r=n(e,".gitignore");if(b(r))try{const e=S(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}_t(),__name(loadGitignore,"loadGitignore");var ug=__name(({onSelectFile:e,onClose:t,searchQuery:s=""})=>{const[i,l]=z(process.cwd()),[u,d]=z([]),[m,g]=z(0),[p,h]=z(0),f=s.trim()?15:10,y=V((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const s=n(t,e);try{const e=T(s),a=[];return e.forEach(e=>{const i=n(s,e);try{const e=A(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=T(i),s=[],l=a.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!a||u.includes(l)){const a=n(i,e);try{const e=A(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,l=0)=>{if(!(l>8))try{T(e).forEach(u=>{const d=n(e,u);try{const e=A(d),n=o(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(a)||m.includes(a))&&s.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==u&&i(d,l+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()||"",l=r.split("/").pop()||"",u=i.includes(a),d=l.includes(a);if(u&&!d)return-1;if(!u&&d)return 1;const m=e.name.split("/").length,g=t.name.split("/").length;return m!==g?m-g:e.name.localeCompare(t.name)}),s.slice(0,50)},[]),w=V(e=>{try{const t=T(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=A(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),g(0),h(0)}catch{}},[]);H(()=>{if(s.trim()){const e=y(s);d(e),g(0),h(0)}else w(i)},[i,w,s,y]),X((n,r)=>{if(r.escape)t();else if(r.upArrow)g(e=>{const t=Math.max(0,e-1);return t<p&&h(t),t});else if(r.downArrow)g(e=>{const t=Math.min(u.length-1,e+1);return t>=p+f&&h(t-f+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!s.trim()&&l(a(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const E=u.slice(p,p+f);return q.createElement(K,{flexDirection:"column",paddingLeft:1},q.createElement(K,{marginBottom:1,flexDirection:"column"},q.createElement(J,{color:"dim"},s.trim()?`Searching for: "${s}"`:`Files: ${i}`),q.createElement(J,{color:"dim"},s.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===E.length?q.createElement(J,{color:"dim"},s.trim()?`No files found matching "${s}"`:"No files found in this directory"):E.map((e,t)=>{const n=p+t,r=e.name,o=n===m;return q.createElement(J,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList");_t(),Ot(),Rn(),_t();var dg=__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 q.createElement(K,{paddingRight:1},q.createElement(J,{color:r(t)},o))},"ContextUsage");_t(),gr();var mg=__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 Bd.on("new-event",e),()=>{Bd.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const a=9+e.length+9>sr;let i=e;return i=truncateString(a?{text:e,maxChars:sr}:{text:e,maxChars:sr-9-9}),q.createElement(K,null,!a&&q.createElement(J,{color:"green"},"● taste: "),q.createElement(J,null,i),!a&&q.createElement(J,{dimColor:!0}," (ctrl+t)"))},"LearningFeedMini");_t();var gg=__name(({mode:e,pendingExitKey:t})=>t?q.createElement(J,{dimColor:!0},"Press Ctrl+C again to exit"):"auto-accept"===e?q.createElement(K,{flexDirection:"row"},q.createElement(J,{color:"#E4CCFF"},"» accept edits on "),q.createElement(J,{dimColor:!0},"(shift+tab)")):"plan"===e?q.createElement(K,{flexDirection:"row"},q.createElement(J,{color:"#FFB86C"},"plan mode "),q.createElement(J,{dimColor:!0},"(shift+tab)")):q.createElement(J,{color:"dim"},"? for shortcuts"),"ModeIndicator");_t(),_t();var pg=__name(({url:e,text:t,dimColor:n=!1,color:r})=>{const o=`]8;;${e}${t}]8;;`;return q.createElement(J,{dimColor:n,color:r},o)},"TerminalLink"),hg=__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 q.createElement(q.Fragment,null,t&&q.createElement(J,{dimColor:!0}," · "),q.createElement(J,{color:n},"PR "),q.createElement(pg,{url:e.url,text:`#${e.number}`,dimColor:!0}))},"PRLinkBadge"),fg=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?q.createElement(q.Fragment,null,t&&q.createElement(J,{dimColor:!0}," · "),q.createElement(J,{color:"connected"===e.type?"green":"yellow"},e.message)):null,"ConnectionIndicatorBadge"),yg=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:a,connectionIndicator:i,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:p,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w})=>{const E=e>=60;return q.createElement(q.Fragment,null,q.createElement(K,{flexDirection:"column",paddingLeft:1},"auto-accept"!==r&&"plan"!==r||l?q.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},q.createElement(K,{flexDirection:"row",columnGap:0},n&&!l?q.createElement(J,{color:"#5FAFAF"},t):q.createElement(gg,{mode:r,pendingExitKey:l}),!l&&q.createElement(hg,{prInfo:o}),!l&&q.createElement(fg,{indicator:i})),E&&q.createElement(K,{flexDirection:"column",alignItems:"flex-end"},s&&q.createElement(mg,null),a&&q.createElement(dg,{usage:a}))):q.createElement(q.Fragment,null,q.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},q.createElement(gg,{mode:r}),E&&s&&q.createElement(mg,null)),q.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},q.createElement(K,{flexDirection:"row",columnGap:0},q.createElement(J,{color:n?"#5FAFAF":void 0,dimColor:!n},t),q.createElement(hg,{prInfo:o}),q.createElement(fg,{indicator:i})),E&&a&&q.createElement(dg,{usage:a}))),(u||d||g&&m)&&q.createElement(K,{flexDirection:"row",columnGap:1},u&&q.createElement(J,null,ve.tick," ","Command Code"," updated:"," ",q.createElement(J,{dimColor:!0},"v",u.updatedFrom),q.createElement(J,{dimColor:!0}," ",ve.arrowRight," "),q.createElement(J,null,"v",u.updatedTo)),!u&&d&&q.createElement(J,{color:"yellow",dimColor:!0},ve.info," Update available:"," ",d.currentVersion," ",ve.arrowRight," ",d.latestVersion),g&&m&&q.createElement(J,{color:"green",dimColor:!0},ve.bullet," Provider:"," ",getProviderDisplayName(m)))),p&&q.createElement(K,{paddingLeft:1},q.createElement(J,{color:"green"},"! for bash mode")),f&&h&&q.createElement(K,{paddingLeft:1},q.createElement(J,{color:"#E4CCFF"},"SHARED: ",h.url," (copied to clipboard)")),y&&q.createElement(K,{paddingLeft:1},q.createElement(J,{color:y.includes("NOT SHARED")?"red":"#E4CCFF"},y)),w&&q.createElement(K,{paddingLeft:1},q.createElement(J,{color:"#E4CCFF"},w)))},"BottomIndicator");_t(),gr();var wg=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=z([]),[o,s]=z(0),[a,i]=z(!0);H(()=>{l()},[]);const l=__name(async()=>{i(!0);const e=await Cd.listSessions();r(e.slice(0,30)),i(!1)},"loadSessions");if(X((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 q.createElement(K,{flexDirection:"column",paddingLeft:2},q.createElement(J,{color:"gray"},"Loading sessions..."));if(0===n.length)return q.createElement(K,{flexDirection:"column",paddingLeft:2},q.createElement(J,{color:"gray"},"No previous sessions found"),q.createElement(J,{color:"dim",dimColor:!0},"Press ESC to go back"));const u=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),d=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),m=__name(e=>truncateString({text:d(e),maxChars:or}),"truncateMessage"),g=__name(e=>e.title?d(e.title):m(e.firstMessage),"getSessionSummary");return q.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},q.createElement(J,{color:"cyan",bold:!0},"Resume Session"),q.createElement(J,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),q.createElement(K,{marginTop:1}),q.createElement(K,{columnGap:2,marginBottom:1},q.createElement(K,{width:5},q.createElement(J,{color:"gray"}," ")),q.createElement(K,{width:13},q.createElement(J,{color:"gray"},"Modified")),q.createElement(K,{width:20},q.createElement(J,{color:"gray"},"Git Branch")),q.createElement(K,{width:11},q.createElement(J,{color:"gray"},"# Messages")),q.createElement(K,null,q.createElement(J,{color:"gray"},"Summary"))),q.createElement(K,{columnGap:2},q.createElement(K,{flexDirection:"column",width:5},n.map((e,t)=>q.createElement(J,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${ve.pointer} ${t+1}.`:` ${t+1}.`))),q.createElement(K,{flexDirection:"column",width:13},n.map((e,t)=>q.createElement(J,{key:`mod-${e.id}`,color:o===t?"white":"gray"},u(e.lastModified)))),q.createElement(K,{flexDirection:"column",width:20},n.map((e,t)=>q.createElement(J,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),q.createElement(K,{flexDirection:"column",width:11},n.map((e,t)=>q.createElement(J,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),q.createElement(K,{flexDirection:"column"},n.map((e,t)=>q.createElement(J,{key:`summary-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},g(e))))))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],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 q.createElement(J,null,r?" ":"",t?q.createElement(J,{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 q.createElement(K,{flexDirection:"column",width:"100%",alignItems:"flex-end"},i.map((e,r)=>q.createElement(K,{key:r,flexDirection:"row"},q.createElement(K,{flexShrink:0,marginRight:1},0===r&&q.createElement(J,{color:"dim"},s)),q.createElement(K,{flexDirection:"row"},e.map((e,r)=>q.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}_t(),_t(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),_t(),__name(createOSC8Link,"createOSC8Link"),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),_t(),Wr();var Eg=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=z(null),[s,a]=z(!1),i=W(!1),l=W(null),[u,d]=z(!1),[m,g]=z("connected"),p=W(null),h=W(null),f=V((e,t)=>{h.current&&(clearTimeout(h.current),h.current=null),g(e),d(!0),void 0!==t&&(h.current=setTimeout(()=>{d(!1)},t))},[]),y=V(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),w=V(async(e=!1)=>{if(!i.current){i.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new Ur,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=p.current;if(null===r?n&&f("connected",3e3):r!==n&&(n?f("connected",2e3):f("disconnected",5e3)),p.current=n,a(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),o(r)}else o(null)}catch{!0===p.current&&f("disconnected",5e3),p.current=!1,a(!1),o(null),l.current?.disconnect(),l.current=null}finally{i.current=!1}}},[f]);return H(()=>{if(!t||n)return;w(!0);const e=setInterval(()=>w(!1),500);return()=>{clearInterval(e),y(),l.current?.disconnect(),l.current=null}},[t,n,w,y]),{context:r,connected:s,refresh:w,connectionIndicator:{visible:u,message:"connected"===m?"IDE ✓":"IDE disconnected",type:m}}},"useVSCodeContext");_t();var bg=__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");_t();var Sg=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),vg=__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"),Cg=["\n","\r","[13;2u","[27;2;13~","[27;2;13~","[13;2u"],kg=["","[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)||Cg.includes(t))}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isNewlineShortcutKey,"isNewlineShortcutKey"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var Pg=__name(()=>q.createElement(K,{flexDirection:"column",paddingLeft:1},q.createElement(J,{color:"dim",bold:!0},"Available Shortcuts:"),q.createElement(K,{columnGap:4},q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"dim"},"! for bash mode"),q.createElement(J,{color:"dim"},"/ for commands"),q.createElement(J,{color:"dim"},"@ for file paths"),q.createElement(J,{color:"dim"},"shift + tab to toggle auto-accept")),q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"dim"},"double tap esc to clear input"),q.createElement(J,{color:"dim"},"ctrl + j / shift + ⏎ for newline"),q.createElement(J,{color:"dim"},"ctrl + g to open in editor"),q.createElement(J,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Tg=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:s="Enter your input…",showFileList:a,setShowFileList:i,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:g=!1,tasteUsage:p=!1,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w,updateStatus:E,updateFailedInfo:b,currentProvider:S,showProviderInfo:v,permissionMode:C="standard",onToggleAutoAccept:k,hintMessage:P,historyManager:T,pendingExitKey:A=null,onOverlayVisibilityChange:x,onDoubleEscapeEmpty:I,onAltP:_,isProcessing:N=!1,ideContextEnabled:$=!0})=>{const[R,D]=z(0),[O,L]=z(!1),[M,F]=z(!1),[U,j]=z(!1),[B,Q]=z(!1),[Y,ee]=z(""),[te,ne]=z(!1),re=W(0),oe=W(0),[se,ae]=z([]),[ie,ce]=z([]),[le,ue]=z(-1),[de,me]=z(""),ge=W(!1),pe=W(!1),[he,fe]=z(-1),[ye,we]=z(""),Ee=W(0),{isEditorOpen:be,editorError:Se,handleOpenInEditor:Ce,clearEditorError:ke}=useExternalEditor({input:e,setInput:n,setInputKey:D,onEditorClose:__name(()=>{ge.current=!1},"onEditorClose")}),{handlePaste:Pe,resetPasteState:Te,isPasting:Ae}=useBracketedPaste({input:e,detectedContent:se,setInput:n,setDetectedImages:ce,setDetectedContent:ae,incrementInputKey:__name(()=>D(e=>e+1),"incrementInputKey")}),{context:xe,connected:Ie,refresh:_e,connectionIndicator:Ne}=Eg({enabled:$,paused:N}),{stdout:$e}=Z(),Re=$e?.columns??80,{pr:De}=lg();H(()=>{const e=a||B||te;x?.(e)},[a,B,te,x]);const Oe=V(()=>{ce([]),ue(-1)},[]),Le=V(()=>{n(""),F(!1),Q(!1),ee(""),ne(!1),ae([]),Oe(),me(""),Te(),fe(-1),we(""),D(e=>e+1)},[n,Te,Oe]),Me=V(()=>{ge.current=!0,n(e+"\n"),D(e=>e+1),setTimeout(()=>{ge.current=!1},0)},[e,n]);X(async(t,r)=>{if(-1!==le&&r.leftArrow)return void ue(prevImageIndex({currentIndex:le,imageCount:ie.length}));if(-1!==le&&r.rightArrow)return void ue(nextImageIndex({currentIndex:le,imageCount:ie.length}));if(r.upArrow){if(a||B||te)return;const t=e.indexOf("\n"),r=-1===t||Ee.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ie.length,selectedImageIndex:le,historyIndex:he}))return void ue(ie.length-1);if(-1!==le&&ue(-1),0!==e.length&&-1===he&&!r)return;const o=T?.count()??0;if(0===o)return;-1===he&&we(e);const s=Math.min(he+1,o-1);return void(s!==he&&(fe(s),n(T?.getAt(s)||""),D(e=>e+1)))}if(r.downArrow){if(a||B||te)return;if(-1===he)return;const t=e.lastIndexOf("\n");if(!(-1===t||Ee.current>t))return;const r=he-1;return fe(r),n(-1===r?ye:T?.getAt(r)||""),void D(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Oe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return ge.current=!0,void Ce();if(getIsExpandToolShortcut(r,t))return ge.current=!0,n(e),D(e=>e+1),void setTimeout(()=>{ge.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ae()}))return pe.current=!0,Me(),void setTimeout(()=>{pe.current=!1},0);if(r.meta&&r.backspace)return void Le();if(r.meta&&"w"===t)return ge.current=!0,void Le();const o=r.ctrl&&"v"===t||kg.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();return r&&(ce(e=>[...e,r]),n(t),D(e=>e+1)),void(ge.current=!0)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return j(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==le&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ie,index:le});return ce([...e]),void ue(t)}if(r.escape){if(-1!==le)return void ue(-1);if(B)return;if(te)return ne(!1),n(de),void D(e=>e+1);const t=Date.now();return t-re.current<500?(e.length>0?Le():I?.(),re.current=0,oe.current=0):(re.current=t,O||M||(oe.current=t)),L(!1),void F(!1)}O&&(r.backspace||r.delete)&&0===e.length&&L(!1)}});const Fe=V(async t=>{if(be)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void _?.();if(await Pe(t))return;if(ge.current)return void(ge.current=!1);-1!==he&&fe(-1);const o=1===t.length,s=t.slice(-1);if(o){if("?"===s&&!O)return L(!0),n(""),void D(e=>e+1);if("!"===s&&!M)return L(!1),F(!0),n(""),void D(e=>e+1)}if("/"!==s||B||"/"!==t||(Q(!0),ee("")),B&&!t.startsWith("/")&&(Q(!1),ee("")),B&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(Q(!1),ee("")):ee(e)}"@"!==s||a||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(i(!0),u(""));const l=t.lastIndexOf("@");if(t.length<e.length&&-1!==l&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(l+1),n=!e.includes(" "),r=l>0?t[l-1]:"";n&&isPrecededByWhitespace(r)&&(i(!0),u(e))}if(a)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),u("");else{const n=t.substring(e+1);u(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);u(e),i(!1)}else u(n)}}O&&(t!==e||t.length<e.length)&&L(!1),Se&&ke(),0===t.length&&(F(!1),Q(!1),ee(""),ne(!1),Oe(),ae([]),u(""),me(""),Te()),n(t)},[O,e,n,a,i,B,M,ie,he,Pe,Te,_,Se,ke,be,Oe]),Ue=V(async()=>{if(_e(),oe.current=0,O)return void L(!1);let n=e.trim();if(!M&&n.startsWith("/")&&d&&"handled"===(await d(n)).status)return T?.add(n),F(!1),Q(!1),ee(""),Oe(),ae([]),fe(-1),void we("");n.length>0&&T?.add(n),fe(-1),we("");let r=[];const o=ie.length>0,s=se.length>0;if(!M&&o&&(r=[...ie]),!M&&s){let e=n;se.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:M?"bash":"user",images:r,ideContext:xe?bg(xe):void 0}),F(!1),Q(!1),ee(""),Oe(),ae([])},[t,d,O,e,M,ie,se,T,_e,Oe]),je=V(t=>{const r=o(process.cwd(),t);let s;if(a&&""!==l){const t=e.lastIndexOf("@");s=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else s=`${e}${r} `;n(s),i(!1),u(""),D(e=>e+1)},[n,i,e,a,l,u]),Be=V(()=>{i(!1),u("")},[i,u]),qe=V(t=>{if("/resume"===t)T?.add(t),fe(-1),we(""),me(e),Q(!1),ee(""),ne(!0),n(""),D(e=>e+1);else{const e=Object.values(Gm).includes(t);Q(!1),ee(""),e?(T?.add(t),fe(-1),we(""),n(""),D(e=>e+1),d&&d(t)):(n(t+" "),D(e=>e+1))}},[d,n,e,T]),ze=V(e=>{Q(!1),ee(""),n(e+" "),D(e=>e+1)},[n]),We=V(()=>{Q(!1),ee(""),n(""),fe(-1),we(""),D(e=>e+1)},[n]),He=V(e=>{ne(!1),n(""),me(""),fe(-1),we(""),D(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Ve=V(()=>{ne(!1),n(de),fe(-1),we(""),D(e=>e+1)},[de,n]),Ge=V(e=>{Ee.current=e},[]),Ke=G(()=>{const t=De&&("OPEN"===De.state||"MERGED"===De.state);return"auto-accept"===C||"plan"===C||Ie||t?!O&&!te:!O&&0===e.length&&!M&&!te},[O,e,M,te,C,Ie,De]),Je=W(new Map),Qe=G(()=>ie.map((e,t)=>{if(Je.current.has(e))return Je.current.get(e)??null;const n=saveTempImage(e,t+1);return Je.current.set(e,n),n}),[ie]),Ye=__name(()=>O||a||B||te||U?0:Ke||A||M?3:4,"getBottomMargin");return q.createElement(K,{width:"100%",flexDirection:"column",marginBottom:Ye()},!te&&q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(ImageRowsDisplay,{detectedImages:ie,selectedImageIndex:le,imageTempPaths:Qe,termWidth:Re,inHistory:-1!==he}),q.createElement(J,{color:M?"green":"gray"},ve.line.repeat(Re)),q.createElement(TextInput,{key:R,value:e,placeholder:be?"Save and close the editor to continue...":s,onChange:Fe,onSubmit:()=>{if(!pe.current)return Date.now()-oe.current<100?(oe.current=0,void Me()):void(a||B||te||be||Ue());pe.current=!1},showCursor:!be&&r&&-1===le,onCursorChange:Ge,prefix:`${M?"!":ve.pointer} `,prefixColor:M?"green":"white"}),q.createElement(J,{color:M?"green":"gray"},ve.line.repeat(Re))),O&&q.createElement(Pg,null),U&&q.createElement(K,{paddingTop:1},q.createElement(J,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),a&&q.createElement(ug,{onSelectFile:je,onClose:Be,searchQuery:l}),B&&q.createElement(Qm,{onSelectCommand:qe,onInsertCommand:ze,onClose:We,searchQuery:Y}),te&&q.createElement(wg,{onSelectSession:He,onClose:Ve}),(Ke||A)&&q.createElement(yg,{termWidth:Re,indicatorText:vg(Ie,xe,Re),isIDEIndicator:Sg(Ie,xe),permissionMode:C,prInfo:De,tasteLearning:g,contextUsage:m,connectionIndicator:Ne,pendingExitKey:A,updateStatus:E,updateFailedInfo:b,currentProvider:S,showProviderInfo:v,isBashMode:M,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w}),Se&&q.createElement(K,{paddingLeft:1,flexDirection:"column"},q.createElement(J,{color:"yellow"},Se)))},"InputBox"),Ag=q.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:a,showFileList:i,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:p,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:E,tasteNotificationMessage:b,updateStatus:S,updateFailedInfo:v,currentProvider:C,showProviderInfo:k,permissionMode:P,onToggleAutoAccept:T,hintMessage:A,historyManager:x,pendingExitKey:I,onResetPendingExitKey:_,onDoubleEscapeEmpty:N,retryAttempt:$,onAltP:R})=>{const[D,O]=z(0),L=W(o);return H(()=>{I&&o!==L.current&&o.length>0&&_?.(),L.current=o},[o,I,_]),H(()=>{if(!t)return void O(0);const e=setInterval(()=>{O(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),q.createElement(K,{flexDirection:"column"},q.createElement(Ym,{messages:e}),q.createElement(K,{flexDirection:"row",justifyContent:"space-between"},q.createElement(K,{flexDirection:"column"},(t||n.isExecuting)&&null===$&&q.createElement(qm,{tokens:g,timeElapsed:D,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),A&&q.createElement(K,{marginLeft:1},q.createElement(J,{dimColor:!0}," ","⎿"," Tip: ",A)))),q.createElement(Tg,{input:o,setInput:s,onSubmit:a,placeholder:"Ask your question...",showFileList:i,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:p,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:E,tasteNotificationMessage:b,updateStatus:S,updateFailedInfo:v,currentProvider:C,showProviderInfo:k,permissionMode:P,onToggleAutoAccept:T,hintMessage:A,historyManager:x,pendingExitKey:!I||t||n.isExecuting?null:I,onDoubleEscapeEmpty:N,onAltP:R,isProcessing:t}))});_t();var xg=__name(({onClose:e})=>{const[t,n]=z(Bd.getEvents());X((t,n)=>{n.ctrl&&"t"===t&&(nm(),e())},{isActive:!0}),H(()=>{const e=__name(()=>{n(Bd.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return Bd.on("new-event",e),Bd.on("cleared",t),()=>{Bd.off("new-event",e),Bd.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 q.createElement(K,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(Ye,{name:"vice"},q.createElement(J,null,Po()))),q.createElement(K,{marginBottom:1,width:"100%",justifyContent:"space-between"},q.createElement(K,null,q.createElement(J,{bold:!0},"Learning Feed"),q.createElement(J,{dimColor:!0}," - Real-time taste learning activity")),q.createElement(J,{dimColor:!0},"Press ctrl+t to close")),q.createElement(K,{flexDirection:"column"},0===t.length?q.createElement(K,null,q.createElement(J,{dimColor:!0},"No learning events yet...")):q.createElement(K,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:i}=o(e.message),l="moved"===t?a(e.details):null,u="upgraded"===t||"downgraded"===t?s(r):null;return q.createElement(K,{key:e.id,marginBottom:1},q.createElement(K,{flexDirection:"column"},q.createElement(K,null,q.createElement(J,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),l?q.createElement(J,{dimColor:!0}," (",l.fullPath,")"):e.details?q.createElement(J,{dimColor:!0}," (",e.details,")"):null),q.createElement(K,{marginLeft:1},q.createElement(J,{dimColor:!0},"⎿"," "),l?q.createElement(q.Fragment,null,q.createElement(J,null,l.category," package ("),q.createElement(J,{dimColor:!0},l.oldPath),q.createElement(J,null," → ",l.newPath),q.createElement(J,null,")")):u?q.createElement(q.Fragment,null,q.createElement(J,null,u.text," ("),q.createElement(J,{dimColor:!0},"confidence: "),q.createElement(J,{dimColor:!0},u.oldPercent,"%"),q.createElement(J,null," → "),q.createElement(J,{color:u.diff>0?"green":"red"},u.newPercent,"%"),q.createElement(J,null,")")):q.createElement(q.Fragment,null,q.createElement(J,null,r),i&&q.createElement(J,{dimColor:!0}," (",i,")")))))}return q.createElement(K,{key:e.id,marginBottom:1},q.createElement(J,{dimColor:!0},ve.pointerSmall," ",e.message))}))))},"LearningFeedFull");_t(),Ot(),cn();var Ig=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(0),[s,a]=z(!0),[i,l]=z(null);H(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),a(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),a(!1)}},"loadMemoryFiles")()},[]);const u=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(X((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]&&u(d[r]),"1"===t&&d[0]&&u(d[0]),"2"===t&&d[1]&&u(d[1]))}),s)return q.createElement(K,{paddingLeft:1,paddingTop:1},q.createElement(J,{color:"dim"},"Loading memory files..."));if(i)return q.createElement(K,{paddingLeft:1,paddingTop:1},q.createElement(J,{color:"red"},"❌ ",i));const m=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 q.createElement(K,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},q.createElement(K,null,q.createElement(J,{color:"white",bold:!0},"Select memory to edit:")),q.createElement(K,{columnGap:4,marginTop:1},q.createElement(K,{flexDirection:"column"},m.map((e,t)=>q.createElement(J,{key:t,color:r===t?"white":"dim"},r===t?`${nn} `:" ",e.label))),q.createElement(K,{flexDirection:"column"},m.map((e,t)=>q.createElement(J,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector");_t(),_t(),_t();var _g=class extends Xe{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}list(e,t=!1,n=""){let r=super.list(e,t,n);return r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),r}},Ng=new Ze;Ng.setOptions({renderer:new _g({strong:te.bold,em:te.italic,del:te.strikethrough,codespan:te.yellow,code:te.yellow,heading:te.bold.underline,firstHeading:te.bold.underline,link:te.cyan,href:te.cyan.underline,blockquote:te.gray.italic,table:te.reset,hr:te.reset,paragraph:te.reset,html:te.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var $g=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=G(()=>{if(!e)return"";const t=[],n=e.replace($g,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=Ng.parse(n);return"string"!=typeof r?e:r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").trim()}catch{return e}},[e]);return q.createElement(J,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return q.createElement(K,null,q.createElement(J,null,ve.nodejs),q.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},q.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage"),_t(),cn();var Rg={"Interrupted by user":"Interrupted by user","Insufficient credits":en};function UserMessage({content:e,imageCount:t=0}){const n="Interrupted by user"===e,r="Insufficient credits"===e,o=e.startsWith("Error:"),s=n||r||o,a=s&&Rg[e]||e;return q.createElement(K,{flexDirection:"column"},q.createElement(K,{paddingX:1,backgroundColor:s?void 0:"#333333"},q.createElement(J,{color:s?"red":"#AAAAAA",bold:!s},ve.pointer),q.createElement(K,{marginLeft:1},q.createElement(J,{color:s?"red":"white",wrap:"wrap"},a))),t>0&&q.createElement(K,{marginLeft:1},q.createElement(J,{dimColor:!0},"⎿"," ",Array.from({length:t},(e,t)=>`[Image #${t+1}]`).join(" "))))}__name(UserMessage,"UserMessage"),_t(),Zt(),Dn(),gr();var Dg="#6B7280";function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,dimDiff:a=!1,maxLines:i}){const l=et.diffLines(e,t);let u=0,d=0,m=0,g=0;l.forEach(e=>{e.added?(u+=e.count||1,g+=e.count||1):e.removed&&(d+=e.count||1,g+=e.count||1)});const p=[];l.forEach((e,t)=>{const n=e.value.split("\n").filter(e=>e);e.added||e.removed?n.forEach((n,r)=>{e.removed?(m++,p.push(q.createElement(K,{key:`${t}-${r}-removed`,width:"100%"},q.createElement(J,{color:"gray",dimColor:a},m.toString().padStart(3)," "),q.createElement(K,{backgroundColor:"#712F37"},q.createElement(J,{dimColor:a},"-"),q.createElement(J,{dimColor:a}," ",n.replace(/\s/g," ")))))):e.added&&(m++,p.push(q.createElement(K,{key:`${t}-${r}-added`,width:"100%"},q.createElement(J,{color:"gray",dimColor:a},m.toString().padStart(3)," "),q.createElement(K,{backgroundColor:"#325B30"},q.createElement(J,{dimColor:a},"+"),q.createElement(J,{dimColor:a}," ",n.replace(/\s/g," "))))))}):m+=n.length});const h=void 0!==i&&p.length>i,f=h?p.slice(0,i):p;return{diffContent:q.createElement(K,{flexDirection:"column"},o&&!r&&q.createElement(J,{color:"gray"},"Updated"," ",q.createElement(J,{color:"white",bold:!0},n)," ","with ",q.createElement(J,{color:"#22C55E"},u)," addition",1!==u?"s":""," and"," ",q.createElement(J,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&q.createElement(J,{color:"red"},"Rejected update to",q.createElement(J,{color:"red"},` ${n}`)),q.createElement(K,{flexDirection:"column",marginLeft:s},f)),isTruncated:h,totalLines:p.length}}function formatTodosForDisplay(e){const t=Mu(e);return t?q.createElement(K,{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 q.createElement(K,{key:e.id||t,flexDirection:"row"},q.createElement(K,{width:2},q.createElement(J,{color:r},n)),q.createElement(J,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):q.createElement(J,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,l="Todos"===e,u="Edit"===e,d=!0===s?.isTasteFile,m=s?.tasteCategory,g=!0===s?.permissionDenied,p=!i&&!l&&!d,{name:h}=detectTerminal(),f="iTerm2"===h?"shift":"ctrl",y=!0===s?.isAgent,w="Shell"===e,E=t&&y?(()=>{const e=t.split(/[.\n]/)[0];return e?e+(t.includes(".")||t.includes("\n")?".":""):t})():w&&t&&!a?truncateCommand({command:t}):t,b=!i&&E&&!d,S=s?.status,v=s?.tokensUsed||0,C="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0;let k,P;if(r)k="yellow",P="→";else if(o)k="red",P=ve.nodejs;else if(i)k=Dg,P="✻";else if(l&&n){const e=Mu(n),t=e?.every(e=>"completed"===e.status);k=t?"#22C55E":"#D4A017",P=ve.nodejs}else k="#22C55E",P=ve.nodejs;return q.createElement(K,null,i&&q.createElement(J,{color:k},P),q.createElement(K,{flexDirection:"column",marginLeft:i?1:0},q.createElement(K,null,i?q.createElement(q.Fragment,null,q.createElement(J,{color:Dg},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!a&&q.createElement(J,{dimColor:!0},"(",`${f}+o to expand`,")")):d?q.createElement(q.Fragment,null,q.createElement(J,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),q.createElement(J,null," ","Using your taste ",m?"package of ":"packages",m&&q.createElement(J,{bold:!0},m))):q.createElement(J,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),b&&q.createElement(J,null," ",q.createElement(Markdown,null,`(${E})`))),y&&("running"===S||n)&&q.createElement(K,{columnGap:1,marginLeft:p?1:0},p&&q.createElement(J,null,"⎿"," "),"running"===S?q.createElement(J,{color:"gray"},"Running (",formatTime2(C)," | ",formatTokens(v),")"):"interrupted"===S?q.createElement(J,{color:"red",wrap:"wrap"},"Interrupted by user"):"error"===S||o?q.createElement(J,{color:"red",wrap:"wrap"},n," (",formatTime2(C)," | ",formatTokens(v),")"):"Interrupted by user"===n?q.createElement(q.Fragment,null,q.createElement(J,{color:"red",wrap:"wrap"},"Interrupted by user")):q.createElement(q.Fragment,null,q.createElement(J,{wrap:"wrap"},"Done"),q.createElement(J,{color:"gray"}," ","(",formatTime2(C)," | ",formatTokens(v),")"))),n&&!d&&!y&&q.createElement(K,{columnGap:1,marginLeft:p?1:0},p&&q.createElement(J,null,"⎿"," "),l?formatTodosForDisplay(n):i?a?q.createElement(K,{width:"100%",flexDirection:"column"},q.createElement(J,null," "),q.createElement(J,{color:Dg,wrap:"wrap",italic:!0},n)):null:u&&s?.oldValue&&s?.newValue?q.createElement(K,{flexDirection:"column"},(()=>{const e=a?void 0:er,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:g,permissionDenied:g,maxLines:e});return q.createElement(q.Fragment,null,n,r&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"… (",o-er," more lines) (",`${f}+o to expand`,")")))})(),g&&n&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"red",wrap:"wrap"},n))):q.createElement(K,{width:"100%"},q.createElement(J,{color:o?"red":"",wrap:"wrap"},a||o?n:(()=>{const{text:t,isTruncated:r,remainingLines:o}=truncateToVisualLines({output:n,maxVisualLines:"Question"===e?Xn:Zn,maxChars:"Question"===e?1/0:rr});return q.createElement(q.Fragment,null,t,r&&"Question"!==e&&q.createElement(J,{dimColor:!0},"\n",o>0?`... +${o} lines (${f}+o to expand)`:`... (${f}+o to expand)`))})()))),r&&!y&&q.createElement(K,{columnGap:1,marginLeft:1},q.createElement(J,null,"⎿"," "),q.createElement(J,{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="✓"),q.createElement(K,null,q.createElement(J,{color:o},s),q.createElement(K,{flexDirection:"column",marginLeft:1},q.createElement(K,null,q.createElement(J,{color:"gray"},"$ "),q.createElement(J,{color:o,bold:!0},e)),q.createElement(K,{columnGap:1,marginLeft:1},q.createElement(J,null,"⎿"," "),q.createElement(J,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),_t(),__name(BashMessage,"BashMessage"),_t(),_t(),Ot();_t(),Ot();var Og="Coding agent that continuously learns your taste of writing code.",Lg=34,Mg=[{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"}],Fg=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume",description:"Resume a conversation"},{key:"-c, --continue",description:"Continue the last conversation"},{key:"-t, --trust",description:"Auto-trust project (skip initial permission prompt)"},{key:"-p, --print [query]",description:"Run in non-interactive mode, output response and exit"},{key:"--plan",description:"Start in plan mode"},{key:"--permission-mode <mode>",description:"Set permission mode (standard, plan, auto-accept)"},{key:"--dangerously-skip-permissions",description:"Bypass all permission prompts (use with caution)"},{key:"--add-dir <directory>",description:"Add directory to workspace context"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"--ide-setup",description:"Setup extension for editor context"},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],Ug=[{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:"/review [pr]",description:"Review a pull request (optional PR number)"},{key:"/add-dir",description:"Manage additional directory scope"},{key:"/help",description:"Display help information"},{key:"/exit",description:"Exit Command Code"}],jg=[{key:"cmd info",description:"Display system information"},{key:"cmd status",description:"Show authentication status"},{key:"cmd help",description:"Display help information"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Bg=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],qg=[{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"}],zg='Start with a prompt: cmd "fix the login bug"';_t(),Wn();var Wg="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]:[Wg]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||Wg;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||Wg}catch{return Wg}}function HelpMessage(){const e=getInvokedCommandName(),t=G(()=>Ug.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return q.createElement(K,{flexDirection:"column",paddingY:1},q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(K,null,q.createElement(J,{bold:!0},"Command Code"),q.createElement(J,{color:"gray"}," v","0.13.0")),q.createElement(J,{color:"gray"},Og)),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Usage"),q.createElement(K,{paddingLeft:2},q.createElement(J,null,e," <command> [options]"))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Options"),q.createElement(K,{flexDirection:"column",paddingLeft:2},Fg.map(t=>q.createElement(K,{key:t.key},q.createElement(J,null,t.key.replace(/^cmd/,e).padEnd(Lg)),q.createElement(J,{color:"gray"},t.description))))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Commands"),q.createElement(K,{flexDirection:"column",paddingLeft:2},jg.map(t=>q.createElement(K,{key:t.key},q.createElement(J,null,t.key.replace(/^cmd/,e).padEnd(Lg)),q.createElement(J,{color:"gray"},t.description))))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Slash Commands"),q.createElement(K,{flexDirection:"column",paddingLeft:2},t.map(e=>q.createElement(K,{key:e.key},q.createElement(J,null,e.key.padEnd(Lg)),q.createElement(J,{color:"gray"},e.description))))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Keyboard Shortcuts"),q.createElement(K,{flexDirection:"column",paddingLeft:2},Mg.map(e=>q.createElement(K,{key:e.key},q.createElement(J,null,e.key.padEnd(Lg)),q.createElement(J,{color:"gray"},e.description))))),q.createElement(K,{flexDirection:"column",marginBottom:1},q.createElement(J,{bold:!0},"Examples"),q.createElement(K,{flexDirection:"column",paddingLeft:2},qg.map(t=>q.createElement(K,{key:t.key},q.createElement(J,null,t.key.replace(/^cmd/,e).padEnd(Lg)),q.createElement(J,{color:"gray"},t.description))))),q.createElement(K,{marginBottom:1},q.createElement(J,{color:"cyan"},"❯"),q.createElement(J,{color:"gray"}," ",zg.replace(/cmd/,e))),q.createElement(K,{flexDirection:"column"},q.createElement(J,{bold:!0},"Links"),q.createElement(K,{flexDirection:"column",paddingLeft:2},Bg.map(e=>q.createElement(K,{key:e.key},q.createElement(J,null,e.key.padEnd(Lg)),q.createElement(J,{color:"cyan"},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?q.createElement(HelpMessage,null):q.createElement(K,{flexDirection:"column"},q.createElement(J,{wrap:"wrap"},q.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return q.createElement(K,null,q.createElement(J,{color:"red"},t?ve.pointer:ve.warning),q.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?q.createElement(J,{color:"red",wrap:"wrap"},e):q.createElement(Markdown,{color:"red"},e)))}function AutoCompactMessage({content:e}){return q.createElement(K,null,q.createElement(J,{dimColor:!0},ve.info),q.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},q.createElement(J,{dimColor:!0},e)))}function InfoMessage({content:e,metadata:t}){return t?.isAutoCompact?q.createElement(AutoCompactMessage,{content:e}):q.createElement(K,null,q.createElement(J,{dimColor:!0},ve.info),q.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},q.createElement(J,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return q.createElement(K,{flexDirection:"column",marginBottom:0,marginTop:-1},q.createElement(K,{columnGap:1},q.createElement(J,null,"⎿"," "),q.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},q.createElement(J,{color:n?"yellow":void 0},e))),t&&q.createElement(K,{marginLeft:3},q.createElement(J,{dimColor:!0},"See ",t)))}function IDEStatusMessage({status:e,ide:t,details:n}){return q.createElement(K,{flexDirection:"column"},q.createElement(K,null,"connected"===e&&q.createElement(J,null,q.createElement(J,{color:"green"},ve.tick),q.createElement(J,null," Connected to "),q.createElement(J,{color:"cyan"},t)),"installed"===e&&q.createElement(J,null,q.createElement(J,{color:"green"},ve.tick),q.createElement(J,null," Installed for "),q.createElement(J,{color:"cyan"},t)),"needs_reload"===e&&q.createElement(J,null,q.createElement(J,{color:"yellow"},ve.circle),q.createElement(J,null," "),q.createElement(J,{color:"cyan"},t),q.createElement(J,null," extension needs reload")),"failed"===e&&q.createElement(J,null,q.createElement(J,{color:"red"},ve.cross),q.createElement(J,null," Install failed")),"not_in_ide"===e&&q.createElement(J,null,q.createElement(J,{color:"yellow"},ve.circle),q.createElement(J,null," Not in IDE"))),n?.map((e,t)=>q.createElement(J,{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"),Rn(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),_t(),__name(ErrorMessage,"ErrorMessage"),_t(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(InfoMessage,"InfoMessage"),_t(),__name(CommandResultMessage,"CommandResultMessage"),_t(),__name(IDEStatusMessage,"IDEStatusMessage"),Wn(),Ot(),Rn(),__name(getModelShortName,"getModelShortName");var Hg=q.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const s=t?["header",...e]:e,a=Po();getTerminalWidth();const i=getPackageJson().version||"0.0.0",l=o?getModelShortName(o):"sonnet-4.5",u=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",m=u.replace(d,"~"),g=getGitHeaderInfo();return q.createElement(Q,{items:s,key:n,style:{width:"100%"}},e=>{if("header"===e)return q.createElement(K,{key:"header",marginBottom:1,flexDirection:"column"},q.createElement(Ye,{name:"vice"},q.createElement(J,null,a.trimEnd())),q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(K,null,q.createElement(J,{color:"gray"},"# "),q.createElement(J,{bold:!0},"Command Code"),q.createElement(J,{color:"gray"}," v",i)),q.createElement(J,{color:"gray"},"# models: ",l," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),q.createElement(K,null,q.createElement(J,{color:"gray"},"# ",m,g&&g.isLocal&&g.branch&&q.createElement(J,{color:"gray"}," (branch: ",g.branch,")")))));const t=e,n=(()=>{switch(t.role){case"user":{const e=Array.isArray(t.metadata?.images)?t.metadata.images.length:0;return q.createElement(UserMessage,{content:t.input,imageCount:e})}case"assistant":return q.createElement(AssistantMessage,{content:t.input});case"tool":return q.createElement(ToolMessage,{name:Du(t.name||""),input:t.input,output:t.output||"",isPending:Nu(t),hasError:_u(t),metadata:t.metadata,expandedOutput:r});case"bash":return q.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:Nu(t),hasError:_u(t)});case"system":return q.createElement(SystemMessage,{content:t.input});case"info":return q.createElement(InfoMessage,{content:t.input,metadata:t.metadata});case"error":return q.createElement(ErrorMessage,{content:t.input});case"command-result":return q.createElement(CommandResultMessage,{message:t.input,details:t.details,hasError:t.hasError??!1});case"ide-status":return q.createElement(IDEStatusMessage,{status:t.status,ide:t.ide,details:t.details});default:return q.createElement(q.Fragment,null)}})();return q.createElement(K,{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}))}_t(),Ot(),__name(getModelOptions,"getModelOptions");var Vg=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");X((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0;return q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(K,null,q.createElement(J,{color:"#E4CCFF",bold:!0},"Select model")),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),q.createElement(Ke,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>q.createElement(J,{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 q.createElement(K,null,q.createElement(J,{color:a},` ${(o?.label||t).padEnd(24)}`),q.createElement(J,{dimColor:!0},o?.description),s&&q.createElement(J,{color:"green"}," ✓"))}}),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press "),q.createElement(J,{dimColor:!0,bold:!0},"Esc"),q.createElement(J,{dimColor:!0}," to cancel")))},"ModelSelector");_t(),Ot();var Gg=__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"),l=__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"),u=__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 q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,color:"yellow"},`${u()} ${"edit"===e.action?l():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&q.createElement(K,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:l(),marginLeft:0}).diffContent),q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0},"Do you want to ",i()," ",q.createElement(J,{color:"cyan"},l()),"?")),q.createElement(Ke,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:o,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"cyan"},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>q.createElement(J,{color:t?"cyan":"white"},e.includes("(shift+tab)")?q.createElement(q.Fragment,null,e.split("(shift+tab)")[0],q.createElement(J,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?q.createElement(q.Fragment,null,e.split("(")[0],q.createElement(J,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt");_t(),Rn();var Kg=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");X((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,a=n&&-1===s;return q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(K,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},q.createElement(K,null,q.createElement(J,{bold:!0},"Select AI Provider")),n&&q.createElement(K,{flexDirection:"row"},q.createElement(J,{dimColor:!0},"Current: "),q.createElement(J,{color:"green"},getProviderDisplayName(n)),a&&q.createElement(J,{color:"yellow"}," [OAuth enforced]"))),q.createElement(K,{marginBottom:0},q.createElement(J,{dimColor:!0},"Available Providers:")),q.createElement(Ke,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"cyan":"gray",bold:e},` ${t}`)}),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");_t();var Jg=__name(({staticKey:e})=>q.createElement(Q,{items:[{staticKey:e}],key:e},()=>q.createElement(J,{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 q.createElement(K,{marginBottom:1},q.createElement(J,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}_t(),__name(RetryMessage,"RetryMessage"),_t(),gr(),cn();var Qg=[{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"}],Yg=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=G(()=>[...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)),[l,u]=z("checkpoint"),[d,m]=z(null),[g,p]=z(0),h=G(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),f=G(()=>h?Qg:Qg.filter(e=>"conversation"===e.mode),[h]);if(H(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),X((e,h)=>{h.escape?"mode"===l?(u("checkpoint"),m(null),p(0)):n():"checkpoint"===l?h.upArrow?s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t}):h.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(t-8+1),t}):h.return&&r.length>0&&(m(r[o]),u("mode"),p(0)):"mode"===l&&(h.upArrow?p(e=>Math.max(0,e-1)):h.downArrow?p(e=>Math.min(f.length-1,e+1)):h.return&&d&&f[g]&&t({messageId:d.messageId,mode:f[g].mode}))}),0===r.length)return q.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},q.createElement(J,{color:"#E4CCFF",bold:!0},"Rewind"),q.createElement(J,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press "),q.createElement(J,{dimColor:!0,bold:!0},"Esc"),q.createElement(J,{dimColor:!0}," to close")));if("mode"===l&&d)return q.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},q.createElement(J,{color:"#E4CCFF",bold:!0},"Rewind"),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"Restore to: "),q.createElement(J,{color:"white"},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),q.createElement(K,{flexDirection:"column"},f.map((e,t)=>{const n=g===t,r=t===f.length-1;return q.createElement(K,{key:e.mode,flexDirection:"column"},q.createElement(K,{flexDirection:"row"},q.createElement(J,{color:n?"#E4CCFF":void 0},n?`${nn} `:" "),q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:n?"#E4CCFF":"white"},e.label),q.createElement(J,{dimColor:!0},e.description))),!r&&q.createElement(J,null," "))})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press "),q.createElement(J,{dimColor:!0,bold:!0},"Enter"),q.createElement(J,{dimColor:!0}," to confirm, "),q.createElement(J,{dimColor:!0,bold:!0},"Esc"),q.createElement(J,{dimColor:!0}," to go back")));const y=r.slice(a,a+8);return q.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},q.createElement(J,{color:"#E4CCFF",bold:!0},"Rewind"),q.createElement(J,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),q.createElement(K,{marginTop:1}),q.createElement(K,{flexDirection:"column"},y.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,l=t===y.length-1,u=n===r.length-1;return q.createElement(K,{key:e.messageId,flexDirection:"column"},q.createElement(K,{flexDirection:"row"},q.createElement(J,{color:s?"#E4CCFF":void 0},s?`${nn} `:" "),q.createElement(K,{flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:s?"#E4CCFF":"white"},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),q.createElement(J,{dimColor:!0}," • "),q.createElement(J,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),q.createElement(J,{dimColor:!0},i>0?`${i} file${i>1?"s":""} changed`:"No code changes"))),!l&&q.createElement(J,null," "))})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press "),q.createElement(J,{dimColor:!0,bold:!0},"Enter"),q.createElement(J,{dimColor:!0}," to select, "),q.createElement(J,{dimColor:!0,bold:!0},"Esc"),q.createElement(J,{dimColor:!0}," to cancel")))},"RewindSelector");_t(),gr();var Zg=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=ee(),[r,o]=z([]),[s,a]=z(0),[i,l]=z(!0),[u,d]=z(0),m=30;H(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await Cd.listSessions();o(e),l(!1)},"loadSessions");if(X((t,o)=>{o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):o.downArrow?a(e=>{const t=Math.min(r.length-1,e+1);return t>=u+m&&d(t-m+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),i)return q.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},q.createElement(J,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),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"),h=__name(e=>truncateString({text:e,maxChars:or}),"truncateMessage");if(0===r.length)return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"gray"},"No sessions available"));const f=r.slice(u,u+m),y=u;return q.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&q.createElement(K,{marginBottom:1},q.createElement(J,{color:"dim"},"Showing ",u+1,"-",Math.min(u+m,r.length)," ","of ",r.length," sessions",u>0&&" (↑ for more)",u+m<r.length&&" (↓ for more)")),q.createElement(K,{columnGap:2,marginBottom:1},q.createElement(K,{width:7},q.createElement(J,{color:"gray"}," ")),q.createElement(K,{width:13},q.createElement(J,{color:"gray"},"Modified")),q.createElement(K,{width:11},q.createElement(J,{color:"gray"},"# Messages")),q.createElement(K,{width:20},q.createElement(J,{color:"gray"},"Git Branch")),q.createElement(K,null,q.createElement(J,{color:"gray"},"Summary"))),q.createElement(K,{columnGap:2},q.createElement(K,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${ve.pointer} ${n+1}.`:` ${n+1}.`)})),q.createElement(K,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`mod-${e.id}`,color:s===n?"white":"gray"},p(e.lastModified))})),q.createElement(K,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),q.createElement(K,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),q.createElement(K,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return q.createElement(J,{key:`summary-${e.id}`,color:s===n?"white":"gray"},h(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 E.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?"[Del] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}_t(),En(),jt(),_t(),jt(),__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 Xg=__name(({onClose:e})=>{const[t,n]=z(""),[r,o]=z(null),[s,a]=z([]),[i,l]=z(getAdditionalDirectories()),[u,d]=z({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=z(0);H(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),H(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const p=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),h=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());o({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),l(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");X((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&s[u.suggestionIndex]?void p(s[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&i[u.activeDirIndex])h(i[u.activeDirIndex]);else{if(r.tab&&s.length>0){const e=s[u.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:s.length,activeDirCount:i.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:i.length}))}}}),H(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[u,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 f=s.slice(m,m+8),y=getFooterText({focusZone:u.zone});return q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},q.createElement(J,{bold:!0,color:"cyan"},"Add directory to workspace"),q.createElement(J,{color:"gray"},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,{color:"gray"},"Added directories"),0===i.length?q.createElement(J,{color:"gray"}," None yet"):i.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return q.createElement(J,{key:e,color:n?"yellow":"green",bold:n},n?` ${ve.pointer} `:" ",formatDirectoryForDisplay(e))})),q.createElement(K,{marginTop:1},q.createElement(J,{bold:!0,color:"white"},"Path")),q.createElement(K,null,q.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?ve.pointer:" "} `,prefixColor:"input"===u.zone?"cyan":"gray",onChange:e=>{n(e),o(null)},onSubmit:p})),!t&&q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray"},"Examples: ../shared ~/docs /abs/path")),r&&q.createElement(K,{marginTop:1},q.createElement(J,{color:{error:"red",warning:"yellow",success:"green"}[r.tone]},r.text)),s.length>0&&q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(J,{color:"gray"},"Suggestions"),f.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return q.createElement(J,{key:e,color:r?"cyan":"gray",bold:r},r?` ${ve.pointer} `:" ",e)})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},y)))},"AddDirModal");_t(),Ot();var ep=__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 q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,color:"yellow"},"Execute Shell Command")),q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",q.createElement(J,{color:"cyan"},a()),".")),e.workingDirectory&&q.createElement(K,{marginBottom:1},q.createElement(J,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0,italic:!0},e.description)),q.createElement(Ke,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"cyan"},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>q.createElement(J,{color:t?"cyan":"white"},e.includes("(shift+tab)")?q.createElement(q.Fragment,null,e.split("(shift+tab)")[0],q.createElement(J,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt");_t(),Ot();var tp=__name(e=>Math.ceil(e.length/4),"estimateTokens"),np=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(!0),[s,a]=z(null),[i,l]=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 u=t.filter(e=>"project"===e.location),d=t.filter(e=>"user"===e.location),m=[...u,...d],g=__name(async t=>{try{await tt([{file:t.filePath,line:1}]),nm(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?a(p()):a(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");X((t,n)=>{if(n.escape)return nm(),void e();if(n.upArrow)l(e=>Math.max(0,e-1));else if(n.downArrow)l(e=>Math.min(m.length-1,e+1));else if(n.return){const e=m[i];e&&g(e)}});const p=__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?q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(J,{color:"#E4CCFF",bold:!0},"Agent Skills"),q.createElement(J,{dimColor:!0},"Loading skills...")):s?q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(J,{color:"red",bold:!0},"Agent Skills"),q.createElement(J,{dimColor:!0},s),q.createElement(K,{marginTop:1}),q.createElement(J,{dimColor:!0},"Press ",q.createElement(J,{bold:!0},"Esc")," to close")):0===t.length?q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(J,{color:"#E4CCFF",bold:!0},"Agent Skills"),q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"No skills found")),q.createElement(J,{dimColor:!0},"Create skills in:"),q.createElement(J,{dimColor:!0}," ~/",".commandcode","/","skills","/ (user)"),q.createElement(J,{dimColor:!0}," ",".commandcode","/","skills","/ (project)"),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press ",q.createElement(J,{bold:!0},"Esc")," to close"))):q.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},q.createElement(K,null,q.createElement(J,{color:"#E4CCFF",bold:!0},"Skills "),q.createElement(J,{dimColor:!0},m.length," skills")),u.length>0&&q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(K,null,q.createElement(J,{color:"#666666",bold:!0},"Project skills "),q.createElement(J,{color:"#666666"},"(",".commandcode","/","skills",")")),u.map((e,t)=>{const n=i===t;return q.createElement(K,{key:e.value},q.createElement(J,{color:n?"green":"white"},e.label),q.createElement(J,{dimColor:!0}," · ~",tp(e.description)," description tokens"))})),d.length>0&&q.createElement(K,{flexDirection:"column",marginTop:1},q.createElement(K,null,q.createElement(J,{color:"#666666",bold:!0},"User skills "),q.createElement(J,{color:"#666666"},"(~/",".commandcode","/","skills",")")),d.map((e,t)=>{const n=i===u.length+t;return q.createElement(K,{key:e.value},q.createElement(J,{color:n?"green":"white"},e.label),q.createElement(J,{dimColor:!0}," · ~",tp(e.description)," description tokens"))})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0,italic:!0},"Esc to close")))},"SkillsConfig");_t(),Nn();var rp=__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")()},[]),X((t,n)=>{if(!n.return&&" "!==t)return n.escape?(nm(),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?q.createElement(K,{key:n,borderStyle:"single",borderColor:"blue",padding:1,flexDirection:"column"},q.createElement(J,{color:"blue",bold:!0},"Taste Settings"),q.createElement(J,{dimColor:!0},"Loading configuration...")):q.createElement(K,{key:n,borderStyle:"single",borderColor:"gray",padding:1,flexDirection:"column"},q.createElement(J,{bold:!0},"Taste Learning"),q.createElement(J,{dimColor:!0},"Configure taste learning preferences for this project"),q.createElement(K,{marginTop:1}),q.createElement(K,{justifyContent:"space-between"},q.createElement(J,null,"Taste learning",q.createElement(J,{dimColor:!0}," - Learn from your interactions")),q.createElement(J,{color:r?"green":"gray"},r?"enabled":"disabled")),q.createElement(K,{marginTop:1}),q.createElement(J,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),q.createElement(J,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig");_t(),xn(),_t(),_t();var op=__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 Bd.on("reset",t),Bd.on("new-event",r),()=>{Bd.off("reset",t),Bd.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new Tl({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;if(n===St.ANTHROPIC)try{const e=await rn.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={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(s[yt.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}_t(),_t(),xn(),_t(),xn(),_t(),_t(),Ot(),ln(),xn(),Nn(),Dn(),__name(createRequestClient,"createRequestClient"),_t(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),_t(),_t(),Ot(),xn(),Zt(),_t();var sp="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:${sp}`,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}`),Bd.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()}`),Bd.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=He.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 ${wt.ALPHA.GENERATE} with model: ${sp}`);const r=buildRequestBody2(n);let o;try{o=await e.post({endpoint:wt.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(Bd.observerHasRun)return;Bd.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(Bd.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)}`),Bd.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 ap=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(h.homedir(),".claude","projects");await R.access(r);const o=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await R.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await R.stat(s)).isDirectory())continue;const r=(await R.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 R.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{Bd.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&Bd.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 R.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{Bd.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 l=await findNewSessions(s),u=l["claude-code"]||[],d=l.codex||[],m=u.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${u.length} new, codex=${d.length} new`),0===m){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=e.length+t.length,r=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);Bd.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(u.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>u.includes(e.id));n.push(...e)}if(d.length>0){const e=(await this.findCodexSessions()).filter(e=>d.includes(e.id));r.push(...e)}const g=n.length+r.length;dlog(`[Import] total sessions: ${g} (claude-code: ${n.length}, codex: ${r.length})`),Bd.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const p=[{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 p){Bd.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const h=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${h.length} batches`);const f=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});Bd.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${h.length} batch${1===h.length?"":"es"}`});try{const o=getApiBaseUrl(),s=new Tl({baseUrl:o});let a=!0;for(let e=0;e<h.length;e++){const t=h[e],n=e+1,r=h.length;r>1&&Bd.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),i=new zd({request:s,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await i.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),Bd.markLearningComplete(),await f,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(),l=[];if(n.length>0&&l.push(`Claude Code (${n.length})`),r.length>0&&l.push(`Codex (${r.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),Bd.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:g,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 Bd.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${l.join(" + ")}`,learningCount:i.totalLearnings,categories:i.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:g,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),Bd.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 R.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")}},ip=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),cp=__name(e=>{const[t,n]=z({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return H(()=>{Bd.reset(),Bd.markImportStarted(),(async()=>{try{const t=await Promise.race([ap.importAndLearn(),ip(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");_t();var lp=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{X((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");_t(),xn();var up=__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{Bd.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{Bd.reset(),e()}}_t(),xn(),_t(),xn(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var dp=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=W(n),o=V(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=V(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=V(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=V(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current())},[e]),l=V(async()=>{dlog("[Handler] demo complete → done"),e("done"),await markDemoShown(),await completeOnboarding(()=>r.current())},[e]),u=V(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:l,handleSkip:u}},"useOnboardingHandlers");_t(),xn();var mp=__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");_t(),_t();var gp=__name(({error:e})=>q.createElement(K,{padding:1},q.createElement(K,{flexDirection:"column",borderColor:"red",padding:1},q.createElement(K,{marginBottom:1},q.createElement(J,null,"Error initializing onboarding: ",e)),q.createElement(K,null,q.createElement(J,null,"Continuing without onboarding...")))),"OnboardingError");_t(),_t();var pp=[{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}],hp=__name(({onComplete:e})=>{const[t,n]=z(0),[r,o]=z(!1),s=t>=pp.length;H(()=>{if(t>=pp.length)return;if(r)return;const e=pp[t],o=setTimeout(()=>{n(e=>Math.min(e+1,pp.length))},e.duration);return()=>clearTimeout(o)},[t,r]),X((t,r)=>{r.escape?e():s?(r.return||" "===t)&&e():" "===t?o(e=>!e):r.return&&n(e=>Math.min(e+1,pp.length))});const a=pp.slice(0,t);return q.createElement(K,{flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:"cyan"},"Meet Your Coding Taste")),q.createElement(K,null,q.createElement(J,null,"Command Code learns your coding style as you work.")),q.createElement(K,null,q.createElement(J,null,"Here's how your preferences evolve in real-time:")),q.createElement(K,{flexDirection:"column",marginY:1},0===a.length&&!s&&q.createElement(J,{dimColor:!0},"Starting demo..."),a.map((e,t)=>"user"===e.type?q.createElement(K,{key:t},q.createElement(J,{color:"white"},`${ve.pointer} ${e.text}`)):q.createElement(K,{key:t,marginBottom:1,marginTop:0,marginLeft:1},q.createElement(K,null,q.createElement(J,null,"⎿"),q.createElement(K,{flexDirection:"column",marginLeft:2,marginTop:0},q.createElement(J,{color:"green"},e.text),e.details&&q.createElement(J,{dimColor:!0},"Saved(",e.details,")")))))),s&&q.createElement(K,{flexDirection:"column",marginY:1,width:80},q.createElement(K,null,q.createElement(J,{color:"green",bold:!0},"Demo Complete!"," ")),q.createElement(J,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."),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Press Enter to get started →"))),!s&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"," ",r?"(paused)":"")))},"TasteDemoComponent");_t(),Ot();var fp=__name(()=>`(run /${Ct.LEARN_TASTE} anytime)`,"getSkipHint"),yp=__name(()=>q.createElement(J,null,"Skip for now"," ",q.createElement(J,{dimColor:!0},fp())),"SkipOptionText"),wp=__name(({sessionCount:e,agentSessions:t,onImport:n,onDemo:r,onSkip:o,demoShown:s=!1})=>{const[a,i]=z(1),l=s?2:3,u=s?2:3;return X((e,t)=>{if(t.escape)o();else if(t.upArrow)i(e=>1===e?l:e-1);else if(t.downArrow)i(e=>e===l?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()}),q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},q.createElement(J,{color:"cyan",bold:!0},"Build Your Coding Taste"),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),q.createElement(K,{marginTop:1},q.createElement(J,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:1===a?"cyan":"gray"},1===a?ve.pointer:" "," 1. Yes, learn from my sessions (recommended)")),!s&&q.createElement(K,null,q.createElement(J,{color:2===a?"cyan":"gray"},2===a?ve.pointer:" "," ","2. No, show me a demo instead")),q.createElement(K,null,q.createElement(J,{color:a===u?"cyan":"gray"},a===u?ve.pointer:" "," ",u,". ",q.createElement(yp,null)))),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice"),Ep=__name(({onDemo:e,onSkip:t})=>{const[n,r]=z(1);return X((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()}),q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",padding:1},q.createElement(J,{color:"cyan",bold:!0},"No Previous Sessions Found"),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,null,"No previous sessions found to analyze."),q.createElement(K,{marginTop:1},q.createElement(J,null,"Would you like to see how taste learning works?"))),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:1===n?"cyan":"gray"},1===n?ve.pointer:" "," 1. Yes, show me a demo")),q.createElement(K,null,q.createElement(J,{color:2===n?"cyan":"gray"},2===n?ve.pointer:" "," 2."," ",q.createElement(yp,null)))),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"NoSessionsChoice");_t(),_t();var bp=__name(({error:e})=>q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"red",paddingX:2,paddingY:1,marginBottom:2},q.createElement(J,{color:"red",bold:!0},"Oops, something went wrong:"),q.createElement(K,{marginTop:1},q.createElement(J,null,e))),"ErrorSection");_t(),_t(),_t(),_t(),_t();var Sp=[ve.bullet,ve.squareSmallFilled,ve.lozenge,ve.star,ve.triangleRight,ve.triangleUp,ve.circleFilled,ve.pointer],vp=__name(()=>q.createElement(J,{backgroundColor:"green",color:"black"}," TASTE "),"TasteBadge"),Cp=["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"],kp=__name(()=>{const[e,t]=z(()=>Math.floor(Math.random()*Cp.length));H(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*Cp.length))},2e3);return()=>clearInterval(e)},[]);const n=Cp[e];return q.createElement(J,{color:"yellow"},n,"...")},"PulsingText"),Pp=__name(e=>String(e).padStart(3," "),"padNum"),Tp=__name(e=>Sp[e%Sp.length],"getSymbol"),Ap=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${Pp(t)} ↓${Pp(n)} (↑↓ scroll)`,"buildStatusLine"),xp=__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]),X((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 l=e.slice(t,t+10),u=t,d=s-t-10;return q.createElement(K,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&q.createElement(J,{dimColor:!0},Ap(s,u,d,r)),l.map((e,n)=>{const r=t+n;return q.createElement(K,{key:r,marginBottom:0},q.createElement(J,{dimColor:!0},Tp(r)," ",e))}))},"ScrollableInsights"),Ip=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:l})=>{if(a)return q.createElement(K,{flexDirection:"column",marginBottom:0},q.createElement(vp,null),q.createElement(K,{marginTop:0},q.createElement(J,{dimColor:!0},"⎿"),q.createElement(K,{marginLeft:2},i?q.createElement(J,{color:"green"},"learned your coding taste"):q.createElement(kp,null))));const u=__name(()=>{const[e,t]=z(!0);return H(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),q.createElement(J,{color:"yellow"},e?ve.circleFilled:ve.circle)},"PulsingDot"),d=__name(()=>r?q.createElement(J,{color:"green"},ve.nodejs):n?q.createElement(u,null):q.createElement(J,{dimColor:!0},ve.circle),"getStatusIcon"),m=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||m?q.createElement(K,{flexDirection:"column",marginBottom:0},(n||r)&&q.createElement(K,{marginBottom:0},q.createElement(K,{marginRight:1},d()),q.createElement(J,{color:r?"white":n?"yellow":"dim"},e)),r&&t&&(!l||0===l.learningCount)&&q.createElement(K,{marginLeft:3,marginBottom:0},q.createElement(J,{dimColor:!0},t)),o.length>0&&q.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>q.createElement(J,{key:t,dimColor:!0},`${ve.bullet} ${e}`))),s.length>0&&q.createElement(xp,{insights:s}),r&&l&&l.learningCount>0&&q.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},q.createElement(K,{marginBottom:1,flexDirection:"row"},q.createElement(J,null,"⎿"),q.createElement(K,{marginLeft:2},q.createElement(J,{color:"green"},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),q.createElement(K,{flexDirection:"column",marginLeft:1},q.createElement(J,{dimColor:!0},ve.pointerSmall," Stored in"," ",l.storage),q.createElement(J,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),_p=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return q.createElement(K,{flexDirection:"column",marginBottom:1},e.map((e,n)=>q.createElement(K,{key:e.id,marginLeft:0===n?0:3},q.createElement(Ip,{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"),Np=__name(({steps:e})=>q.createElement(_p,{steps:e}),"ProgressSection");_t();var $p=__name(({isImporting:e=!1,waitingForInput:t=!1})=>q.createElement(q.Fragment,null,e&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"ESC to cancel")),t&&q.createElement(K,{marginTop:1},q.createElement(J,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");_t();var Rp=[{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"}}],Dp=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=op(Rp),{isImporting:s,waitingForInput:a,error:i}=cp(t);return lp({onEscape:e,onEnter:__name(()=>{a&&(i&&n?n():e())},"onEnter"),enabled:s||a}),q.createElement(K,{flexDirection:"column",padding:1},o&&q.createElement(bp,{error:o}),!o&&q.createElement(Np,{steps:r}),q.createElement($p,{isImporting:s,waitingForInput:a}))},"ImportProgress"),Op=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onDemoComplete:a,onDemo:i,onSkip:l})=>"asking"===e?"has_sessions"!==t?.reason?q.createElement(Ep,{onDemo:i,onSkip:l}):q.createElement(wp,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onDemo:i,onSkip:l,demoShown:t.demoShown}):"learning"===e?q.createElement(Dp,{onComplete:r,onError:o,onErrorDismiss:s}):"demo"===e?q.createElement(hp,{onComplete:a}):null,"OnboardingStepRenderer"),Lp=__name(({onComplete:e,autoLearn:t=!1})=>{H(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=up({autoLearn:t,onShouldSkip:e}),{step:s,setStep:a}=mp({conditions:n,autoLearn:t}),{handleImportStart:i,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleDemoComplete:m,handleSkip:g}=dp({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?q.createElement(gp,{error:r}):"done"===s?null:q.createElement(Op,{step:s,conditions:n,onImportStart:i,onImportComplete:l,onImportError:u,onErrorDismiss:d,onDemoComplete:m,onDemo:()=>a("demo"),onSkip:g})},"TasteOnboarding");_t(),Ot();var Mp=__name(({onTrust:e,onExit:t})=>{const{exit:n}=ee(),[r,o]=z(1),s=process.cwd().replace(process.env.HOME||"","~");return X((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())}),q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",padding:1},q.createElement(J,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),q.createElement(K,{marginTop:1},q.createElement(J,{color:"gray"},s)),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),q.createElement(K,{marginTop:1},q.createElement(J,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:1===r?"cyan":"gray"},1===r?ve.pointer:" "," 1. Yes, proceed")),q.createElement(K,null,q.createElement(J,{color:2===r?"cyan":"gray"},2===r?ve.pointer:" "," 2. No, exit"))))},"TrustPrompt");_t(),$n(),Rn();var Fp=__name(({onComplete:e,onCancel:t})=>{const[n,r]=z(!1),[o,s]=z(""),{authState:a,statusMessage:i,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:g}=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 X((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.");g()}}),n?q.createElement(In,{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}`)}}):q.createElement(to,{authState:a,statusMessage:i,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");_t(),_t(),Dn();var Up=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),jp=__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"),Bp=__name(({icon:e,label:t,children:n})=>q.createElement(J,null,q.createElement(J,{color:"cyan"},e," "),q.createElement(J,{dimColor:!0},t.padEnd(12)),n),"Row"),qp=__name(({title:e})=>q.createElement(J,null,q.createElement(J,{color:"gray"},"───"),q.createElement(J,{color:"white"}," ",e," "),q.createElement(J,{color:"gray"},"─".repeat(35))),"Header"),zp=__name(({title:e,marginTop:t=0,children:n})=>q.createElement(K,{flexDirection:"column",marginTop:t},q.createElement(qp,{title:e}),q.createElement(K,{flexDirection:"column",paddingY:1},n)),"Section"),Wp=__name(({cpuCount:e,totalMem:t})=>q.createElement(zp,{title:"System Information"},q.createElement(Bp,{icon:Se.bullet,label:"Date"},q.createElement(J,null,formatDate())),q.createElement(Bp,{icon:Se.pointer,label:"Platform"},q.createElement(J,{color:"green"},Up(h.platform())),q.createElement(J,{dimColor:!0}," ","(",h.platform(),", ",h.arch(),")")),q.createElement(Bp,{icon:Se.triangleUp,label:"Hostname"},q.createElement(J,null,h.hostname())),q.createElement(Bp,{icon:Se.bullet,label:"User"},q.createElement(J,{color:"yellow"},h.userInfo().username)),q.createElement(Bp,{icon:Se.bullet,label:"CPUs"},q.createElement(J,{color:"magenta"},e," cores")),q.createElement(Bp,{icon:Se.bullet,label:"Memory"},q.createElement(J,{color:"cyan"},t," GB")),q.createElement(Bp,{icon:Se.play,label:"Uptime"},q.createElement(J,null,jp(h.uptime()))),q.createElement(Bp,{icon:Se.arrowRight,label:"Home"},q.createElement(J,{dimColor:!0},h.homedir())),q.createElement(Bp,{icon:Se.pointer,label:"Shell"},q.createElement(J,null,process.env.SHELL||"N/A")),q.createElement(Bp,{icon:Se.bullet,label:"Node"},q.createElement(J,{color:"green"},process.version))),"SystemInfoSection"),Hp=__name(({cpus:e})=>q.createElement(zp,{title:"CPU Details",marginTop:1},e.map((e,t)=>q.createElement(Bp,{key:t,icon:Se.bullet,label:`Core ${t}`},q.createElement(J,null,e.model.trim()),q.createElement(J,{color:"yellow"}," @ ",e.speed," MHz")))),"CPUDetailsSection"),Vp=__name(({networkInterfaces:e})=>q.createElement(zp,{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)=>q.createElement(Bp,{key:`${e}-${n}`,icon:Se.bullet,label:e},q.createElement(J,{color:"green"},t.address))):null})),"NetworkSection"),Gp=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>q.createElement(K,{flexDirection:"column"},q.createElement(J,null,"System Information"),q.createElement(J,null,"─".repeat(40)),q.createElement(J,null,"Date ",formatDate()),q.createElement(J,null,"Platform ",Up(h.platform())," (",h.platform(),","," ",h.arch(),")"),q.createElement(J,null,"Hostname ",h.hostname()),q.createElement(J,null,"User ",h.userInfo().username),q.createElement(J,null,"CPUs ",e.length," cores"),q.createElement(J,null,"Memory ",t," GB"),q.createElement(J,null,"Uptime ",jp(h.uptime())),q.createElement(J,null,"Home ",h.homedir()),q.createElement(J,null,"Shell ",process.env.SHELL||"N/A"),q.createElement(J,null,"Node ",process.version),r&&q.createElement(q.Fragment,null,q.createElement(J,null,"\n","CPU Details"),q.createElement(J,null,"─".repeat(40)),e.map((e,t)=>q.createElement(J,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),q.createElement(J,null,"\n","Network"),q.createElement(J,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>q.createElement(J,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Kp=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>q.createElement(K,{flexDirection:"column"},q.createElement(Wp,{cpuCount:e.length,totalMem:t}),r&&q.createElement(Hp,{cpus:e}),r&&q.createElement(Vp,{networkInterfaces:n})),"StyledInfo"),Jp=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=ee();H(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=h.cpus(),o=h.networkInterfaces(),s=Math.round(h.totalmem()/1024/1024/1024);return t?q.createElement(Gp,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e}):q.createElement(Kp,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e})},"InfoUI"),Qp={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},Yp=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),Zp=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(Yp("__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"),Xp=__name(()=>{const e=Zp();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&Qp[t]?Qp[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),eh=__name(()=>{if("win32"===f.platform()){const e=process.env.COMSPEC;return e?l(e):process.env.SHELL?l(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=_(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=l(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?l(e):"N/A"},"getShellName"),th=__name(()=>{const e=Zp();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),nh=__name(()=>{try{const e=_("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:Up(f.platform()),terminal:Xp(),shell:eh(),version:nh(),ide:th()}}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"),_t(),_t(),xn();var rh=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(h.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await R.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 R.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await R.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 R.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await R.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await R.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 rh}__name(createHistoryManager,"createHistoryManager"),_t();var oh=__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"),sh=__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,l=n.has(a);let u,d;i?(u="●",d="cyan"):l?(u="✓",d="green"):(u="○",d="gray"),s.push(q.createElement(J,{key:a},q.createElement(J,{color:d},u),q.createElement(J,{color:i?"cyan":void 0}," ",o.header),a<e.length-1?q.createElement(J,{dimColor:!0}," | "):null))}),!o){const e=r;s.push(q.createElement(J,{key:"review"},q.createElement(J,{dimColor:!0}," | "),q.createElement(J,{color:e?"cyan":"gray"},e?"●":"○"),q.createElement(J,{color:e?"cyan":void 0,bold:e}," ","Review")))}return q.createElement(K,null,s)},"TabIndicator"),ah=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,o]=z(0),[s,a]=z(new Map),i=W(new Map),[l,u]=z(""),[d,m]=z(new Set),[g,p]=z(null),[h,f]=z(!1),[y,w]=z(!1),[E,b]=z(!1),[S,v]=z(null),[C,k]=z(!1),P=e[r],T=P?.multiSelect??!1,A=s.get(r),x=P?[...P.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],I=x.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),_=new Map(I.map((e,t)=>[e.label,x[t]])),N=__name(e=>{"submit"===e.value?M():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),$=__name(()=>{if(!A||0===A.length)return 0;const e=A[0],t=P.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),R=__name(e=>{if(!h)if(T){const t=oh(e.value,P.options.length-1);if(null===t)return;const n=P.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=oh(e.value,P.options.length-1);if(null===t)return;f(!0);const n=P.options[t]?.label||"";L([n])}},"handleSelect"),D=__name(()=>{if(h)return;f(!0);const e=Array.from(d);L(e)},"handleMultiSelectDone"),O=__name(()=>{if(!h&&l.trim())if(T){const e=new Set(P.options.map(e=>e.label));m(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(l.trim()),n})}else f(!0),L([l.trim()])},"handleOtherSubmit"),L=__name(t=>{i.current.set(r,t);const s=new Map(i.current);a(s);const l=__name(t=>{const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);u(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;l(e),o(e),f(!1),b(!1),v(null),k(!1)}else if(e.every((e,t)=>s.has(t))){if(n&&1===e.length)return void M();m(new Set),u(""),w(!0),f(!1)}else{const t=e.findIndex((e,t)=>!s.has(t));-1!==t&&(l(t),o(t)),f(!1),b(!1),v(null),k(!1)}},"finishQuestion"),M=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:i.current.get(t)||[]}));t({answers:n})},"submitAnswers"),F=__name(t=>{w(!1),o(t),k(!1),b(!1),v(null);const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}},"editQuestion"),U=__name(t=>{if(t<0||t>=e.length)return;T&&(d.size>0?i.current.set(r,Array.from(d)):i.current.delete(r),a(new Map(i.current))),f(!1),b(!1),v(null),k(!1);const n=e[t],s=i.current.get(t);if(n?.multiSelect&&s){m(new Set(s));const e=s.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==s?.length)u("");else{const e=s[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}o(t)},"navigateToQuestion"),j=__name(()=>{if(!g||!T)return;if("done"===g.value)return;const e=oh(g.value,P.options.length-1);if(null===e)return;const t=P.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return X((t,o)=>{if(" "===t&&T&&!E&&j(),"d"!==t||!T||E||y||D(),!y&&!h){if(o.downArrow&&!E&&!C&&!n&&g&&I.length>0&&g.value===I[I.length-1]?.value&&b(!0),o.upArrow&&!E&&!C&&g&&I.length>0&&g.value===I[0]?.value&&(T?k(!0):n||(b(!0),v(I.length-1))),o.upArrow&&E){b(!1),v(I.length-1);const e=I[I.length-1];e&&p(e)}if(o.downArrow&&E)if(b(!1),T)k(!0);else{v(0);const e=I[0];e&&p(e)}if(o.upArrow&&C&&(k(!1),b(!0)),o.downArrow&&C){k(!1),v(0);const e=I[0];e&&p(e)}o.return&&C&&T&&D()}if(h||E||C||(y?o.leftArrow&&F(e.length-1):o.leftArrow&&r>0?U(r-1):o.rightArrow&&(r<e.length-1?U(r+1):(T&&(d.size>0?i.current.set(r,Array.from(d)):i.current.delete(r),a(new Map(i.current))),w(!0)))),o.escape&&!h)if(y)w(!1);else if(E){b(!1);const e=S??I.length-1;v(e);const t=I[e];t&&p(t)}else if(C){k(!1);const e=I[I.length-1];e&&p(e)}}),P||y?y?q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(sh,{questions:e,currentIndex:e.length,answeredQuestions:new Set(s.keys()),isReviewPage:!0})),e.map((e,t)=>q.createElement(K,{key:t,marginBottom:1,flexDirection:"column"},q.createElement(J,{dimColor:!0},t+1,". ",e.question),q.createElement(J,{color:"green"}," ",s.get(t)?.join(", ")||"No answer"))),q.createElement(Ke,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:N,initialIndex:0,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"cyan"},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>q.createElement(J,{color:t?"cyan":"white"},e)}),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},ve.arrowLeft," to go back and edit"))):q.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(sh,{questions:e,currentIndex:r,answeredQuestions:new Set(s.keys()),isReviewPage:!1,hideReview:n})),q.createElement(K,{marginBottom:1},q.createElement(J,{bold:!0},P.question)),E||C?q.createElement(K,{flexDirection:"column"},I.map((e,t)=>{const n=_.get(e.label),r=T&&n&&d.has(n.label),o=!T&&n&&A?.includes(n.label),s=r||o;return q.createElement(K,{key:t,flexDirection:"column"},q.createElement(K,null,q.createElement(J,null," "),q.createElement(J,{color:s?"green":"white"}," ",t+1,"."," "),T&&(s?q.createElement(J,{color:"green"},"[",ve.tick,"]"," "):q.createElement(J,{dimColor:!0},"[ ] ")),q.createElement(J,{color:s?"green":"white"},n?.label||""),!T&&s&&q.createElement(J,{color:"green"}," ",ve.tick)),n?.description&&q.createElement(K,null,q.createElement(J,null," "),q.createElement(J,{dimColor:!0},T?" ":" ",n.description)))})):q.createElement(Ke,{key:`${r}-${S??"default"}`,items:I,initialIndex:S??$(),onSelect:R,onHighlight:p,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"cyan"},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=_.get(e),r=T&&n&&d.has(n.label),o=!T&&n&&A?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",l=a?.[2]||e;return q.createElement(K,{flexDirection:"column"},q.createElement(K,null,q.createElement(J,{color:t?"cyan":s?"green":"white"}," ",i,"."," "),T&&(s?q.createElement(J,{color:"green"},"[",ve.tick,"]"," "):q.createElement(J,{dimColor:!0},"[ ] ")),q.createElement(J,{color:t?"cyan":s?"green":"white"},l),!T&&s&&q.createElement(J,{color:"green"}," ",ve.tick)),n?.description&&q.createElement(J,{dimColor:!0},T?" ":" ",n.description))}}),!n&&q.createElement(K,null,q.createElement(J,{color:"cyan"},E?ve.pointer:" "),q.createElement(J,{color:E?"cyan":void 0}," ",I.length+1,"."," "),T&&(d.has(l.trim())?q.createElement(J,{color:"green"},"[",ve.tick,"] "):q.createElement(J,{dimColor:!0},"[ ] ")),q.createElement(nt,{value:l,onChange:e=>{const t=l.trim();u(e),T&&m(n=>{const r=new Set(n);return t&&r.has(t)&&r.delete(t),e.trim()&&r.add(e.trim()),r})},onSubmit:O,placeholder:"Type something...",focus:E})),T&&q.createElement(K,null,q.createElement(J,{color:"cyan"},C?ve.pointer:" "),q.createElement(J,{color:C?"cyan":void 0,bold:C}," ",r===e.length-1?"Submit":"Next")),e.length>1&&q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function LiveAgentStatusInner({entry:e}){const t=Du(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||[],[l,u]=z(".");return H(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),q.createElement(K,{flexDirection:"column",marginBottom:1,width:"90%"},q.createElement(K,null,q.createElement(J,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${t} `),o&&q.createElement(J,null," ","(",o,")")),q.createElement(K,{columnGap:1,marginLeft:1},q.createElement(J,null,"⎿"," "),q.createElement(J,{color:"gray"},"Running (",formatTime2(a)," | ",formatTokens(s),")",l)),i.length>0&&q.createElement(K,{flexDirection:"column",marginLeft:1},i.map((e,t)=>{const n=Du(e.name);return q.createElement(K,{key:t,columnGap:1},q.createElement(J,{color:"gray"},"⎿"),q.createElement(J,{color:"gray"}," ",n),e.input&&q.createElement(J,{color:"gray"},"(",e.input,")"))})))}function LiveAgentStatus({entry:e}){return"tool"!==e.role?null:q.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:Kl,capabilities:{},clientInfo:Jl}})});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}_t(),Dn(),__name(LiveAgentStatusInner,"LiveAgentStatusInner"),__name(LiveAgentStatus,"LiveAgentStatus"),_t(),_t(),_t(),Cr(),zr(),_t(),Tr(),xn(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient");var ih=__name(({onClose:e})=>{const[t,n]=z([]),[r,o]=z(!0),[s,a]=z(0),[i,l]=z("list"),[u,d]=z(null);H(()=>{m()},[]);const m=__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"),g=G(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),p=g[s]??null;X((t,n)=>{n.ctrl&&"c"===t?e():n.escape?"actions"===i||"confirm-remove"===i?(l("list"),d(null)):e():"list"===i&&(n.upArrow&&(a(e=>Math.max(0,e-1)),d(null)),n.downArrow&&(a(e=>Math.min(g.length-1,e+1)),d(null)),n.return&&p&&(l("actions"),d(null)))});const h=__name(e=>{switch(e){case"connected":return q.createElement(J,{color:"green"},"✓");case"authenticated":return q.createElement(J,{color:"cyan"},"✓");case"requires_auth":return q.createElement(J,{color:"yellow"},"⚠");case"error":return q.createElement(J,{color:"red"},"✗");default:return q.createElement(J,{color:"gray"},"○")}},"getStatusIcon"),f=__name(e=>{switch(e.status){case"connected":return"connected"+(void 0!==e.toolCount?` · ${e.toolCount} tools`:"");case"authenticated":return"authenticated · not connected";case"requires_auth":return"requires authentication";case"error":return e.error||"error";default:return"not connected"}},"getStatusText"),y=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),w=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),E=__name(async e=>{if(p)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)"remove"!==e.value||l("confirm-remove");else{if(!p.config.oauth)return void d({text:"No OAuth configured for this server",color:"yellow"});d({text:`Authenticating ${p.name}...`,color:"cyan",loading:!0});try{const e={authorizationUrl:p.config.oauth.authorizationUrl,tokenUrl:p.config.oauth.tokenUrl,clientId:p.config.oauth.clientId,clientSecret:p.config.oauth.clientSecret,scopes:p.config.oauth.scopes},t=await performOAuthFlow(p.name,e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`✓ Authenticated with ${p.name}`,color:"green"});try{const e=getMcpConnectionManager();await e.reconnectServer(p.name)}catch{}await m()}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 ${p.name}...`,color:"cyan",loading:!0});try{const e=getMcpConnectionManager();await e.reconnectServer(p.name),d({text:`✓ Connected to ${p.name}`,color:"green"}),await m()}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 l("list")},"handleActionSelect"),b=__name(async e=>{if(p)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===p.status&&await e.disconnectServer(p.name),await removeMcpServer({name:p.name,scope:p.scope}),l("list"),await m(),a(e=>Math.min(e,Math.max(0,g.length-2)))}catch(e){d({text:`✗ Failed: ${e instanceof Error?e.message:String(e)}`,color:"red"}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"#E4CCFF",bold:!0},"Manage MCP servers"),q.createElement(J,{dimColor:!0},"Loading..."));if("confirm-remove"===i&&p)return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"red",bold:!0},"Remove ",p.name,"?"),q.createElement(J,{dimColor:!0},"This will remove the server from ",p.scope," config."),q.createElement(K,{marginTop:1},q.createElement(Ke,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:b,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"}," ",t)})),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===i&&p){const e=[];return"connected"===p.status?e.push({label:"Connected",value:"connected"}):e.push({label:"Connect",value:"connect"}),p.config.oauth&&("authenticated"===p.status||"connected"===p.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"}),q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"#E4CCFF",bold:!0},p.name),q.createElement(K,null,h(p.status),q.createElement(J,{dimColor:!0}," ",f(p))),q.createElement(K,{marginTop:1},q.createElement(Ke,{items:e,onSelect:E,indicatorComponent:({isSelected:e})=>q.createElement(J,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>q.createElement(J,{color:e?"white":"gray"}," ",t)})),u&&q.createElement(K,{marginTop:1},u.loading&&q.createElement(J,{color:u.color},q.createElement(Re,{type:"dots"})," "),q.createElement(J,{color:u.color},u.text)),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to go back")))}let S=null;return q.createElement(K,{flexDirection:"column"},q.createElement(J,{color:"#E4CCFF",bold:!0},"Manage MCP servers"),q.createElement(J,{dimColor:!0},t.length," ",1===t.length?"server":"servers"),0===t.length?q.createElement(K,{marginTop:1,flexDirection:"column"},q.createElement(J,{dimColor:!0},"No MCP servers configured."),q.createElement(J,{dimColor:!0},'Use "cmd mcp add" to add a server.'),q.createElement(J,{dimColor:!0},"Docs: https://commandcode.ai/docs/mcp")):q.createElement(K,{marginTop:1,flexDirection:"column"},g.map((e,t)=>{const n=e.scope!==S;S=e.scope;const r=t===s;return q.createElement(q.Fragment,{key:e.name},n&&q.createElement(K,{marginTop:0===t?0:1},q.createElement(J,{bold:!0},y(e.scope)),q.createElement(J,{dimColor:!0}," (",w(e.scope),")")),q.createElement(K,{paddingLeft:1},q.createElement(J,{color:r?"white":"gray"},r?"› ":" "),q.createElement(J,{color:r?"white":void 0,bold:r},e.name),q.createElement(J,{dimColor:!0}," · "),h(e.status),q.createElement(J,{color:"connected"===e.status?"green":"authenticated"===e.status?"cyan":"requires_auth"===e.status?"yellow":"gray"}," ",f(e))))})),u&&q.createElement(K,{marginTop:1},u.loading&&q.createElement(J,{color:u.color},q.createElement(Re,{type:"dots"})," "),q.createElement(J,{color:u.color},u.text)),q.createElement(K,{marginTop:1},q.createElement(J,{dimColor:!0},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");xn();var{setText:ch}=Oe,{runIDESetup:lh}=await Promise.resolve().then(()=>(Vr(),Hr));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 uh=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:o,updateFailedInfo:s,initialPrompt:a,skipOnboarding:i=!1,initialPermissionMode:l})=>{const{exit:u}=ee(),[d,m]=z(""),[g,p]=z("Ready..."),h=W(!1),[f,y]=z(null),[w,E]=z(o);H(()=>{if(w){const e=setTimeout(()=>{E(null)},3e4);return()=>clearTimeout(e)}},[w]);const{stdout:b}=Z(),[S,v]=z(!1),[C,k]=z(!1),[P,T]=z(!1),[A,x]=z(!1),[I,_]=z(!1),[N,$]=z(!1),[R,D]=z(!1),[O,L]=z(!1),[M,F]=z(!1),[U,j]=z(null),[B,G]=z(null),[Q,Y]=z(getConfiguredModel()),[te,ne]=z(!1),[re,oe]=z(!1),[ae,ie]=z(!1),ce=W(null),le=W(null),[ue,de]=z(0),[me,ge]=z(!1),{executeBash:pe,executionState:he}=Xd(),[fe,ye]=z(""),[we,Ee]=z([]),[be,Se]=z([]),[ve,Ce]=z(!1),[ke,Pe]=z([]),[Te,Ae]=z(crypto.randomUUID()),[xe,Ie]=z(!1),[_e,Ne]=z(!1),[$e,Re]=z(!1),De=W(null),[Oe,Le]=z(!1),[Me,Fe]=z(!1),[Ue,je]=z(!0),[Be,qe]=z(!1),[ze,We]=z(!1),[He,Ve]=z(null),[Ge,Ke]=z(!1),Je=W(!1),[Qe,Ye]=z(!1),[Ze,Xe]=z(0),[et,tt]=z(null),[nt,rt]=z(null),[ot,st]=z(null),at=W(!1),it=W(!1),ct=W(ot);H(()=>{ct.current=ot},[ot]);const[lt,ut]=z(!1),[dt,mt]=z(""),[gt,pt]=z(!1),[ht,ft]=z(()=>l||(r?"auto-accept":"standard")),yt=W(ht);H(()=>{yt.current=ht},[ht]);const[Et,bt]=z(""),St=W(null),vt=W(null),Pt=__name(()=>{St.current&&clearTimeout(St.current),vt.current&&clearTimeout(vt.current),ce.current&&clearTimeout(ce.current),le.current&&clearTimeout(le.current)},"cleanupTimers"),[Tt,At]=z(!1),[xt,It]=z(!1),_t=W(null),Nt=W(0),[$t,Dt]=z(null),Ot=V(()=>{_t.current=null,Dt(null),vt.current&&(clearTimeout(vt.current),vt.current=null)},[]);H(()=>{if(Qe){Pt();try{u()}catch{process.exit(0)}}},[Qe,u]);const Lt=V(()=>{We(!0),qe(!1),Ke(!1),nm(),de(e=>e+1),e&&Ie(!0)},[e,t]),Mt=__name(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(e=>{dlog("[MCP] Failed to initialize",e)})},"initializeMcpInBackground"),Ft=__name(async()=>{try{const e=await isTasteLearningEnabled();pt(e),e&&await xm.initializeProject()}catch(e){}},"loadTasteStatus"),Ut=__name(async()=>{const e=await getConfiguredProvider();G(e);const t=await isOAuthEnforced();ne(t)},"loadCurrentProvider"),jt=W([]),Bt=W(null),qt=W(null),[zt,Wt]=z(null),[Ht,Vt]=z(null),{requestShellPermission:Gt,service:Kt,respondToPrompt:Jt,clearSessionPermissions:Qt,setEnabled:Yt}=tm({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")}),Bt.current&&p("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Wt({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),Bt.current&&p("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?p("Permission granted"):p("Permission denied")},"onPermissionResponse")}),Zt=__name(e=>{St.current&&clearTimeout(St.current),bt(e),St.current=setTimeout(()=>{bt(""),St.current=null},5e3)},"showHintMessage");H(()=>()=>Pt(),[]),H(()=>{Kt&&applyAutoAcceptMode({enabled:ht,service:Kt})},[ht,Kt]),H(()=>{(async()=>{if(await Cd.isProjectInitialized())if(Fe(!0),je(!1),Ft(),Ut(),Mt(),t){const e=await Cd.listSessions();if(e.length>0){const t=e[0];An(t.id)}}else e&&Ie(!0);else if(n)if(await Cd.initializeProject(),Fe(!0),je(!1),Ft(),Ut(),Mt(),t){const e=await Cd.listSessions();if(e.length>0){const t=e[0];An(t.id)}}else e&&Ie(!0);else isDirectoryEmpty()?(await Cd.initializeProject(),Fe(!0),je(!1),Ft(),Ut(),Mt()):(Le(!0),je(!1))})()},[e,t,n,u]),H(()=>{i||triggerTasteOnboarding({projectTrusted:Me,onboardingComplete:ze,isOnboardingMode:Be,tasteOnboardingCheckedRef:Je,setIsOnboardingMode:qe})},[Me,ze,Be,i]),H(()=>{if(Be&&!He){const e=ku();Ve(e.id),Ee(t=>[...t,e])}else!Be&&He&&(Ee(e=>e.filter(e=>e.id!==He)),Ve(null))},[Be,He]),H(()=>{jt.current=ke},[ke]);const Xt=V(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)),Ee(t=>[...t,e])):Ee(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...jt.current];return jt.current=[],Pe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Xe(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{tt(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{y(e)},"onRetryUpdate"),onProviderChange:__name(e=>{G(e)},"onProviderChange"),onStatusUpdate:__name(e=>{h.current=!0,p(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{if("shell_command"===e&&Kt){const e={command:t.command||"",args:t.args,workingDirectory:t.directory,description:n??buildFallbackDescription(t)};return Kt.requestShellPermission(e).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)=>{Vt({params:e,resolve:t,reject:n}),p("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const t=ct.current;return t?{sessionId:e||Te,secret:t.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>yt.current,"getPermissionMode")}),[ht,Te,Kt]);H(()=>{(async()=>{if(B&&"anthropic"===B&&te)try{await rn.getValidAccessToken()||p("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){p("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[B,te]),H(()=>{if(!ve)return void(h.current=!1);if(null!==f)return;const e=setInterval(()=>{h.current||p(Ru())},7e3);return()=>clearInterval(e)},[ve,f]);const en=V(()=>{const e=!ve&&!zt&&!Ht,t=Bt.current?.hasCheckpoints()??!1;e&&t&&At(!0)},[ve,zt]),tn=V(()=>{if(!Bt.current)return;Bt.current.interrupt(!0);const e=be.length>0;if(Ce(!1),y(null),Se([]),p("Interrupted by user"),!e){const e=Cu("Interrupted by user");Ee(t=>[...t,e])}if(jt.current.length>0){const e=jt.current.join("\n");m(t=>t?e+"\n"+t:e),Pe([]),jt.current=[]}},[be]),nn=__name(()=>{ft(e=>{let t;return t="standard"===e?"auto-accept":"auto-accept"===e?"plan":"standard","auto-accept"===t&&zt&&(Jt({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}),nm(),de(e=>e+1)},"handleToggleAutoAccept");async function getBillingLink(){if(nt)return nt;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return rt(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return rt(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}X((e,t)=>{if(t.shift&&t.tab||"[Z"===e)nn();else if(P||A||I||N||R||O||U||M||Tt||xt||_e)$t&&Ot();else{if(""===e||t.ctrl&&"c"===e){if(ve&&Bt.current)return void tn();const e=Date.now(),t=e-Nt.current;return Nt.current=e,void("ctrl-c"===_t.current&&t<2e3?(vt.current&&(clearTimeout(vt.current),vt.current=null),Ye(!0)):(m(""),_t.current="ctrl-c",Dt("ctrl-c"),vt.current&&clearTimeout(vt.current),vt.current=setTimeout(()=>{_t.current=null,Dt(null),vt.current=null},2e3)))}if(t.ctrl&&"t"===e)return nm(),F(e=>!e),void de(e=>e+1);if(getIsExpandToolShortcut(t,e))return nm(),ge(e=>!e),void de(e=>e+1);if(t.meta&&"p"===e||isAltP(e))$(!0);else{if(t.escape){if(Ht)return Ht.reject(new Error("Question cancelled by user")),Vt(null),void p("Question cancelled");zt?(Jt({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),p("Permission denied")):ve&&Bt.current&&tn()}t.meta||t.ctrl}}}),H(()=>{const e=__name(()=>{nm(),de(e=>e+1)},"handleResize");if(b)return b.on("resize",e),()=>{b.off("resize",e)}},[b]),H(()=>{Bt.current||!Me||xe||$e||(Bt.current=new Kd(Xt(),Te),(async()=>{await hn()})())},[Te,xe,$e,Me]),H(()=>{if(!Me)return;const e=createHistoryManager();return De.current=e,e.init(),()=>{e.cleanup()}},[Me]),H(()=>{a&&Me&&!Ue&&Bt.current&&!xe&&!it.current&&(it.current=!0,on({role:"user",input:a}))},[a,Me,Ue,xe]),__name(getBillingLink,"getBillingLink");const on=__name(async({role:e,input:t,images:n,ideContext:r,displayMessage:o})=>{if(t.length)if(w&&E(null),Xe(0),"bash"===e){if(at.current)return;at.current=!0;const e=Su(t);Ee([...we,e]),m(""),await pe(t,e=>{Ee(e)},()=>{nm(),de(e=>e+1)}),at.current=!1}else{if(ve)return Pe(e=>[...e,o??t]),void m("");if(at.current)return;at.current=!0,Ce(!0),p(Ru()),m("");try{Bt.current&&await Bt.current.sendMessage(t,n,r,o)}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){p("Insufficient credits");const e=await getBillingLink(),t=Cu(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);Ee(e=>[...e,t])}else if(e.message.startsWith("Error:")){p("Error");const t=Cu(e.message);Ee(e=>[...e,t])}else{p("Error");const t=e.message||"An unexpected error occurred",n=Cu(t);Ee(e=>[...e,n])}}finally{Ce(!1),"Interrupted by user"!==g&&"Permission denied"!==g&&"Insufficient credits"!==g&&p("Ready..."),at.current=!1}}},"handleSubmit"),sn=__name(()=>{Ee(e=>[...e,vu("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),an=__name(()=>{const e=yu(`/${Ct.TERMINAL_SETUP}`),t=setupVSCodeTerminal(),n=Pu(t.message,!t.success,t.details);Ee(t=>[...t,e,n])},"handleTerminalSetupCommand"),cn=__name(async()=>{const e=await lh(),t=Tu(e.status,e.ide,e.details);Ee(e=>[...e,t])},"handleIDESetupCommand"),ln=__name(async()=>{if(Ee([]),Se([]),nm(),st(null),ut(!1),mt(""),Bt.current){const e=Bt.current.getSessionManager();e&&await e.deleteShareInfo(),Bt.current=null;const t=crypto.randomUUID();Ae(t),Qt(),Bt.current=new Kd(Xt(t),t)}de(e=>e+1),tt(null),Xe(0)},"handleClearCommand"),un=__name(()=>{Bt.current?Bt.current.hasCheckpoints()?At(!0):Ee(e=>[...e,wu("No checkpoints available. Start sending messages to create checkpoints.")]):Ee(e=>[...e,wu("No active conversation to rewind.")])},"handleRewindCommand"),dn=__name(async e=>{const{messageId:t,mode:n}=e;if(At(!1),Bt.current)try{const e=Bt.current.listCheckpoints().find(e=>e.messageId===t);p("Restoring checkpoint...");const r=await Bt.current.restoreToCheckpoint({messageId:t,mode:n});if(r.success){const t=Bt.current.getSessionManager(),n=Bt.current.getMessages(),o=t.reconstructFeedFromMessages(n);Ee(o),nm(),de(e=>e+1),e&&e.userPrompt&&m(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.";Ee(e=>[...e,wu(a)]),p("Ready...")}else Ee(e=>[...e,Cu(`Failed to restore: ${r.error}`)]),p("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;Ee(e=>[...e,Cu(t)]),p("Ready...")}},"handleRewindSelect"),mn=__name(()=>{At(!1)},"handleRewindCancel"),gn=__name(async()=>{if(Bt.current)if(Bt.current.isRequestInProgress())Ee(e=>[...e,wu("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{Ce(!0),p("Compacting conversation...");const e=await Bt.current.manualCompact();nm(),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.`),Ee(e=>[...e,wu(t)]),Ce(!1),p("Ready..."),tt({current:Bt.current.getContextTokensUsed()||0,limit:_d})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;Ee(e=>[...e,Cu(t)]),Ce(!1),p("Ready...")}else Ee(e=>[...e,wu("No active conversation to compact.")])},"handleCompactCommand"),pn=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return await An(t),{status:"handled"}}const t=parseCommandInput({input:e});if(!t)return{status:"unknown"};const{commandName:n,rawArguments:r,positionalArgs:o}=t;if(Km.has(n)&&r.trim().length>0)return{status:"unknown"};switch(n){case"/exit":return Ye(!0),{status:"handled"};case"/clear":return await ln(),{status:"handled"};case"/help":return sn(),{status:"handled"};case"/share":return fn(),{status:"handled"};case"/unshare":return Pn(),{status:"handled"};case"/taste":return T(!0),{status:"handled"};case"/learn-taste":return await Tn(),{status:"handled"};case"/skills":return x(!0),{status:"handled"};case"/provider":return isInternalTeamFlagEnforced()?_(!0):p("Provider selection not available"),{status:"handled"};case"/model":return $(!0),{status:"handled"};case"/memory":return D(!0),{status:"handled"};case"/resume":return Ie(!0),{status:"handled"};case"/init":return yn(),{status:"handled"};case"/agents":return k(!0),{status:"handled"};case"/mcp":return wn(),{status:"handled"};case"/compact":return await gn(),{status:"handled"};case"/rewind":return un(),{status:"handled"};case"/login":return await bn(),{status:"handled"};case"/logout":return await Cn(),{status:"handled"};case"/feedback":return await kn(),{status:"handled"};case"/terminal-setup":return an(),{status:"handled"};case"/ide":return await cn(),{status:"handled"};case"/add-dir":return Ne(!0),{status:"handled"};case"/review":{const e=r.trim();return await on({input:buildReviewPrompt({prNumber:r}),role:"user",displayMessage:e?`/review ${e}`:"/review"}),{status:"handled"}}}const s=getCustomCommandContent(n);if(s){const e=processCommandTemplate({template:s,rawArguments:r,positionalArgs:o});return await on({input:e.content,role:"user"}),{status:"handled"}}return{status:"unknown"}},"handleCommand"),hn=__name(async()=>{const e=Bt.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&st({url:t.url,secret:t.secret})}},"loadShareInfo"),fn=__name(async()=>{if(Te){if(ot)return await ch(ot.url),p(""),ut(!0),void setTimeout(()=>{ut(!1)},3e3);try{p("Creating share link...");const e=Bt.current?.getMessages()||[],t=Ro.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new Tl({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:wt.ALPHA.SHARE.CREATE,body:{sessionId:Te,messages:t}}),o={url:r.url,secret:r.secret};st(o);const s=Bt.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await ch(r.url),p(""),ut(!0),setTimeout(()=>{ut(!1)},5e3)}catch(e){p(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else p("No active session to share")},"handleShareCommand"),yn=__name(async()=>{try{const e=process.cwd(),t=`Created AGENTS.md at ${await initProjectMemory(e)}. You can now edit it with /memory or open it in your editor.`;Ee(e=>[...e,wu(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;Ee(e=>[...e,wu(t)])}},"handleInitCommand"),wn=__name(()=>{L(!0)},"handleMcpCommand"),En=__name(()=>{L(!1)},"handleMcpClose"),bn=__name(async()=>{const e=Rt();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 Ee(e=>[...e,wu(`Already logged in${t}`)])}It(!0)},"handleLoginCommand"),Sn=V((e,t)=>{It(!1),e?(Ee(e=>[...e,wu(t)]),Bt.current&&Bt.current.refreshRequest()):Ee(e=>[...e,Cu(t)]),p("Ready...")},[]),vn=V(()=>{It(!1),Ee(e=>[...e,wu("Authentication cancelled.")]),p("Ready...")},[]),Cn=__name(async()=>{const e=await performLogout();e.success?(Bt.current&&Bt.current.refreshRequest(),e.wasAuthenticated?e.warnings.length>0?Ee(t=>[...t,wu(`Successfully logged out from Command Code. Warnings: ${e.warnings.join(", ")}`)]):Ee(e=>[...e,wu("Successfully logged out from Command Code.")]):Ee(e=>[...e,wu("Not currently authenticated.")])):Ee(t=>[...t,Cu(`Logout failed: ${e.error}`)])},"handleLogoutCommand"),kn=__name(async e=>{const t=buildGitHubIssueUrl(e);try{await se(t,{wait:!1,background:!0}),Ee(e=>[...e,wu(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`)])}catch(e){Ee(e=>[...e,Cu("Failed to open browser"),vu(createOSC8Link(t,"Open GitHub issue manually"))])}},"handleFeedbackCommand"),Pn=__name(async()=>{if(Te){if(!ot)return mt("NOT SHARED: Session is not currently shared"),void setTimeout(()=>mt(""),5e3);try{p("Removing share link...");const e=new Tl({baseUrl:getApiBaseUrl()});await e.delete({endpoint:wt.ALPHA.SHARE.DELETE,body:{sessionId:Te,secret:ot.secret}});const t=Bt.current?.getSessionManager();t&&await t.deleteShareInfo(),mt("UNSHARED: Sharing has stopped"),p(""),st(null),setTimeout(()=>{mt("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;p(t),setTimeout(()=>p(""),5e3)}}else p("No active session to unshare")},"handleUnshareCommand"),Tn=__name(async()=>{Ke(!0),qe(!0);const e=ku();Ve(e.id),Ee(t=>[...t,e])},"handleLearnCommand"),An=__name(async e=>{const t=crypto.randomUUID();qt.current=t;try{Ee([]),Se([]),Bt.current=null,ft("standard"),Ae(e),Ie(!1),Re(!0),Bt.current=new Kd(Xt(e),e);const{feedEntries:n,corruptedLines:r,totalLines:o}=await Bt.current.loadSession(e);if(qt.current!==t)return;await hn();const s=[];if(0===n.length&&o>0?s.push(Cu(`Session could not be loaded. ${o} lines could not be parsed.`)):0===n.length?s.push(wu("Session loaded but contains no messages.")):(r>0&&s.push(wu(`Warning: ${r} message(s) could not be loaded.`)),s.push(...n)),qt.current!==t)return;Ee(s),nm(),de(e=>e+1)}catch(e){if(qt.current!==t)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";Ee([Cu(`Failed to load session: ${n}. Starting fresh session.`)]),Ie(!1),Re(!1),Ae(crypto.randomUUID())}},"handleSelectSession"),xn=__name(async()=>{Ee([]),Se([]),Bt.current=null,ft("standard"),Ae(crypto.randomUUID()),Ie(!1),Re(!1)},"handleNewSession"),In=__name(async()=>{try{await Cd.initializeProject(),Le(!1),e?(console.log("No conversations found to resume."),Ye(!0)):(Fe(!0),Ft(),Ut())}catch(e){console.error("Failed to initialize project:",e),Le(!1),Ye(!0)}},"handleTrust"),_n=__name(()=>{Ye(!0)},"handleNoTrust"),Nn=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void j({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),G(e),_(!1);const n=getProviderDisplayName(e);p(`Provider set to ${n}`),ce.current&&clearTimeout(ce.current),oe(!0),ce.current=setTimeout(()=>{oe(!1),ce.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),p("Failed to set provider"),_(!1)}},"handleProviderSelect"),$n=__name(()=>{_(!1)},"handleProviderCancel"),Rn=__name(e=>{const t=Object.values(kt).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),Dn=__name(async e=>{try{await setSelectedModel({model:e}),Y(e),$(!1);const t=Rn(e);p(`Model set to ${t}`),le.current&&clearTimeout(le.current),ie(!0),le.current=setTimeout(()=>{ie(!1),le.current=null},5e3)}catch(e){console.error("Failed to set model:",e),p("Failed to set model"),$(!1)}},"handleModelSelect"),On=__name(()=>{$(!1)},"handleModelCancel"),Ln=__name(()=>{if(U){j(null),_(!1),G(U.provider);const e=getProviderDisplayName(U.provider);p(`${e} authentication successful`),ce.current&&clearTimeout(ce.current),oe(!0),ce.current=setTimeout(()=>{oe(!1),ce.current=null},5e3)}},"handleAuthSuccess"),Mn=__name(()=>{j(null)},"handleAuthCancel");if(Qe)return null;if(Oe)return q.createElement(q.Fragment,null,q.createElement(Jg,{staticKey:ue}),q.createElement(Mp,{onTrust:In,onExit:_n}));if(Ue)return null;if(xe)return q.createElement(Zg,{onSelectSession:An,onNewSession:xn});if(!Me)return null;if(Ht)return q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we,showHeader:!0,expandedToolOutput:me,currentModel:Q}),q.createElement(K,{marginY:1},q.createElement(ah,{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"),nm(),de(e=>e+1)):t.startsWith("Yes, exit")&&(ft("standard"),nm(),de(e=>e+1))}if(Ht.params.enterPlanMode){const t=e.answers[0]?.selectedOptions[0];t?.startsWith("Yes")&&(ft("plan"),nm(),de(e=>e+1))}Ht.resolve(e),Vt(null),p("Answers submitted")}})));if(zt){if("shell_command"===zt.toolName){const e=zt.params;return q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we,showHeader:!0,expandedToolOutput:me,currentModel:Q}),be.map(e=>q.createElement(LiveAgentStatus,{key:e.id,entry:e})),q.createElement(K,{marginY:1},q.createElement(ep,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(p("Shell command allowed"),"standard"===ht&&Zt("Use shift+tab to enable auto-accept")):p("Shell command denied")},onToggleAutoAccept:nn})))}if("kill_shell"===zt.toolName){const e=createKillShellPermissionRequest(zt.params);return q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we,showHeader:!0,expandedToolOutput:me,currentModel:Q}),q.createElement(K,{marginY:1},q.createElement(ep,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(p("Process termination allowed"),"standard"===ht&&Zt("Use shift+tab to enable auto-accept")):p("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 q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we,showHeader:!0,expandedToolOutput:me,currentModel:Q}),be.map(e=>q.createElement(LiveAgentStatus,{key:e.id,entry:e})),q.createElement(K,{marginY:1},q.createElement(Gg,{request:e,onResponse:e=>{Jt(e);const t="no"!==e.value;zt.resolve(t),Wt(null),t?(p("File operation allowed"),"standard"===ht&&Zt("Use shift+tab to enable auto-accept")):p("File operation denied")},onToggleAutoAccept:nn})))}}return M?q.createElement(xg,{onClose:()=>{F(!1),de(e=>e+1)}}):P?q.createElement(q.Fragment,null,q.createElement(Jg,{staticKey:ue}),q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"Press Esc to return to conversation")),q.createElement(rp,{onClose:()=>T(!1),onSettingsChange:Ft,staticKey:ue}))):A?q.createElement(q.Fragment,null,q.createElement(Jg,{staticKey:ue}),q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(K,{marginBottom:1},q.createElement(J,{dimColor:!0},"Press Esc to return to conversation")),q.createElement(np,{onClose:()=>x(!1),staticKey:ue}))):q.createElement(K,{flexDirection:"column",width:"100%"},q.createElement(Hg,{staticKey:ue,feed:we.filter(e=>"taste-onboarding"!==e.role),showHeader:!0,expandedToolOutput:me,currentModel:Q}),He&&q.createElement(Lp,{onComplete:Lt,autoLearn:Ge}),be.map(e=>q.createElement(LiveAgentStatus,{key:e.id,entry:e})),q.createElement(RetryMessage,{attempt:f}),!I&&!N&&!U&&!R&&!O&&!C&&!Tt&&!xt&&!_e&&!He&&q.createElement(Ag,{queuedMessages:ke,isProcessing:ve,executionState:he,status:g,input:d,setInput:m,onSubmit:on,showFileList:S,setShowFileList:v,fileSearchQuery:fe,setFileSearchQuery:ye,onCommand:pn,outputTokens:Ze,contextUsage:et,tasteLearning:gt,shareInfo:ot,showShareNotification:lt,unshareNotificationMessage:dt,updateStatus:w,updateFailedInfo:s,currentProvider:B,showProviderInfo:re,permissionMode:ht,onToggleAutoAccept:nn,hintMessage:Et,historyManager:De.current,pendingExitKey:$t,onResetPendingExitKey:Ot,onDoubleEscapeEmpty:en,retryAttempt:f,onAltP:()=>$(!0)}),I&&q.createElement(K,{marginY:1},q.createElement(Kg,{onSelect:Nn,onCancel:$n,currentProvider:B})),N&&q.createElement(K,{marginY:1},q.createElement(Vg,{onSelect:Dn,onCancel:On,currentModel:Q})),C&&q.createElement(K,{marginY:1},q.createElement(Vm,{onCancel:()=>k(!1)})),R&&q.createElement(K,{marginY:1},q.createElement(Ig,{onClose:()=>D(!1)})),O&&q.createElement(K,{marginY:1},q.createElement(ih,{onClose:En})),Tt&&Bt.current&&q.createElement(K,{marginY:1},q.createElement(Yg,{checkpoints:Bt.current.listCheckpoints(),onSelect:dn,onCancel:mn})),U&&q.createElement(K,{marginY:1},q.createElement(U.Component,{onSuccess:Ln,onCancel:Mn})),xt&&q.createElement(K,{marginY:1},q.createElement(Fp,{onComplete:Sn,onCancel:vn})),_e&&q.createElement(K,{marginY:1},q.createElement(Xg,{onClose:()=>{Ne(!1)}})))},"InteractiveCLI");dn(),fn();var dh=__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"),mh=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),gh=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),ph=__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"),hh=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),fh=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),yh=__name(()=>{fh()},"initializeTerminal"),wh=__name(async(e={})=>{const t=dh(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),yh(),mh(e)){const e=await Cd.isProjectInitialized(),t=e?await Cd.listSessions():[],n=gh({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=ph({options:e}),r=hh();Y(q.createElement(uh,{...n}),r)},"interactiveMode");_t(),Ot(),ln(),Nn(),Dn(),Zt();var Eh=null,bh=!1,Sh=new Set([Nl,$l,Ll]);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(bh)return;bh=!0;const e=__name(e=>{Eh?.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(),Eh=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:Eh.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 Mo&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof Fo&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof qo&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Oo&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof zo&&(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 vh=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===St.ANTHROPIC&&(r=await rn.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o=getEnvironmentContext(),s=await getMemoryContent([]),a=await getTasteContent(),i=generateSkillsXML(await loadAllSkillSummaries())||null,l=crypto.randomUUID(),u=await isTasteLearningEnabled(),d={[yt.PROJECT_SLUG]:Cd.getCurrentProjectDirName(),[yt.TASTE_LEARNING]:u.toString(),[yt.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(d[yt.OAUTH_TOKEN]=`Bearer ${r}`),{tools:e,config:o,memory:s,taste:a,skills:i,headers:d,sessionId:l}}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:wt.ALPHA.GENERATE,headers:t.headers,signal:r});return He.fromReadableStream(a).finalMessage()}async function executeToolCall(e,t,n){if(Sh.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 Mo||t instanceof Fo||t instanceof qo||t instanceof Oo||t instanceof zo)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 Tl({baseUrl:o}),a=[{role:"user",content:t}],i=await setupConversationContext();let l=0,u="";for(;l<vh;){if(l++,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&&(u+=d),0===o.length)break;const m=[];for(const e of o){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);m.push(t)}a.push({role:"assistant",content:e.content}),a.push({role:"user",content:m})}return l>=vh&&process.stderr.write(`Warning: Reached maximum conversation turns (${vh}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),u}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery"),jt();var Ch=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),kh=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),Ph=__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"),Th=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),Ah=__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=Ah(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=Ch(e);await kh();const r=Ph(t),o=Th({options:t,runtimeOptions:r,initialPrompt:n});wh(o)}__name(interactiveModeAction,"interactiveModeAction"),_t(),xn(),Sr(),Vr(),globalThis.COMMAND_CODE_CWD=process.cwd();var xh=__name(()=>process.cwd(),"getCwd"),Ih=__name(()=>process.argv.slice(2),"getArgs"),_h=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),Nh=__name(()=>{const e=xh(),t=Ih(),n=_h(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){Nh(),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"),_t(),Ot(),xn(),Wn(),Rn();var $h=getPackageJson(),Rh=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=$h.version,t=getInvokedCommandName(),n=Ug.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(te.bold("Command Code")+te.gray(` v${e}`)),console.log(te.gray(Og)),console.log(),console.log(te.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(te.bold("Options"));for(const e of Fg){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Lg)+te.gray(e.description))}console.log(),console.log(te.bold("Commands"));for(const e of jg){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Lg)+te.gray(e.description))}console.log(),console.log(te.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Lg)+te.gray(e.description));console.log(),console.log(te.bold("Keyboard Shortcuts"));for(const e of Mg)console.log(" "+e.key.padEnd(Lg)+te.gray(e.description));console.log(),console.log(te.bold("Examples"));for(const e of qg){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Lg)+te.gray(e.description))}console.log(),console.log(te.cyan("❯")+" "+te.gray(zg.replace(/cmd/,t))),console.log(),console.log(te.bold("Links"));for(const e of Bg)console.log(" "+e.key.padEnd(Lg)+te.cyan(e.description));console.log()}function createProgram(){const e=new ke;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version($h.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 Pe("--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",Rh,[]).addOption(new Pe(ht).hideHelp()).addOption(new Pe(ft).hideHelp()).addOption(new Pe("-d, --debug","Enable debug mode").hideHelp()).addOption(new Pe("--local","Use local server").hideHelp()).addOption(new Pe("--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"),_t(),Sr();var Dh=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=h.platform(),n=h.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(){Dh||(Dh=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=De("Opening GitHub issues...").start();try{await se(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"),_t(),__name(openGitHubIssue,"openGitHubIssue");var Oh=new ke("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);_t();var Lh=new ke("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});_t();var Mh=new ke("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(q.createElement(Jp,{verbose:e.verbose,text:e.text}));await t()});_t(),Ot(),xn(),Sr();var Fh=new ke(Ct.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{const{unmount:e}=Y(q.createElement(Dp,{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:hr.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 ke("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 Pe("-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(te.red(`Error: Invalid server name '${e}'`)),console.error(te.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(te.red(`Error: Invalid transport type '${n.transport}'`)),console.error(te.gray("Valid options: stdio, http")),process.exit(1));let a=!1;if("http"===n.transport){t||(console.error(te.red("Error: URL is required for http transport")),console.error(te.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(te.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(te.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(te.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(te.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(te.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${kr}/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(te.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(te.gray(` ${e}`))},"onStatus")});o.success?console.log(te.green("✓ Successfully authenticated")):(a=!0,console.log(te.yellow(`Warning: Authentication failed: ${o.error}`)),console.log(te.gray("You can retry with: cmd mcp auth "+e)),console.log(te.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,a=process.argv.indexOf("--");let i,l=[];if(-1!==a){const e=process.argv.slice(a+1);0===e.length&&(console.error(te.red("Error: Command is required for stdio transport")),console.error(te.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),i=e[0],l=e.slice(1)}else if(t){i=t;const n=o.indexOf(e);-1!==n&&o.length>n+2&&(l=o.slice(n+2))}else console.error(te.red("Error: Command is required for stdio transport")),console.error(te.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(te.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);s={transport:"stdio",enabled:!0,command:i,...l.length>0&&{args:l},...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(te.yellow(`✓ Added MCP server '${e}' to ${i} config (authentication pending)`)):console.log(te.green(`✓ Added MCP server '${e}' to ${i} config`)),"http"===s.transport)console.log(te.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(te.gray(` Command: ${e}`))}console.log(""),console.log(te.cyan("Next steps:")),console.log(te.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(te.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(te.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(te.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(te.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new ke("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(te.yellow("\nNo MCP servers configured\n")),console.log(te.gray("Add a server with:")),console.log(te.gray(" cmd mcp add --transport http <name> <url>")),console.log(te.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(te.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(te.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(te.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?te.green("enabled"):te.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?te.green("✓"):te.red("✗"):o.config.headers||o.config.env?te.green("✓"):te.gray("-"),console.log(` ${te.white(o.name.padEnd(t))} ${te.cyan(o.config.transport.padEnd(n))} ${te.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(te.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new ke("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(te.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(te.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${te.dim("Scope:")} ${r}`),console.log(` ${te.dim("Transport:")} ${n.transport}`),console.log(` ${te.dim("Status:")} ${n.enabled?te.green("enabled"):te.gray("disabled")}`),"http"===n.transport){if(console.log(` ${te.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${te.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(` ${te.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${te.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${te.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(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new ke("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Pe("-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(te.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(te.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(te.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(te.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new ke("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 Pe("-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(te.red(`Error: Invalid server name '${e}'`)),console.error(te.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(te.red("Error: Invalid JSON")),console.error(te.gray("Make sure to quote the JSON string properly")),console.error(te.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=Yl.safeParse(o);if(!a.success){console.error(te.red("Error: Invalid server configuration"));for(const e of a.error.issues)console.error(te.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const i=a.data;let l=!1;if("http"!==i.transport||i.url||(console.error(te.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==i.transport||i.command||(console.error(te.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:i,scope:n.scope}),i.oauth){console.log(te.cyan("Starting OAuth authentication...")),console.log(te.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(te.gray(` ${e}`))},"onStatus")});n.success?console.log(te.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(te.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(te.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(te.gray("Or authenticate via the /mcp menu in a session")))}const u="user"===n.scope?"global":"project"===n.scope?"project":"local";if(l?console.log(te.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(te.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===i.transport)console.log(te.gray(` URL: ${i.url}`));else{const e=[i.command,...i.args||[]].join(" ");console.log(te.gray(` Command: ${e}`))}console.log(""),console.log(te.cyan("Next steps:")),console.log(te.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new ke("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(te.yellow("No servers with stored authentication."));console.log(te.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?te.yellow("expired"):te.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(te.red("Error: Server name is required")),console.error(te.gray(`Usage: ${n} mcp auth <server>`)),console.error(te.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(te.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(te.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(te.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(te.gray(" A refresh token is available for re-authentication"));else{if(console.log(te.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(te.gray(` Expires in ${e} minutes`))}t.scope&&console.log(te.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(te.green(`✓ Cleared authentication for '${e}'`)):console.log(te.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(te.red(`Error: MCP server '${e}' not found`)),console.error(te.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(te.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(te.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(te.cyan(`Authenticating with '${e}'...`)),console.log(te.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,o,{onStatus:__name(e=>{console.log(te.gray(` ${e}`))},"onStatus")});if(s.success)return console.log(te.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(te.gray("Restart the session to connect with the authenticated server."));console.error(te.red(`\nError: Authentication failed: ${s.error}`)),console.log(te.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new ke("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(h.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${n}`)}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"taste.md")}_t(),_t(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),_t(),__name(listMcpCommand,"listMcpCommand"),_t(),__name(getMcpCommand,"getMcpCommand"),_t(),__name(removeMcpCommand,"removeMcpCommand"),_t(),__name(addJsonMcpCommand,"addJsonMcpCommand"),_t(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),_t(),Ot(),_t(),_t(),_t(),Ot(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),_t(),_t();var Uh=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||Uh.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:Uh.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(Uh.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(!Uh.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],l=parseFloat(i);if(isNaN(l))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;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==a.index?o.substring(0,a.index).trim():o.trim();return u&&0!==u.length?(u.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r)}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=t.slice(n+1,n+4),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?te.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(te.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`${te.green(e)} ${te.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?te.red(t.summary):te.yellow(t.summary),"",...formatIssueGroup(r,te.red,te.bold(te.red("Errors:"))),...formatIssueGroup(o,te.yellow,te.bold(te.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"),_t(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var jh=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;jh.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 Bh=/^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}):Bh.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 qh=__name(e=>"local-global"===e?"global":"project","locationLabel"),zh=__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 b(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${qh(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});b(o)&&r.push({path:o,displayName:"taste.md"});const s=(await R.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>b(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 R.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await R.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 zh({file:"all",error:`No taste files found in ${qh(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 zh({file:"all",error:`No taste files found in ${qh(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 b(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):zh({file:"all",error:`No taste directory found in ${qh(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"),_t(),Sr(),__name(resolveConflictStrategy,"resolveConflictStrategy");var Wh=te.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(`${te.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?`${te.dim(t[1])}${te.green(t[2])}${te.white(t[3]??"")}${t[4]?te.dim(t[4]):""}`:te.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${te.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 Hh=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return ot(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:Hh})}function getProfileLink(e){return ot(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:Hh})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return rt(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(te.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(`${te.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(te.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new ke("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 ${te.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(`${te.green(Se.tick)} All ${te.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(te.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(te.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(te.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 R.readFile(t,"utf-8");const r=migrateHeader({content:n});return r===n?n:(await R.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(Tm)?e:Tm+"\n\n"+e:Tm+"\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"),_t(),_t(),_t(),_t(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),_t(),__name(formatPackage,"formatPackage"),_t(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var Vh="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:Vh,category:e.name});return b(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await R.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:Vh});if(!b(e))return[];const t=await R.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:Vh,category:t});return b(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:Vh});await R.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:Vh,category:n.category}),s=e.dirname(o);await R.mkdir(s,{recursive:!0});const a=formatPackage({pkg:n});await R.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"),_t(),_t();var Gh="local-project";function prefixHeaderIfNeeded(e){return!e||e.trim().startsWith(Tm)?e:Tm+"\n\n"+e}async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!b(n))return null;const r=migrateHeader({content:await R.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()},l=[...s,...a].join("\n").trim();return""===l&&await R.rm(n,{force:!0}),""!==l&&await R.writeFile(n,l+"\n","utf-8"),i}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:Gh}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:Gh,category:n}),a=e.dirname(s);return b(a)&&await R.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 R.writeFile(n,e.trim()+"\n","utf-8")}let s="";b(n)&&(s=await R.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await R.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:Gh,category:n.category}),a=e.dirname(s);await R.mkdir(a,{recursive:!0});const i=formatPackage({pkg:n});await R.writeFile(s,i,"utf-8");const l=`# ${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+=l.trim()+t,void await R.writeFile(r,e.trim()+"\n","utf-8")}let u="";b(r)&&(u=await R.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await R.writeFile(r,u.trim()+"\n","utf-8")}__name(prefixHeaderIfNeeded,"prefixHeaderIfNeeded"),__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var Kh="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:Kh,category:e.name});return b(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:Kh});if(!b(e))return[];const t=[],n=getRootTasteFile({target:Kh});if(b(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await R.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:Kh});await R.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:Kh}),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:Kh});return b(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!b(n))return;const r=await R.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 l=formatPackage({pkg:r}),u=new Blob([l],{type:"text/markdown"}),d=new File([u],"taste.md",{type:"text/markdown"});if(i.append("files[taste.md]",d),"category"===s)return i;const m=getTastePath({target:"local-project"}),g=e.join(m,r.category);if(!b(g))return i;const p=getCategoryTasteFile({target:"local-project",category:r.category});if(!b(p))return i;const h=await R.readFile(p,"utf-8"),f=new Blob([h],{type:"text/markdown"}),y=new File([f],"taste.md",{type:"text/markdown"});return i.append(`files[${r.category}/taste.md]`,y),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(b(a)){const e=await R.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:hr.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}${wt.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}${wt.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:hr.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()}${wt.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:hr.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()}${wt.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()}${wt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,l=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:a});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:l.status,extra:{"package.count":t.length}}),await l.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${wt.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 R.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 ke("list").alias("ls").option("-g, --global","List global packages").addOption(new Pe("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Pe("--staging","Use staging environment").hideHelp()).description(`List available packages ${te.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"),_t(),_t(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),Ot(),_t(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),Sr(),_t(),Sr(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),_t(),Ot(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),xn(),__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 Jh={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?Jh.remote:e.global?Jh.global:Jh.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` ${te.white(e.category)}${e.isPublic?te.green(" [public]"):""}${e.isPublic&&e.starCount?te.yellow(` ${Se.star}${e.starCount}`):""}${e.downloadCount?te.gray(` ${Se.arrowDown}${e.downloadCount}`):""}${n}${te.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?De(`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${Wh} Packages`),console.log(`${te.gray("⎿")} ${te.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(te.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(te.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 R.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 tt([{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"),_t(),_t(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var Qh=new Set(["local-project","local-global","remote-project","remote-user"]);async function open7(e){const{package:t,target:n}=e;if(!Qh.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=st.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 ke("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 ${te.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 se(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${te.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(`${te.green(Se.tick)} Opened ${te.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"),_t(),_t(),_t(),_t();var Yh=null,Zh=!1;function setActiveSpinner(e){Yh=e}function stopActiveSpinner(e){Yh&&(Yh.stop(e),Yh=null)}function setPrompted(e){Zh=e}function wasPrompted(){return Zh}function beginPrompt(e,t){stopActiveSpinner(),Te.intro(te.dim(e)),t&&Te.log.message(te.dim(t)),setPrompted(!0)}function handleCancel(e){Te.isCancel(e)&&(Te.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Te.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Te.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),Te.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${te.green(`'${t}'`)} from ${n}`,s),Te.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${te.dim(`(from ${n})`)}`);const a=await Te.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),Te.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${te.green(`'${t}'`)} to global`,o),Te.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await Te.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),Te.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${te.green(`'${t}'`)} from global`,o),Te.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await Te.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),Te.log.warn("Non-interactive terminal detected, skipping push"),"skip";const a=ot(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${te.green(`'${t}'`)} to ${n}`,s),Te.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),Te.log.info(`Current package: ${te.cyan(a)} ${te.dim("(review)")}`);const i=await Te.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 l=i;return startStrategySpinner(l),l}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),Te.log.warn("Non-interactive terminal detected, skipping push"),"skip";const a=ot(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${te.green(`'${t}'`)} to ${n}`,s),Te.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),Te.log.info(`Current package: ${te.cyan(a)} ${te.dim("(review)")}`);const i=await Te.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 l=i;return startStrategySpinner(l),l}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 l=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=l}async function processPackage(e){const{tastePkg:t,result:n}=e;try{await executePackageStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullProjectPackage(e){const{files:t,packageName:n,owner:r,overwrite: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 l=t.filter(e=>"taste.md"!==e.file);for(const e of l){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 l={category:n,learnings:parseTasteContent(i.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,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"),_t(),_t(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),_t(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var Xh=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),ef=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),tf=__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 l=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=l}async function pullSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePullStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pull(e){const{packages:t,source:n,overwrite:r=!1,strategy:o}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return Xh({pkg:"all",error:`Invalid source: ${n}`});const s=tf(n);let a;try{a="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return Xh({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===a.length)return Xh({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 l=t.length>0?a.filter(e=>t.includes(e.category)):a;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=ef();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:o,overwrite:r,result:u});return u}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 Xh({pkg:n,error:"Taste package not found in remote"});const{type:i,files:l}=a,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy: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=ef();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return Xh({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Te.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?te.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${te.green(a)}Replaced ${te.green(`'${t}'`)} taste package in project`+i;if(s){const e=formatMergeParts(s);return`${te.green(a)}Pulled ${te.green(`'${t}'`)} taste package from ${n} ${te.gray(`(${e.join(", ")})`)}`+i}return`${te.green(a)}Pulled ${te.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"}`,l=[];return s.length>0&&l.push(wrapLine(`${te.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${te.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&l.push(wrapLine(`${te.dim("Skipped")} (${o.length}) ${te.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Te.log.message(l.join("\n")),Te.outro(`${i} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${te.green(Se.tick)} ${i} from ${n}`),l.length>0&&console.log(l.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(te.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new ke("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 Pe("--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 Pe("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${te.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(De("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(De("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 Tl({baseUrl:e}),n=await t.get({endpoint:wt.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 Te.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(`${te.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,l=wasPrompted()?"":`${Se.tick} `;if(!i)return logResult2(`${te.green(l)}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?` ${te.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${te.green(l)}Replaced ${s} in ${i}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${te.green(l)}Pushed ${s} to ${i}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),p=g.length>0?` ${te.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${te.green(l)}Pushed ${s} to ${i}${p}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],o=t.filePaths?.[r],s=n.remote&&o,a=s?o:"global",i=wasPrompted()?"":`${Se.tick} `,l=!s&&o?te.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${te.green(i)}Replaced ${te.green(`'${r}'`)} taste package in ${a}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${te.green(i)}Pushed ${te.green(`'${r}'`)} taste package to ${a} ${te.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${te.green(i)}Pushed ${te.green(`'${r}'`)} taste package to ${a}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",o=wasPrompted()?"":`${Se.tick} `;return logResult2(wrapLine(`${te.green(o)}Pushed ${te.green(t.packagesPushed.length)} taste packages ${te.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(te.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(`${te.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&a.push(wrapLine(`${te.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&a.push(wrapLine(`${te.dim("Skipped")} (${r.length}) ${te.dim(r.join(", "))}`,4)),a.length>0&&Te.log.message(a.join("\n"));const i=`${s} ${1===s?"package":"packages"}`;Te.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(`${te.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${te.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${te.dim("Skipped")} (${n.length}) ${te.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"),_t(),__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"),_t(),xn(),_t(),Ot(),__name(fetchUserNamespaces,"fetchUserNamespaces"),_t(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),_t(),_t();var nf=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),rf=__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",l=o.reduce((e,t)=>e+t.learnings.length,0),u=rf(r.files);return"project"!==i?promptTypeMismatchStrategy({packageName:s,owner:a,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:s,owner:a,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,isPublicExplicitlySet:a,flagStrategy:i}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l});if("skip"===await resolvePushAllStrategy({flagStrategy:i,overwrite:o,existingProject:d,packagesToPush:n,projectName:l,owner:r}))return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:a?s:d?.isPublic??!1});for(const e of n)u.packagesPushed.push(e.category),u.filePaths[e.category]=`${r}/${l}`,u.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&u.overwritten.push(...n.map(e=>e.category)),u}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return nf({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var of=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),sf=__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 af=__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,l="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),u=await resolveSinglePushStrategy({flagStrategy:r,overwrite:o,existingPkg:l,target:n,tastePkg:t});if("skip"===u)return void i.skipped.push(t.category);if("overwrite"===u&&(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"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:s,isPublic:a}),i.packagesPushed.push(t.category),i.mergeDetails[t.category]=r}const d=af({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 of({pkg:"all",error:"No taste directory found in project"});const i=await getAllPackages2();if(0===i.length)return of({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:i,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?i.filter(e=>n.includes(e.category)):i;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:a}):of({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return of({pkg:"all",error:`Invalid target: ${r}`});const m=sf();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:a,overwrite:o,userOwner:d,isPublic:s,result:m});return m}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 of({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:i}),filePath:`${i.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return of({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:a,overwrite:o,existingPkg:u,target:"remote-project",tastePkg:i}),m=t?s:u?.isPublic??!1,g=sf();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:i,owner:n,isPublic:m}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:i,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),g.packagesPushed.push(r),g.mergeDetails[r]=t}return g.filePaths[r]=`${n}/${r}`,g}async function pushRemote(e){const{packageName:t}=e;if(!exists())return of({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return of({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 Te.select({message:"Owner",options:r,initialValue:t});return Te.isCancel(o)&&(Te.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new ke("push").description(`Push taste packages to remote ${te.dim("(commandcode.ai)")} or global ${te.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 Pe("--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 Pe("--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"),_t(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var cf=__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};Te.intro(te.dim(`pushing ${t}`)),setPrompted(!0);const o=Te.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),Te.outro(te.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(te.dim(` Pushing ${s} to ${a} (remote)${i}`)),console.log(""),setActiveSpinner(De("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:cf(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}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:cf(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=Te.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(De("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"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(te.dim(` Pushing ${i} to ${l}${u}`)),console.log(""),setActiveSpinner(De("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 ke(Ct.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),e}function formatVersion(e,t,n=!1){const r=n?re.bold(re.green(t)):re.white(t);return`${re.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${re.bold(re.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(re.dim(`Run ${re.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(re.dim("Try updating manually:")),console.log(re.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(re.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=De("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.stop(),console.log(""),console.log(`${re.green(Se.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${re.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=De("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:hr.UPDATE_COMMAND,heading:"CLI update failed","update.current_version":t.currentVersion,"update.target_version":t.latestVersion}}),showManualUpdateHint(t.latestVersion),await shutdownTelemetry(),process.exit(1)),e.succeed(`Updated to v${t.latestVersion}`),showUpdateSuccessHint()):e.succeed(`Up to date ${re.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(resolveStrategyLabel,"resolveStrategyLabel"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),__name(createTasteCommand,"createTasteCommand"),_t(),Ot(),Sr(),__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 lf=new ke("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);_t();var uf=__name((e,t)=>`${Se.info} ${e}: ${re.cyan(t)}`,"formatInfoLine"),df=__name(e=>re.bold(`${e}:`),"formatSectionHeader"),mf=__name(e=>re.red(e),"formatError"),gf=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),pf=__name(e=>["",df("User Information"),uf("Name",e.name),uf("Email",e.email),uf("Username",e.userName)],"buildUserOutput"),hf=__name(e=>["",df("Organization"),uf("Name",e.name),uf("Login",e.login)],"buildOrgOutput"),ff=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),yf=__name((e,t)=>{ff(pf(e)),t&&ff(hf(t)),console.log("")},"displayUserInfo"),wf=__name(e=>null!==e&&e.length>0,"validateApiKey"),Ef=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=De("Fetching user information...").start();try{const t=await getAuthKey();wf(t)||(e.fail(mf('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();Ef(n)||(e.fail(mf("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),yf(n.user,n.org)}catch(t){e.fail(mf(`Error: ${gf(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var bf=new ke("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var Sf=createProgram();Sf.action(interactiveModeAction),Sf.addCommand(Lh),Sf.addCommand(Mh),Sf.addCommand(bf),Sf.addCommand(lf),Sf.addCommand(Oh),Sf.addCommand(createTasteCommand()),Sf.addCommand(createMcpCommand()),Sf.addCommand(Fh),Sf.addCommand(so),Sf.addCommand(uo),Sf.addCommand(wo),setupCommanderHooks(Sf),Sf.parse();
|